diff --git a/client/src/components/Button.tsx b/client/src/components/Button.tsx index cca3db9..0a588d6 100644 --- a/client/src/components/Button.tsx +++ b/client/src/components/Button.tsx @@ -1,30 +1,55 @@ -import type { ButtonHTMLAttributes } from "react"; +import { type ButtonHTMLAttributes } from "react"; -type Variant = "primary" | "secondary" | "danger"; +type Variant = "primary" | "secondary" | "ghost" | "danger"; +type Size = "sm" | "md" | "lg"; interface ButtonProps extends ButtonHTMLAttributes { variant?: Variant; + size?: Size; + loading?: boolean; } export function Button({ variant = "primary", + size = "md", + loading, className = "", children, + disabled, type = "button", ...props }: ButtonProps) { - const base = - "inline-flex items-center justify-center gap-2 rounded-[10px] px-4 py-2.5 text-sm font-semibold transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"; const variants: Record = { - danger: - "border border-[rgba(239,68,68,0.3)] bg-[rgba(239,68,68,0.15)] text-[#F87171] hover:bg-[rgba(239,68,68,0.25)]", - primary: "glow-btn", - secondary: - "border border-[var(--border)] bg-[var(--bg-elevated)] text-[var(--text-primary)] hover:border-[var(--border-hover)] hover:bg-[var(--bg-hover)]", + danger: "btn btn-danger", + ghost: "btn btn-ghost", + primary: "btn btn-primary", + secondary: "btn btn-secondary", + }; + const sizes: Record = { + lg: "btn-lg", + md: "", + sm: "btn-sm", }; return ( - ); diff --git a/client/src/components/ConfirmModal.tsx b/client/src/components/ConfirmModal.tsx new file mode 100644 index 0000000..fe47878 --- /dev/null +++ b/client/src/components/ConfirmModal.tsx @@ -0,0 +1,65 @@ +import { useEffect } from "react"; + +interface Props { + open: boolean; + title: string; + message: string; + confirmLabel?: string; + destructive?: boolean; + onConfirm: () => void; + onCancel: () => void; +} + +export function ConfirmModal({ + open, + title, + message, + confirmLabel = "Confirm", + destructive = false, + onConfirm, + onCancel, +}: Props) { + useEffect(() => { + if (!open) { + return; + } + + const handler = (event: KeyboardEvent) => { + if (event.key === "Escape") { + onCancel(); + } + }; + + document.addEventListener("keydown", handler); + return () => document.removeEventListener("keydown", handler); + }, [onCancel, open]); + + if (!open) { + return null; + } + + return ( +
+
event.stopPropagation()}> +

+ {title} +

+

+ {message} +

+
+ + +
+
+
+ ); +} diff --git a/client/src/components/PlanBadge.tsx b/client/src/components/PlanBadge.tsx index 8545550..db67c66 100644 --- a/client/src/components/PlanBadge.tsx +++ b/client/src/components/PlanBadge.tsx @@ -1,35 +1,22 @@ -import type { HTMLAttributes } from "react"; - -import { normalizePlan } from "@/lib/plan"; - -type PlanBadgeProps = HTMLAttributes & { - plan: string; -}; - -export function PlanBadge({ plan, className = "", ...props }: PlanBadgeProps) { - const normalizedPlan = normalizePlan(plan); - const isPro = normalizedPlan === "pro"; +export function PlanBadge({ plan }: { plan: string }) { + const isPro = plan?.toLowerCase() === "pro"; return ( - {isPro ? "✦ PRO" : "FREE"} + {isPro ? "PRO" : "FREE"} ); } diff --git a/client/src/components/StatusBadge.tsx b/client/src/components/StatusBadge.tsx index 7a3f758..73ea57f 100644 --- a/client/src/components/StatusBadge.tsx +++ b/client/src/components/StatusBadge.tsx @@ -1,18 +1,14 @@ -import type { InvoiceStatus, ProposalStatus } from "@/types/invoice"; +type Status = "DRAFT" | "SENT" | "PAID" | "OVERDUE" | "ACCEPTED" | "DECLINED"; -interface StatusBadgeProps { - status: InvoiceStatus | ProposalStatus; -} - -const statusClasses: Record = { - ACCEPTED: "badge-paid", - DECLINED: "badge-overdue", - DRAFT: "badge-draft", - OVERDUE: "badge-overdue", - PAID: "badge-paid", - SENT: "badge-sent", +const map: Record = { + ACCEPTED: "badge badge-accepted", + DECLINED: "badge badge-declined", + DRAFT: "badge badge-draft", + OVERDUE: "badge badge-overdue", + PAID: "badge badge-paid", + SENT: "badge badge-sent", }; -export function StatusBadge({ status }: StatusBadgeProps) { - return {status}; +export function StatusBadge({ status }: { status: string }) { + return {status}; } diff --git a/client/src/components/Toast.tsx b/client/src/components/Toast.tsx index 40c2fd8..4b3be65 100644 --- a/client/src/components/Toast.tsx +++ b/client/src/components/Toast.tsx @@ -1,34 +1,48 @@ -type ToastProps = { - message: string; - onDismiss: () => void; - tone?: "success" | "error"; +type ToastType = "success" | "error" | "info"; + +const icons: Record = { + error: "✕", + info: "·", + success: "✓", }; -const toneClasses = { - success: "var(--success)", - error: "#F87171", +const colors: Record = { + error: "var(--red)", + info: "var(--accent)", + success: "var(--green)", }; -export function Toast({ message, onDismiss, tone = "success" }: ToastProps) { +export function Toast({ + message, + type = "success", + onDismiss, +}: { + message: string; + type?: ToastType; + onDismiss: () => void; +}) { return (
- {tone === "error" ? "!" : "✓"} + {icons[type]} {message}
-
-
-

- Dashboard -

-
-

- Financial snapshot -

- +
+
+
+ InvoiceFlow + / + Dashboard +
+
+ + {initials} + + {user ? : null}
-
- {error &&
{error}
} - -
- {loading - ? Array.from({ length: 4 }).map((_, index) => ( -
- - - -
- )) - : statCards.map((card, index) => { - const Icon = card.icon; +
+ + + IF + + InvoiceFlow + + +
- return ( -
-
- -
-

- {card.label} -

-

{card.value}

-
- ); - })} -
- -
+
+
-

- Monthly revenue -

-

- Paid invoices over the last 6 months -

+

+ {greeting}, {firstName} +

+

Here's your overview for today.

-
+ {error ? ( +
+ ⚠ {error} + +
+ ) : null} + + {!loading && (stats?.overdue ?? 0) > 0 ? ( +
+ ⚠ {formatCurrency(stats?.overdue ?? 0)} in overdue invoices + + Review → + +
+ ) : null} + +
{loading ? ( - + Array.from({ length: 4 }).map((_, index) => ( +
+ + +
+ )) ) : ( - - - - `$${Number(value) / 1000}k`} - tickLine={false} - width={48} - /> - [formatCurrency(Number(value)), "Revenue"]} - /> - - + <> +
+
+

Total Revenue

+ +
+

+ {formatCurrency(revenue)} +

+
+
+
+

Outstanding

+ +
+

+ {formatCurrency(outstanding)} +

+
+
+
+

Overdue

+ +
+

0 ? "var(--red)" : "var(--text-1)" }} + > + {formatCurrency(overdue)} +

+
+
+
+

Drafts

+ +
+

{drafts}

+
+ )} -
-
- -
-
-
-

- Recent invoices -

-

- The 5 most recent invoice records -

-
- - View all +
+ +
+ + + New Invoice + + + + New Proposal + + + View All Invoices
- {loading ? ( -
- {Array.from({ length: 5 }).map((_, index) => ( - - ))} +
+
+

Revenue

+ Last 6 months +
+
+ {loading ? ( + + ) : ( + + + + `$${Number(value) / 1000}k`} + tickLine={false} + width={48} + /> + [formatCurrency(Number(value)), "Revenue"]} + /> + + + )} +
+
+ +
+
+

Recent invoices

+ + View all → +
- ) : stats && stats.recentInvoices.length > 0 ? (
- - +
+ - {["Invoice", "Client", "Amount", "Status", "Date", "Actions"].map((label) => ( - - ))} + + + + + + - {stats.recentInvoices.map((invoice) => ( - - - - - - - - - ))} + {loading + ? Array.from({ length: 5 }).map((_, index) => ( + + + + + + + + + )) + : stats?.recentInvoices.map((invoice) => ( + navigate(`/invoices/${invoice.id}`)} + > + + + + + + + + ))}
- {label} - InvoiceClientAmountStatusDate
- {invoice.number} - - {invoice.client} - - {formatCurrency(invoice.amount, invoice.currency)} - - - - {formatDate(invoice.date)} - -
- - - - -
-
+ + + + + + + + + + + +
{invoice.number}{invoice.client}{formatCurrency(invoice.amount, invoice.currency)} + + {formatDate(invoice.date)} + +
- ) : ( -
-

- No invoices yet -

-

- Revenue, outstanding totals, and invoice activity will appear here. -

-
- )} -
+ +
diff --git a/client/src/pages/InvoiceDetailPage.tsx b/client/src/pages/InvoiceDetailPage.tsx index 87e43b7..bab979b 100644 --- a/client/src/pages/InvoiceDetailPage.tsx +++ b/client/src/pages/InvoiceDetailPage.tsx @@ -1,21 +1,97 @@ -import { useEffect, useState } from "react"; -import { Link, useParams } from "react-router-dom"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useNavigate, useParams } from "react-router-dom"; import { Button } from "@/components/Button"; import { StatusBadge } from "@/components/StatusBadge"; import { Toast } from "@/components/Toast"; +import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar"; import { invoicesApi } from "@/lib/api/invoices"; import { Page } from "@/pages/Page"; -import type { Invoice } from "@/types/invoice"; +import type { Invoice, InvoiceStatus } from "@/types/invoice"; + +const formatDate = (dateString: string) => new Date(dateString).toLocaleDateString(); + +const formatCurrency = (amount: number, currency: string) => + new Intl.NumberFormat("en-US", { + currency, + style: "currency", + }).format(amount); + +function CopyIcon() { + return ( + + ); +} + +function SkeletonBlock({ className = "" }: { className?: string }) { + return
; +} + +function Timeline({ status }: { status: InvoiceStatus }) { + const steps = status === "OVERDUE" ? ["DRAFT", "SENT", "OVERDUE"] : ["DRAFT", "SENT", "PAID"]; + const currentIndex = steps.indexOf(status); + + return ( +
+ {steps.map((step, index) => { + const completed = index < currentIndex; + const current = index === currentIndex; + const overdue = current && step === "OVERDUE"; + + return ( +
+
+ + {index + 1} + + + {step} + +
+ {index < steps.length - 1 ? : null} +
+ ); + })} +
+ ); +} export function InvoiceDetailPage() { + const navigate = useNavigate(); const { id } = useParams(); const [invoice, setInvoice] = useState(null); const [loading, setLoading] = useState(true); const [downloadLoading, setDownloadLoading] = useState(false); + const [downloaded, setDownloaded] = useState(false); const [sendLoading, setSendLoading] = useState(false); + const [copied, setCopied] = useState(false); const [toast, setToast] = useState(null); const [error, setError] = useState(null); + const copiedTimer = useRef(null); + const downloadedTimer = useRef(null); + const { + active: loadingBarActive, + complete: loadingBarComplete, + done: finishLoadingBar, + start: startLoadingBar, + } = useLoadingBar(); useEffect(() => { if (!id) { @@ -24,12 +100,25 @@ export function InvoiceDetailPage() { return; } - loadInvoice(id); + void loadInvoice(id); }, [id]); + useEffect( + () => () => { + if (copiedTimer.current !== null) { + window.clearTimeout(copiedTimer.current); + } + if (downloadedTimer.current !== null) { + window.clearTimeout(downloadedTimer.current); + } + }, + [], + ); + const loadInvoice = async (invoiceId: string) => { try { setLoading(true); + startLoadingBar(); const data = await invoicesApi.getById(invoiceId); setInvoice(data); setError(null); @@ -38,20 +127,10 @@ export function InvoiceDetailPage() { console.error("Error loading invoice:", err); } finally { setLoading(false); + finishLoadingBar(); } }; - const formatDate = (dateString: string) => { - return new Date(dateString).toLocaleDateString(); - }; - - const formatCurrency = (amount: number, currency: string) => { - return new Intl.NumberFormat("en-US", { - currency, - style: "currency", - }).format(amount); - }; - const handleDownloadPdf = async () => { if (!invoice) { return; @@ -68,6 +147,8 @@ export function InvoiceDetailPage() { link.click(); link.remove(); window.URL.revokeObjectURL(url); + setDownloaded(true); + downloadedTimer.current = window.setTimeout(() => setDownloaded(false), 2000); } catch (err) { setError("Failed to download invoice PDF"); console.error("Error downloading invoice PDF:", err); @@ -95,11 +176,64 @@ export function InvoiceDetailPage() { } }; + useEffect(() => { + const handler = (event: KeyboardEvent) => { + const target = event.target as HTMLElement | null; + const tagName = target?.tagName; + + if (tagName === "INPUT" || tagName === "TEXTAREA" || target?.isContentEditable) { + return; + } + + if (event.key.toLowerCase() === "e" && invoice) { + navigate(`/invoices/${invoice.id}/edit`); + } + + if (event.key.toLowerCase() === "d") { + void handleDownloadPdf(); + } + + if (event.key.toLowerCase() === "s" && invoice?.status === "DRAFT") { + void handleSendInvoice(); + } + + if (event.key === "Escape" || event.key === "Backspace") { + navigate("/invoices"); + } + }; + + window.addEventListener("keydown", handler); + return () => window.removeEventListener("keydown", handler); + }); + + const copyEmail = async () => { + if (!invoice) { + return; + } + + await navigator.clipboard.writeText(invoice.clientEmail); + setCopied(true); + if (copiedTimer.current !== null) { + window.clearTimeout(copiedTimer.current); + } + copiedTimer.current = window.setTimeout(() => setCopied(false), 1500); + }; + + const pageTitle = useMemo(() => invoice?.number ?? "Invoice", [invoice]); + if (loading) { return ( - -
- Loading invoice... + + +
+
+ + + +
+
+ +
); @@ -107,165 +241,139 @@ export function InvoiceDetailPage() { if (!invoice) { return ( - -
{error ?? "Invoice not found"}
- - Back to invoices - + +
⚠ {error ?? "Invoice not found"}
+
); } return ( - - {toast && setToast(null)} />} + + + {toast ? setToast(null)} /> : null} - {error &&
{error}
} + {error ?
⚠ {error}
: null}
- - Back to invoices - -
- - - - {invoice.status === "DRAFT" && ( - +
+ + {invoice.status === "DRAFT" ? ( + - )} -
-
-
-
-
- IF -
-
-

- Invoice -

-

- {invoice.number} -

-
-
- -
+
+ +
-
-
-

Client

-

- {invoice.clientName} -

-

- {invoice.clientEmail} -

-

- {invoice.clientAddress} -

-
-
+
+
+
-
Issue date
-
{formatDate(invoice.issueDate)}
-
-
-
Due date
-
{formatDate(invoice.dueDate)}
+

{invoice.clientName}

+
+

{invoice.clientEmail}

+ +
+

+ {invoice.clientAddress} +

-
-
Currency
-
{invoice.currency}
+
+ +

{invoice.number}

-
-
-
-

- Line Items -

+
+ {[ + ["Issue date", formatDate(invoice.issueDate)], + ["Due date", formatDate(invoice.dueDate)], + ["Currency", invoice.currency], + ].map(([label, value]) => ( +
+

{label}

+

{value}

+
+ ))}
-
- - + +
+
+ - - - - + + + + {invoice.lineItems.map((item) => ( - - - - - + + + + + ))}
- Description - - Qty - - Unit Price - - Amount - DescriptionQtyUnit PriceAmount
- {item.description} - - {item.quantity} - - {formatCurrency(item.unitPrice, invoice.currency)} - - {formatCurrency(item.amount, invoice.currency)} -
{item.description}{item.quantity}{formatCurrency(item.unitPrice, invoice.currency)}{formatCurrency(item.amount, invoice.currency)}
-
- -
-
- Subtotal - {formatCurrency(invoice.subtotal, invoice.currency)} -
-
- Tax ({invoice.taxRate}%) - {formatCurrency(invoice.taxAmount, invoice.currency)} -
-
- Total - - {formatCurrency(invoice.total, invoice.currency)} - -
-
-
- {invoice.notes && ( -
-

Notes / Terms

-

- {invoice.notes} -

+ {invoice.notes ? ( +
+

Notes

+

+ {invoice.notes} +

+
+ ) : null}
- )} + + +
); } diff --git a/client/src/pages/InvoiceFormPage.tsx b/client/src/pages/InvoiceFormPage.tsx index dcceffc..00f6dcf 100644 --- a/client/src/pages/InvoiceFormPage.tsx +++ b/client/src/pages/InvoiceFormPage.tsx @@ -1,12 +1,14 @@ -import { useState, useEffect } from "react"; -import { useNavigate, useParams } from "react-router-dom"; -import { useForm, useFieldArray, Controller, SubmitHandler } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; +import { useEffect, useRef, useState } from "react"; +import { type SubmitHandler, useFieldArray, useForm } from "react-hook-form"; +import { useNavigate, useParams } from "react-router-dom"; import { z } from "zod"; -import { invoicesApi } from "@/lib/api/invoices"; + import { Button } from "@/components/Button"; +import { TopLoadingBar, useLoadingBar } from "@/components/TopLoadingBar"; +import { invoicesApi } from "@/lib/api/invoices"; import { Page } from "@/pages/Page"; -import type { CreateInvoiceData, UpdateInvoiceData, Invoice } from "@/types/invoice"; +import type { CreateInvoiceData, UpdateInvoiceData } from "@/types/invoice"; const lineItemSchema = z.object({ description: z.string().min(1, "Description is required"), @@ -15,18 +17,19 @@ const lineItemSchema = z.object({ }); const invoiceSchema = z.object({ - clientName: z.string().min(1, "Client name is required"), - clientEmail: z.string().email("Valid email is required"), clientAddress: z.string().min(1, "Client address is required"), - issueDate: z.string().min(1, "Issue date is required"), - dueDate: z.string().min(1, "Due date is required"), + clientEmail: z.string().email("Valid email is required"), + clientName: z.string().min(1, "Client name is required"), currency: z.string().default("USD"), + dueDate: z.string().min(1, "Due date is required"), + issueDate: z.string().min(1, "Issue date is required"), + lineItems: z.array(lineItemSchema).min(1, "At least one line item is required"), notes: z.string().default(""), taxRate: z.number().min(0).max(100).default(0), - lineItems: z.array(lineItemSchema).min(1, "At least one line item is required"), }); type FormValues = z.input; +type SaveState = "idle" | "loading" | "success" | "error"; const currencies = [ { code: "USD", symbol: "$" }, @@ -35,126 +38,171 @@ const currencies = [ { code: "INR", symbol: "₹" }, ]; +const toDateInput = (date: Date) => date.toISOString().split("T")[0]; + +const addDays = (dateString: string, days: number) => { + const date = new Date(dateString); + date.setDate(date.getDate() + days); + return toDateInput(date); +}; + export function InvoiceFormPage() { const navigate = useNavigate(); const { id } = useParams(); const isEditing = Boolean(id); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); + const [saveState, setSaveState] = useState("idle"); + const isDueDateTouched = useRef(false); + const saveStateTimer = useRef(null); + const { + active: loadingBarActive, + complete: loadingBarComplete, + done: finishLoadingBar, + start: startLoadingBar, + } = useLoadingBar(); const { + formState: { errors }, + handleSubmit, register, control, - handleSubmit, watch, setValue, - formState: { errors }, } = useForm({ - resolver: zodResolver(invoiceSchema), defaultValues: { - clientName: "", - clientEmail: "", clientAddress: "", - issueDate: new Date().toISOString().split('T')[0], - dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], + clientEmail: "", + clientName: "", currency: "USD", + dueDate: toDateInput(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)), + issueDate: toDateInput(new Date()), + lineItems: [{ description: "", quantity: 1, unitPrice: 0 }], notes: "", taxRate: 0, - lineItems: [{ description: "", quantity: 1, unitPrice: 0 }], }, + resolver: zodResolver(invoiceSchema), }); - const { fields, append, remove } = useFieldArray({ + const { append, fields, remove } = useFieldArray({ control, name: "lineItems", }); - const watchedLineItems = watch("lineItems"); - const watchedTaxRate = watch("taxRate"); + const values = watch(); + const issueDate = values.issueDate; + const watchedLineItems = values.lineItems; + const watchedTaxRate = values.taxRate; + const dueDateField = register("dueDate"); useEffect(() => { - if (isEditing && id) { - loadInvoice(id); + if (!isEditing || !id) { + return; } - }, [isEditing, id]); - const loadInvoice = async (invoiceId: string) => { - try { - setLoading(true); - const invoice = await invoicesApi.getById(invoiceId); - - setValue("clientName", invoice.clientName); - setValue("clientEmail", invoice.clientEmail); - setValue("clientAddress", invoice.clientAddress); - setValue("issueDate", new Date(invoice.issueDate).toISOString().split('T')[0]); - setValue("dueDate", new Date(invoice.dueDate).toISOString().split('T')[0]); - setValue("currency", invoice.currency); - setValue("notes", invoice.notes); - setValue("taxRate", Number(invoice.taxRate)); - - const lineItems = invoice.lineItems.map(item => ({ - description: item.description, - quantity: Number(item.quantity), - unitPrice: Number(item.unitPrice), - })); - setValue("lineItems", lineItems.length > 0 ? lineItems : [{ description: "", quantity: 1, unitPrice: 0 }]); - - setError(null); - } catch (err) { - setError("Failed to load invoice"); - console.error("Error loading invoice:", err); - } finally { - setLoading(false); + const loadInvoice = async () => { + try { + setLoading(true); + startLoadingBar(); + const invoice = await invoicesApi.getById(id); + + setValue("clientName", invoice.clientName); + setValue("clientEmail", invoice.clientEmail); + setValue("clientAddress", invoice.clientAddress); + setValue("issueDate", toDateInput(new Date(invoice.issueDate))); + setValue("dueDate", toDateInput(new Date(invoice.dueDate))); + setValue("currency", invoice.currency); + setValue("notes", invoice.notes); + setValue("taxRate", Number(invoice.taxRate)); + setValue( + "lineItems", + invoice.lineItems.length + ? invoice.lineItems.map((item) => ({ + description: item.description, + quantity: Number(item.quantity), + unitPrice: Number(item.unitPrice), + })) + : [{ description: "", quantity: 1, unitPrice: 0 }], + ); + isDueDateTouched.current = true; + setError(null); + } catch (err) { + setError("Failed to load invoice"); + console.error("Error loading invoice:", err); + } finally { + setLoading(false); + finishLoadingBar(); + } + }; + + void loadInvoice(); + }, [finishLoadingBar, id, isEditing, setValue, startLoadingBar]); + + useEffect(() => { + if (!issueDate || isDueDateTouched.current) { + return; } - }; - const calculateTotals = () => { - const subtotal = watchedLineItems.reduce( - (sum, item) => sum + (item.quantity * item.unitPrice), - 0 - ); - const taxAmount = subtotal * ((watchedTaxRate ?? 0) / 100); - const total = subtotal + taxAmount; - return { subtotal, taxAmount, total }; - }; + setValue("dueDate", addDays(issueDate, 30)); + }, [issueDate, setValue]); - const { subtotal, taxAmount, total } = calculateTotals(); + useEffect( + () => () => { + if (saveStateTimer.current !== null) { + window.clearTimeout(saveStateTimer.current); + } + }, + [], + ); - const formatCurrency = (amount: number) => { - const currency = currencies.find(c => c.code === watch("currency")) || currencies[0]; - return new Intl.NumberFormat("en-US", { + const subtotal = watchedLineItems.reduce( + (sum, item) => sum + (item.quantity || 0) * (item.unitPrice || 0), + 0, + ); + const taxAmount = subtotal * ((watchedTaxRate ?? 0) / 100); + const total = subtotal + taxAmount; + + const formatCurrency = (amount: number) => + new Intl.NumberFormat("en-US", { + currency: values.currency, style: "currency", - currency: watch("currency"), }).format(amount); + + const showTransientState = (state: SaveState) => { + setSaveState(state); + if (saveStateTimer.current !== null) { + window.clearTimeout(saveStateTimer.current); + } + saveStateTimer.current = window.setTimeout(() => setSaveState("idle"), 2000); }; const onSubmit: SubmitHandler = async (data) => { try { setLoading(true); - + setSaveState("loading"); + if (isEditing && id) { await invoicesApi.update(id, data as UpdateInvoiceData); } else { await invoicesApi.create(data as CreateInvoiceData); } - + + showTransientState("success"); navigate("/invoices"); } catch (err: any) { setError(err.response?.data?.message || "Failed to save invoice"); + showTransientState("error"); console.error("Error saving invoice:", err); } finally { setLoading(false); } }; - const handleSaveAsDraft = () => { - handleSubmit(onSubmit)(); - }; - const handleSaveAndSend = () => { handleSubmit(async (data) => { try { setLoading(true); + setSaveState("loading"); if (isEditing && id) { await invoicesApi.update(id, data as UpdateInvoiceData); @@ -163,9 +211,12 @@ export function InvoiceFormPage() { const invoice = await invoicesApi.create(data as CreateInvoiceData); await invoicesApi.send(invoice.id); } + + showTransientState("success"); navigate("/invoices"); } catch (err: any) { setError(err.response?.data?.message || "Failed to save and send invoice"); + showTransientState("error"); console.error("Error saving and sending invoice:", err); } finally { setLoading(false); @@ -173,272 +224,285 @@ export function InvoiceFormPage() { })(); }; + const appendItem = () => { + append({ description: "", quantity: 1, unitPrice: 0 }); + window.requestAnimationFrame(() => { + document.getElementById(`line-item-description-${fields.length}`)?.focus(); + }); + }; + if (loading && isEditing) { return ( - -
-
Loading invoice...
+ + +
+
+
+
+
+
+
); } return ( - - {error &&
{error}
} - -
- {/* Client Information */} -
-

Client Information

-
-
- - - {errors.clientName && ( -

{errors.clientName.message}

- )} -
-
- - - {errors.clientEmail && ( -

{errors.clientEmail.message}

- )} -
-
- -