Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

feat: save sellers for future use, enhance invoice form with advanced input validation and user experience improvements (#47)

Vlad Sazonaubed431f55361
diff --git a/.cursor/rules/shared.mdc b/.cursor/rules/shared.mdc
index 1b81a39..0c26c17 100644
--- a/.cursor/rules/shared.mdc
+++ b/.cursor/rules/shared.mdc
@@ -18,9 +18,12 @@ Naming Conventions
TypeScript Usage
- Use TypeScript for all code; prefer interfaces over types.
-- Avoid enums; use maps instead.
+- Avoid enums; use objects with `as const` instead.
- Use functional components with TypeScript interfaces.
+React Usage
+- Prefer Conditional (ternary) operator (? :) over Logical AND operator (&&)
+
Syntax and Formatting
- Use the "function" keyword for pure functions.
- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
diff --git a/package.json b/package.json
index 1e0fd3b..59d4a5c 100644
--- a/package.json
+++ b/package.json
@@ -15,6 +15,8 @@
"dependencies": {
"@hookform/resolvers": "3.9.0",
"@loglib/tracker": "0.8.0",
+ "@radix-ui/react-alert-dialog": "1.1.6",
+ "@radix-ui/react-dialog": "1.1.6",
"@radix-ui/react-label": "2.1.2",
"@radix-ui/react-slot": "1.1.2",
"@radix-ui/react-switch": "1.1.3",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 51eae1c..641f4b2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,6 +14,12 @@ importers:
'@loglib/tracker':
specifier: 0.8.0
version: 0.8.0([email protected])
+ '@radix-ui/react-alert-dialog':
+ specifier: 1.1.6
+ '@radix-ui/react-dialog':
+ specifier: 1.1.6
'@radix-ui/react-label':
specifier: 2.1.2
@@ -283,6 +289,19 @@ packages:
'@radix-ui/[email protected]':
resolution: {integrity: sha512-SJ31y+Q/zAyShtXJc8x83i9TYdbAfHZ++tUZnvjJJqFjzsdUnKsxPL6IEtBlxKkU7yzer//GQtZSV4GbldL3YA==}
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-p4XnPqgej8sZAAReCAKgz1REYZEBLR8hU9Pg27wFnCWIMc8g1ccCs0FjBcy05V15VTu8pAePw/VDYeOm/uZ6yQ==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-G+KcpzXHq24iH0uGG/pF8LyzpFJYGD4RfLjCIBfGdSLXvjLHST31RUiRVrupIBMvIppMgSzQ6l66iAxl03tdlg==}
peerDependencies:
@@ -314,6 +333,19 @@ packages:
'@types/react':
optional: true
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-/IVhJV5AceX620DUJ4uYVMymzsipdKBzo3edo+omeskCKGm9FRHM0ebIdbPnlQVJqyuHbuBltQUOG2mOTq2IYw==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-E4TywXY6UsXNRhFrECa5HAvE5/4BFcGyfTyK36gP+pAW1ed7UTK4vKwdr53gAJYwqbfCWC6ATvJa3J3R/9+Qrg==}
peerDependencies:
@@ -327,6 +359,28 @@ packages:
'@types/react-dom':
optional: true
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-pSIwfrT1a6sIoDASCSpFwOasEwKTZWDw/iBdtnqKO7v6FeOzYJ7U53cPzYFVR3geGGXgVHaH+CdngrrAzqUGxg==}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
+ '@radix-ui/[email protected]':
+ resolution: {integrity: sha512-zxwE80FCU7lcXUGWkdt6XpTTCKPitG1XKOwViTxHVKIJhZl9MvIl2dVHeZENCWD9+EdWv05wlaEkRXUykU27RA==}
+ peerDependencies:
+ '@types/react': '*'
+ '@types/react-dom': '*'
+ react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-EJUrI8yYh7WOjNOqpoJaf1jlFIH2LvtgAl+YcFqNCa+4hj64ZXmPkAKOFs/ukjz3byN6bdb/AVUqHkI8/uWWMA==}
peerDependencies:
@@ -693,6 +747,10 @@ packages:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
+ resolution: {integrity: sha512-y+CcFFwelSXpLZk/7fMB2mUbGtX9lKycf1MWJ7CaTIERyitVlyQx6C+sxcROU2BAJ24OiZyK+8wj2i8AlBoS3A==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-R5iJ5lkuHybztUfuOAznmboyjWq8O6sqNqtK7CLOqdydi54VNbORp49mb14KbWgG1QD3JFO9hJdZ+y4KutfdOQ==}
@@ -899,6 +957,9 @@ packages:
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}
+
resolution: {integrity: sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q==}
@@ -1149,6 +1210,10 @@ packages:
resolution: {integrity: sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==}
engines: {node: '>= 0.4'}
@@ -1804,6 +1869,36 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+ resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
+ resolution: {integrity: sha512-pnAi91oOk8g8ABQKGF5/M9qxmmOPxaAnopyTHYfqYEwJhyFrbbBtHuSgtKEoH0jpcxx5o3hXqH1mNd9/Oi+8iQ==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
+ resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
@@ -2055,9 +2150,6 @@ packages:
resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==}
- resolution: {integrity: sha512-jWVzBLplnCmoaTr13V9dYbiQ99wvZRd0vNWaDRg+aVYRcjDF3nDksxFDE/+fkXnKhpnUUkmx5pK/v8mCtLVqZA==}
-
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -2105,12 +2197,32 @@ packages:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
+ resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
resolution: {integrity: sha512-6Cf7Yr7Wk7Kdv77nnJMf6de4HuDE4dTxKij+RqE9rufDsI6zsbjyAxcH5y2ueJCQAnfgKbzXbZHYlkFwmBlWkw==}
engines: {node: '>= 16.0.0'}
peerDependencies:
react: '*'
+ resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ '@types/react': '*'
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -2318,6 +2430,20 @@ snapshots:
'@radix-ui/[email protected]': {}
+ dependencies:
+ '@radix-ui/primitive': 1.1.1
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.2(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.12
+ '@types/react-dom': 18.3.1
+
dependencies:
@@ -2339,6 +2465,28 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.12
+ dependencies:
+ '@radix-ui/primitive': 1.1.1
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.5(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope': 1.1.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.2(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ aria-hidden: 1.2.4
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ react-remove-scroll: 2.6.3(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.12
+ '@types/react-dom': 18.3.1
+
dependencies:
'@radix-ui/primitive': 1.1.1
@@ -2352,6 +2500,23 @@ snapshots:
'@types/react': 18.3.12
'@types/react-dom': 18.3.1
+ dependencies:
+ react: 18.3.1
+ optionalDependencies:
+ '@types/react': 18.3.12
+
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.1(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.12
+ '@types/react-dom': 18.3.1
+
dependencies:
'@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
@@ -2630,7 +2795,7 @@ snapshots:
dependencies:
'@swc/counter': 0.1.3
- tslib: 2.8.0
+ tslib: 2.8.1
'@types/[email protected]': {}
@@ -2768,6 +2933,10 @@ snapshots:
+ dependencies:
+ tslib: 2.8.1
+
dependencies:
deep-equal: 2.2.3
@@ -3017,6 +3186,8 @@ snapshots:
has-property-descriptors: 1.0.2
object-keys: 1.1.1
+
@@ -3437,6 +3608,8 @@ snapshots:
has-symbols: 1.0.3
hasown: 2.0.2
+
dependencies:
call-bind: 1.0.7
@@ -4009,6 +4182,33 @@ snapshots:
+ dependencies:
+ react: 18.3.1
+ react-style-singleton: 2.2.3(@types/[email protected])([email protected])
+ tslib: 2.8.1
+ optionalDependencies:
+ '@types/react': 18.3.12
+
+ dependencies:
+ react: 18.3.1
+ react-remove-scroll-bar: 2.3.8(@types/[email protected])([email protected])
+ react-style-singleton: 2.2.3(@types/[email protected])([email protected])
+ tslib: 2.8.1
+ use-callback-ref: 1.3.3(@types/[email protected])([email protected])
+ use-sidecar: 1.1.3(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.12
+
+ dependencies:
+ get-nonce: 1.0.1
+ react: 18.3.1
+ tslib: 2.8.1
+ optionalDependencies:
+ '@types/react': 18.3.12
+
dependencies:
loose-envify: 1.4.0
@@ -4303,8 +4503,6 @@ snapshots:
minimist: 1.2.8
strip-bom: 3.0.0
-
@@ -4370,10 +4568,25 @@ snapshots:
dependencies:
punycode: 2.3.1
+ dependencies:
+ react: 18.3.1
+ tslib: 2.8.1
+ optionalDependencies:
+ '@types/react': 18.3.12
+
dependencies:
react: 18.3.1
+ dependencies:
+ detect-node-es: 1.1.0
+ react: 18.3.1
+ tslib: 2.8.1
+ optionalDependencies:
+ '@types/react': 18.3.12
+
diff --git a/src/app/components/invoice-form.tsx b/src/app/components/invoice-form.tsx
index ad29d65..0e324bd 100644
--- a/src/app/components/invoice-form.tsx
+++ b/src/app/components/invoice-form.tsx
@@ -7,7 +7,8 @@ import {
type InvoiceData,
type InvoiceItemData,
} from "@/app/schema";
-import { Button } from "@/components/ui/button";
+import { SellerManagement } from "@/components/seller-management";
+import { ButtonHelper } from "@/components/ui/button-helper";
import { Input } from "@/components/ui/input";
import { InputHelperMessage } from "@/components/ui/input-helper-message";
import { Label } from "@/components/ui/label";
@@ -20,17 +21,18 @@ import { SelectNative } from "@/components/ui/select-native";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { CustomTooltip } from "@/components/ui/tooltip";
-import { cn } from "@/lib/utils";
+import { getAmountInWords, getNumberFractionalPart } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { loglib } from "@loglib/tracker";
import dayjs from "dayjs";
import { AlertTriangle, Plus, Trash2 } from "lucide-react";
import React, { useCallback, useEffect } from "react";
import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";
+import { toast } from "sonner";
import { useDebouncedCallback } from "use-debounce";
import { z } from "zod";
-export const PDF_DATA_LOCAL_STORAGE_KEY = "invoicePdfData";
+export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";
export const PDF_DATA_FORM_ID = "pdfInvoiceForm";
export const DEBOUNCE_TIMEOUT = 500;
export const LOADING_BUTTON_TIMEOUT = 400;
@@ -90,28 +92,6 @@ const AlertIcon = () => {
return <AlertTriangle className="mr-1 inline-block h-3 w-3 text-amber-500" />;
};
-const ButtonHelper = ({
- children,
- className,
- ...props
-}: { children: React.ReactNode; className?: string } & React.ComponentProps<
- typeof Button
->) => {
- return (
- <Button
- _variant="link"
- _size="sm"
- className={cn(
- "h-5 max-w-full whitespace-normal text-pretty p-0 text-left underline",
- className
- )}
- {...props}
- >
- {children}
- </Button>
- );
-};
-
interface InvoiceFormProps {
invoiceData: InvoiceData;
onInvoiceDataChange: (updatedData: InvoiceData) => void;
@@ -140,6 +120,7 @@ export function InvoiceForm({
const dateOfIssue = useWatch({ control, name: "dateOfIssue" });
const dateOfService = useWatch({ control, name: "dateOfService" });
const paymentDue = useWatch({ control, name: "paymentDue" });
+ const language = useWatch({ control, name: "language" });
const isDateOfIssueInCurrentMonth =
checkIfDateOnInvoiceIsInCurrentMonth(dateOfIssue);
@@ -166,8 +147,6 @@ export function InvoiceForm({
name: "items",
});
- // const sellerSelectId = useId();
-
// calculate totals and other values when invoice items change
useEffect(() => {
// run validations before calculations because user can input invalid data
@@ -274,7 +253,64 @@ export function InvoiceForm({
return (
<>
<form
- onSubmit={handleSubmit(onSubmit)}
+ onSubmit={handleSubmit(onSubmit, (errors) => {
+ console.error("Form validation errors:", errors);
+ toast.error(
+ <div>
+ <p className="font-semibold">Please fix the following errors:</p>
+ <ul className="mt-1 list-inside list-disc">
+ {Object.entries(errors)
+ .map(([key, error]) => {
+ // Handle nested errors (e.g., seller.name, items[0].name)
+ if (
+ error &&
+ typeof error === "object" &&
+ "message" in error
+ ) {
+ return (
+ <li key={key} className="text-sm">
+ {error?.message || "Unknown error"}
+ </li>
+ );
+ }
+
+ // Handle array errors (e.g., items array)
+ if (Array.isArray(error)) {
+ return error.map((item, index) =>
+ Object.entries(
+ item as Record<string, { message?: string }>
+ ).map(([fieldName, fieldError]) => (
+ <li
+ key={`${key}.${index}.${fieldName}`}
+ className="text-sm"
+ >
+ {fieldError?.message || "Unknown error"}
+ </li>
+ ))
+ );
+ }
+
+ // Handle nested object errors
+ if (error && typeof error === "object") {
+ return Object.entries(error).map(
+ ([nestedKey, nestedError]) => (
+ <li key={`${key}.${nestedKey}`} className="text-sm">
+ {nestedError?.message || "Unknown error"}
+ </li>
+ )
+ );
+ }
+
+ return null;
+ })
+ .flat(Infinity)}
+ </ul>
+ </div>,
+ {
+ closeButton: true,
+ }
+ );
+ })}
className="mb-4 space-y-3.5"
id={PDF_DATA_FORM_ID}
>
@@ -546,37 +582,12 @@ export function InvoiceForm({
<fieldset className="rounded-lg border p-4 shadow">
<Legend>Seller Information</Legend>
- {/* TODO: Will be done later */
- /*
+ {/* Seller Select */}
<div className="relative bottom-3 flex items-end justify-end gap-2">
- <div className="space-y-1">
- <div className="flex items-center gap-1">
- <Label htmlFor={sellerSelectId}>Select Seller</Label>
- <CustomTooltip
- trigger={<Info className="h-3 w-3" />}
- content="You can save multiple sellers to use them later"
- />
- </div>
- <SelectNative
- id={sellerSelectId}
- className="block h-8 text-[12px] lg:text-[12px]"
- >
- {/* TODO: fetch sellers from local storage */
- /*}
- <option value="1">Seller 1</option>
- <option value="2">Seller 2</option>
- <option value="3">Seller 3</option>
- </SelectNative>
- </div>
+ <SellerManagement setValue={setValue} invoiceData={invoiceData} />
+ </div>
- {/* TODO: add new seller modal + form and save to local storage */
- /*}
- <Button _variant="outline" _size="sm" className="">
- New Seller
- <Plus className="ml-1 h-3 w-3" />
- </Button>
- </div>
- </> */}
+ {/* Seller Information Form */}
<div className="space-y-4">
<div>
<Label htmlFor="sellerName" className="mb-1">
@@ -779,6 +790,17 @@ export function InvoiceForm({
<ErrorMessage>{errors.seller.swiftBic.message}</ErrorMessage>
)}
</div>
+ {/* TODO: add button that opens dialog to save seller with prefilled data from the form
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ _variant="outline"
+ onClick={() => {
+ }}
+ >
+ Save seller
+ </Button>
+ </div> */}
</div>
</fieldset>
@@ -1117,16 +1139,32 @@ export function InvoiceForm({
<Controller
name={`items.${index}.amount`}
control={control}
- render={({ field }) => (
- <Input
- {...field}
- id={`itemAmount${index}`}
- type="number"
- step="1"
- min="0"
- className=""
- />
- )}
+ render={({ field }) => {
+ const fieldValueNumber = Number(field.value) || 0;
+ const previewFormattedValue =
+ fieldValueNumber.toLocaleString("en-US", {
+ style: "decimal",
+ maximumFractionDigits: 3,
+ });
+
+ return (
+ <>
+ <Input
+ {...field}
+ id={`itemAmount${index}`}
+ type="number"
+ step="0.01"
+ min="0"
+ className=""
+ />
+ {!errors.items?.[index]?.amount && (
+ <InputHelperMessage>
+ Preview: {previewFormattedValue}
+ </InputHelperMessage>
+ )}
+ </>
+ );
+ }}
/>
{errors.items?.[index]?.amount && (
<ErrorMessage>
@@ -1231,33 +1269,46 @@ export function InvoiceForm({
<Controller
name={`items.${index}.netPrice`}
control={control}
- render={({ field }) => (
- <div className="flex w-full flex-col">
- <MoneyInput
- {...field}
- id={`itemNetPrice${index}`}
- currency={currency}
- type="number"
- step="0.01"
- min="0"
- className="w-full"
- />
- {!errors.items?.[index]?.netPrice && (
- <InputHelperMessage>
- Preview:{" "}
- {Number(field.value || 0).toLocaleString(
- "en-US",
- {
- style: "currency",
- currency: currency,
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- }
- )}
- </InputHelperMessage>
- )}
- </div>
- )}
+ render={({ field }) => {
+ const fieldValueNumber = Number(field.value) || 0;
+
+ const previewFormattedValue =
+ fieldValueNumber.toLocaleString("en-US", {
+ style: "currency",
+ currency: currency,
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ });
+
+ const previewAmountInWords = getAmountInWords({
+ amount: fieldValueNumber,
+ language,
+ });
+
+ const previewNumberFractionalPart =
+ getNumberFractionalPart(fieldValueNumber);
+
+ return (
+ <div className="flex w-full flex-col">
+ <MoneyInput
+ {...field}
+ id={`itemNetPrice${index}`}
+ currency={currency}
+ type="number"
+ step="0.01"
+ min="0"
+ className="w-full"
+ />
+ {!errors.items?.[index]?.netPrice && (
+ <InputHelperMessage>
+ Preview: {previewFormattedValue} (
+ {previewAmountInWords} {currency}{" "}
+ {previewNumberFractionalPart}/100)
+ </InputHelperMessage>
+ )}
+ </div>
+ );
+ }}
/>
</div>
{errors.items?.[index]?.netPrice && (
@@ -1324,7 +1375,7 @@ export function InvoiceForm({
</ErrorMessage>
) : (
<InputHelperMessage>
- Enter NP, OO or percentage value
+ Enter NP, OO or percentage value (0-100)
</InputHelperMessage>
)}
</div>
diff --git a/src/app/components/invoice-pdf-template/index.tsx b/src/app/components/invoice-pdf-template/index.tsx
index f9c4f5c..391bd9c 100644
--- a/src/app/components/invoice-pdf-template/index.tsx
+++ b/src/app/components/invoice-pdf-template/index.tsx
@@ -218,12 +218,17 @@ export const InvoicePdfTemplate = ({
justifyContent: "space-between",
}}
>
- <InvoicePaymentInfo invoiceData={invoiceData} />
+ <View style={{ width: "50%" }}>
+ <InvoicePaymentInfo invoiceData={invoiceData} />
+ </View>
+
{vatTableSummaryIsVisible && (
- <InvoiceVATSummaryTable
- invoiceData={invoiceData}
- formattedInvoiceTotal={formattedInvoiceTotal}
- />
+ <View style={{ width: "50%" }}>
+ <InvoiceVATSummaryTable
+ invoiceData={invoiceData}
+ formattedInvoiceTotal={formattedInvoiceTotal}
+ />
+ </View>
)}
</View>
diff --git a/src/app/components/invoice-pdf-template/invoice-header.tsx b/src/app/components/invoice-pdf-template/invoice-header.tsx
index db2051b..ea6b8d5 100644
--- a/src/app/components/invoice-pdf-template/invoice-header.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-header.tsx
@@ -31,7 +31,9 @@ export function InvoiceHeader({ invoiceData }: { invoiceData: InvoiceData }) {
</Text>
{invoiceData?.invoiceType && invoiceData.invoiceTypeFieldIsVisible && (
- <Text style={[styles.fontBold, styles.fontSize8]}>
+ <Text
+ style={[styles.fontBold, styles.fontSize8, { maxWidth: "250px" }]}
+ >
{invoiceData?.invoiceType}
</Text>
)}
diff --git a/src/app/components/invoice-pdf-template/invoice-items-table.tsx b/src/app/components/invoice-pdf-template/invoice-items-table.tsx
index 71bf0bb..7fc8458 100644
--- a/src/app/components/invoice-pdf-template/invoice-items-table.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-items-table.tsx
@@ -60,7 +60,7 @@ export function InvoiceItemsTable({
{/* Amount column */}
{isAmountFieldVisible ? (
<View style={[styles.tableCol, styles.colAmount, styles.center]}>
- <Text style={[styles.tableCellBold, {}]}>
+ <Text style={[styles.tableCellBold]}>
{t.invoiceItemsTable.amount}
</Text>
</View>
@@ -125,6 +125,13 @@ export function InvoiceItemsTable({
{/* Table rows */}
{invoiceData?.items.map((item, index) => {
+ const formattedAmount = item.amount
+ .toLocaleString("en-US", {
+ style: "decimal",
+ maximumFractionDigits: 3,
+ })
+ .replaceAll(",", " ");
+
const formattedNetPrice = item.netPrice
.toLocaleString("en-US", {
minimumFractionDigits: 2,
@@ -194,7 +201,7 @@ export function InvoiceItemsTable({
]}
>
{typeof item?.amount === "number"
- ? item.amount.toFixed(2)
+ ? formattedAmount
: "0.00"}
</Text>
</View>
diff --git a/src/app/components/invoice-pdf-template/invoice-payment-info.tsx b/src/app/components/invoice-pdf-template/invoice-payment-info.tsx
index 9456f20..de287ab 100644
--- a/src/app/components/invoice-pdf-template/invoice-payment-info.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-payment-info.tsx
@@ -19,7 +19,7 @@ export function InvoicePaymentInfo({
const paymentMethodIsVisible = invoiceData.paymentMethodFieldIsVisible;
return (
- <View>
+ <View style={{ maxWidth: "250px" }}>
{paymentMethodIsVisible && (
<Text style={styles.fontSize7}>
{t.paymentInfo.paymentMethod}:{" "}
diff --git a/src/app/components/invoice-pdf-template/invoice-payment-totals.tsx b/src/app/components/invoice-pdf-template/invoice-payment-totals.tsx
index 3714375..04b7073 100644
--- a/src/app/components/invoice-pdf-template/invoice-payment-totals.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-payment-totals.tsx
@@ -1,15 +1,9 @@
import { View, Text } from "@react-pdf/renderer";
import { styles } from ".";
import type { InvoiceData } from "@/app/schema";
-import n2words from "n2words";
import { translations } from "./translations";
-// Get the fractional part of the total
-const getFractionalPart = (total: number = 0) => {
- return Math.round((total % 1) * 100)
- .toString()
- .padStart(2, "0");
-};
+import { getAmountInWords, getNumberFractionalPart } from "@/lib/utils";
export function InvoicePaymentTotals({
invoiceData,
@@ -21,11 +15,12 @@ export function InvoicePaymentTotals({
const language = invoiceData.language;
const t = translations[language];
- const invoiceTotalInWords = n2words(Math.floor(invoiceData?.total ?? 0), {
- lang: language,
+ const invoiceTotalInWords = getAmountInWords({
+ amount: invoiceData?.total ?? 0,
+ language,
});
- const fractionalPart = getFractionalPart(invoiceData?.total ?? 0);
+ const fractionalPart = getNumberFractionalPart(invoiceData?.total ?? 0);
const currency = invoiceData.currency;
diff --git a/src/app/components/invoice-pdf-template/invoice-vat-summary-table.tsx b/src/app/components/invoice-pdf-template/invoice-vat-summary-table.tsx
index 2c36222..5a83dc5 100644
--- a/src/app/components/invoice-pdf-template/invoice-vat-summary-table.tsx
+++ b/src/app/components/invoice-pdf-template/invoice-vat-summary-table.tsx
@@ -54,7 +54,7 @@ export function InvoiceVATSummaryTable({
.replaceAll(",", " ");
return (
- <View style={[styles.table, { width: "50%" }]}>
+ <View style={[styles.table, { width: "100%" }]}>
{/* Header row */}
<View style={styles.tableRow}>
<View style={[styles.tableCol, { width: "25%" }]}>
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index 2b5e687..b9092d8 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -58,7 +58,7 @@ export default function RootLayout({
}}
/>
{/* https://sonner.emilkowal.ski/ */}
- <Toaster visibleToasts={1} />
+ <Toaster visibleToasts={1} richColors />
</body>
</html>
);
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 340e150..09bfaaf 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -1,6 +1,7 @@
"use client";
import {
+ DEFAULT_SELLER_DATA,
invoiceSchema,
SUPPORTED_CURRENCIES,
SUPPORTED_DATE_FORMATS,
@@ -9,7 +10,7 @@ import {
} from "@/app/schema";
import { Button } from "@/components/ui/button";
import { CustomTooltip, TooltipProvider } from "@/components/ui/tooltip";
-import { useMediaQuery } from "@/lib/hooks/use-media-query";
+import { useMediaQuery } from "@/hooks/use-media-query";
import dayjs from "dayjs";
import {
compressToEncodedURIComponent,
@@ -67,21 +68,7 @@ const initialInvoiceData = {
invoiceType: "Reverse Charge",
invoiceTypeFieldIsVisible: true,
- seller: {
- name: "Seller name",
- address: "Seller address",
-
- vatNo: "Seller vat number",
- vatNoFieldIsVisible: true,
-
- email: "[email protected]",
-
- accountNumber: "Seller account number",
- accountNumberFieldIsVisible: true,
-
- swiftBic: "Seller swift bic",
- swiftBicFieldIsVisible: true,
- },
+ seller: DEFAULT_SELLER_DATA,
buyer: {
name: "Buyer name",
address: "Buyer address",
@@ -213,11 +200,16 @@ export default function Home() {
JSON.stringify(newInvoiceDataValidated)
) {
toast.info(
- <p>
- <span className="font-semibold">Changes detected:</span> This
- invoice differs from the shared link version. To share your
- updated invoice, please click &apos;Generate a link to
- invoice&apos; to create a new shareable link.
+ <p className="text-pretty text-sm leading-relaxed">
+ <span className="font-semibold text-blue-600">
+ Invoice Updated:
+ </span>{" "}
+ Your changes have modified this invoice from its shared
+ version. Click{" "}
+ <span className="font-semibold underline">
+ &apos;Generate a link to invoice&apos;
+ </span>{" "}
+ to create an updated shareable link.
</p>,
{
duration: 10000,
diff --git a/src/app/schema/index.ts b/src/app/schema/index.ts
index b4f5da9..09d9b53 100644
--- a/src/app/schema/index.ts
+++ b/src/app/schema/index.ts
@@ -16,6 +16,22 @@ export const SUPPORTED_DATE_FORMATS = [
"YYYY.MM.DD", // 2024.03.20
] as const;
+export const DEFAULT_SELLER_DATA = {
+ name: "Seller name",
+ address: "Seller address",
+
+ vatNo: "Seller vat number",
+ vatNoFieldIsVisible: true,
+
+ email: "[email protected]",
+
+ accountNumber: "Seller account number",
+ accountNumberFieldIsVisible: true,
+
+ swiftBic: "Seller swift bic",
+ swiftBicFieldIsVisible: true,
+} as const satisfies SellerData;
+
export type SupportedDateFormat = (typeof SUPPORTED_DATE_FORMATS)[number];
export const invoiceItemSchema = z
@@ -23,10 +39,19 @@ export const invoiceItemSchema = z
// Show/hide Number column on PDF
invoiceItemNumberIsVisible: z.boolean().default(true),
- name: z.string().min(1, "Item name is required").trim(),
+ name: z
+ .string()
+ .min(1, "Item name is required")
+ .max(500, "Item name must not exceed 500 characters")
+ .trim(),
nameFieldIsVisible: z.boolean().default(true),
- typeOfGTU: z.string().trim().optional().default(""),
+ typeOfGTU: z
+ .string()
+ .max(50, "Type of GTU must not exceed 50 characters")
+ .trim()
+ .optional()
+ .default(""),
typeOfGTUFieldIsVisible: z.boolean().default(true),
amount: z
@@ -37,6 +62,9 @@ export const invoiceItemSchema = z
.transform(Number)
.refine((val) => val > 0, {
message: "Amount must be positive",
+ })
+ .refine((val) => val <= 9_999_999_999.99, {
+ message: "Amount must not exceed 9.999.999.999",
}),
amountFieldIsVisible: z.boolean().default(true),
@@ -51,6 +79,9 @@ export const invoiceItemSchema = z
.transform(Number)
.refine((val) => val >= 0, {
message: "Net price must be >= 0",
+ })
+ .refine((val) => val <= 100_000_000_000, {
+ message: "Net price must not exceed 100 billion",
}),
netPriceFieldIsVisible: z.boolean().default(true),
@@ -86,42 +117,93 @@ export const invoiceItemSchema = z
export type InvoiceItemData = z.infer<typeof invoiceItemSchema>;
-export const invoiceSchema = z.object({
- language: z.enum(SUPPORTED_LANGUAGES).default("en"),
- dateFormat: z.enum(SUPPORTED_DATE_FORMATS).default("YYYY-MM-DD"),
- currency: z.enum(SUPPORTED_CURRENCIES).default("EUR"),
-
- invoiceNumber: z.string().min(1, "Invoice number is required").trim(),
- dateOfIssue: z.string().min(1, "Date of issue is required").trim(),
- dateOfService: z.string().min(1, "Date of service is required").trim(),
-
- invoiceType: z.string().trim().optional(),
- invoiceTypeFieldIsVisible: z.boolean().default(true),
-
- seller: z.object({
- name: z.string().min(1, "Seller name is required").trim(),
- address: z.string().min(1, "Seller address is required").trim(),
-
- vatNo: z.string().trim().optional(),
+export const sellerSchema = z
+ .object({
+ id: z.string().optional(),
+
+ name: z
+ .string()
+ .min(1, "Seller name is required")
+ .max(500, "Seller name must not exceed 500 characters")
+ .trim(),
+ address: z
+ .string()
+ .min(1, "Seller address is required")
+ .max(500, "Seller address must not exceed 500 characters")
+ .trim(),
+
+ vatNo: z
+ .string()
+ .max(200, "VAT number must not exceed 200 characters")
+ .trim()
+ .optional(),
vatNoFieldIsVisible: z.boolean().default(true),
email: z.string().email("Invalid email address").trim(),
- accountNumber: z.string().trim().optional(),
+ accountNumber: z
+ .string()
+ .max(200, "Account number must not exceed 200 characters")
+ .trim()
+ .optional(),
accountNumberFieldIsVisible: z.boolean().default(true),
- swiftBic: z.string().trim().optional(),
+ swiftBic: z
+ .string()
+ .max(200, "SWIFT/BIC must not exceed 200 characters")
+ .trim()
+ .optional(),
swiftBicFieldIsVisible: z.boolean().default(true),
- }),
- buyer: z.object({
- name: z.string().min(1, "Buyer name is required").trim(),
- address: z.string().min(1, "Buyer address is required").trim(),
+ })
+ .strict();
+
+export type SellerData = z.infer<typeof sellerSchema>;
- vatNo: z.string().trim().optional(),
+export const buyerSchema = z
+ .object({
+ id: z.string().optional(),
+
+ name: z
+ .string()
+ .min(1, "Buyer name is required")
+ .max(500, "Buyer name must not exceed 500 characters")
+ .trim(),
+ address: z
+ .string()
+ .min(1, "Buyer address is required")
+ .max(500, "Buyer address must not exceed 500 characters")
+ .trim(),
+ vatNo: z
+ .string()
+ .max(200, "VAT number must not exceed 200 characters")
+ .trim()
+ .optional(),
vatNoFieldIsVisible: z.boolean().default(true),
email: z.string().email("Invalid email address").trim(),
- }),
+ })
+ .strict();
+
+export type BuyerData = z.infer<typeof buyerSchema>;
+
+export const invoiceSchema = z.object({
+ language: z.enum(SUPPORTED_LANGUAGES).default("en"),
+ dateFormat: z.enum(SUPPORTED_DATE_FORMATS).default("YYYY-MM-DD"),
+ currency: z.enum(SUPPORTED_CURRENCIES).default("EUR"),
+
+ invoiceNumber: z.string().min(1, "Invoice number is required").trim(),
+ dateOfIssue: z.string().min(1, "Date of issue is required").trim(),
+ dateOfService: z.string().min(1, "Date of service is required").trim(),
+
+ invoiceType: z
+ .string()
+ .max(500, "Invoice type must not exceed 500 characters")
+ .trim()
+ .optional(),
+ invoiceTypeFieldIsVisible: z.boolean().default(true),
+
+ seller: sellerSchema,
+ buyer: buyerSchema,
items: z.array(invoiceItemSchema).min(1, "At least one item is required"),
total: z.coerce.number().nonnegative("Total must be non-negative"),
@@ -129,12 +211,20 @@ export const invoiceSchema = z.object({
// Show/hide VAT Table Summary on PDF
vatTableSummaryIsVisible: z.boolean().default(true),
- paymentMethod: z.string().trim().optional(),
+ paymentMethod: z
+ .string()
+ .max(500, "Payment method must not exceed 500 characters")
+ .trim()
+ .optional(),
paymentMethodFieldIsVisible: z.boolean().default(true),
paymentDue: z.string().min(1, "Payment due is required").trim(),
- notes: z.string().trim().optional(),
+ notes: z
+ .string()
+ .max(3500, "Notes must not exceed 3500 characters")
+ .trim()
+ .optional(),
notesFieldIsVisible: z.boolean().default(true),
personAuthorizedToReceiveFieldIsVisible: z.boolean().default(true),
diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsx
new file mode 100644
index 0000000..bfd9f05
--- /dev/null
+++ b/src/components/seller-dialog.tsx
@@ -0,0 +1,405 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import { sellerSchema, type SellerData } from "@/app/schema";
+import { useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Switch } from "@/components/ui/switch";
+import { CustomTooltip } from "@/components/ui/tooltip";
+import { toast } from "sonner";
+import { SELLERS_LOCAL_STORAGE_KEY } from "./seller-management";
+import { z } from "zod";
+import { useState } from "react";
+
+const SELLER_FORM_ID = "seller-form";
+interface SellerDialogProps {
+ isOpen: boolean;
+ onClose: React.Dispatch<React.SetStateAction<boolean>>;
+ handleSellerAdd?: (
+ seller: SellerData,
+ {
+ shouldApplyNewSellerToInvoice,
+ }: { shouldApplyNewSellerToInvoice: boolean }
+ ) => void;
+ handleSellerEdit?: (seller: SellerData) => void;
+ initialData: SellerData | null;
+ isEditMode: boolean;
+}
+
+export function SellerDialog({
+ isOpen,
+ onClose,
+ handleSellerAdd,
+ handleSellerEdit,
+ initialData,
+ isEditMode,
+}: SellerDialogProps) {
+ const form = useForm<SellerData>({
+ resolver: zodResolver(sellerSchema),
+ defaultValues: {
+ id: initialData?.id ?? "",
+ name: initialData?.name ?? "",
+ address: initialData?.address ?? "",
+ vatNo: initialData?.vatNo ?? "",
+ email: initialData?.email ?? "",
+ accountNumber: initialData?.accountNumber ?? "",
+ swiftBic: initialData?.swiftBic ?? "",
+ vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
+ accountNumberFieldIsVisible:
+ initialData?.accountNumberFieldIsVisible ?? true,
+ swiftBicFieldIsVisible: initialData?.swiftBicFieldIsVisible ?? true,
+ },
+ });
+
+ const [shouldApplyNewSellerToInvoice, setShouldApplyNewSellerToInvoice] =
+ useState(false);
+
+ function onSubmit(formValues: SellerData) {
+ try {
+ // **RUNNING SOME VALIDATIONS FIRST**
+
+ // Get existing sellers or initialize empty array
+ const sellers = localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY);
+ const existingSellers = sellers ? JSON.parse(sellers) : [];
+
+ // Validate existing sellers array with Zod
+ const existingSellersValidationResult = z
+ .array(sellerSchema)
+ .safeParse(existingSellers);
+
+ if (!existingSellersValidationResult.success) {
+ console.error(
+ "Invalid existing sellers data:",
+ existingSellersValidationResult.error
+ );
+
+ // Show error toast
+ toast.error("Error loading existing sellers", {
+ richColors: true,
+ description: "Please try again",
+ });
+
+ // Reset localStorage if validation fails
+ localStorage.setItem(SELLERS_LOCAL_STORAGE_KEY, JSON.stringify([]));
+
+ return;
+ }
+
+ // we don't need to validate the name if we are editing an existing seller
+
+ // Validate seller data against existing sellers
+ const isDuplicateName = existingSellers.some(
+ (seller: SellerData) =>
+ seller.name === formValues.name && seller.id !== formValues.id
+ );
+
+ if (isDuplicateName) {
+ form.setError("name", {
+ type: "manual",
+ message: "A seller with this name already exists",
+ });
+
+ // Focus on the name input field for user to fix the error
+ form.setFocus("name");
+
+ // Show error toast
+ toast.error("A seller with this name already exists", {
+ richColors: true,
+ });
+
+ return;
+ }
+
+ if (isEditMode) {
+ // Edit seller
+ handleSellerEdit?.(formValues);
+ } else {
+ // Add new seller
+ handleSellerAdd?.(formValues, { shouldApplyNewSellerToInvoice });
+ }
+
+ // Close dialog
+ onClose(false);
+
+ // Reset form
+ form.reset();
+ } catch (error) {
+ console.error("Failed to save seller:", error);
+
+ toast.error("Failed to save seller", {
+ description: "Please try again",
+ richColors: true,
+ });
+ }
+ }
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onClose}>
+ <DialogContent className="flex flex-col gap-0 overflow-y-visible p-0 sm:max-w-lg [&>button:last-child]:top-3.5">
+ <DialogHeader className="border-b border-slate-200 px-6 py-4 dark:border-slate-800">
+ <DialogTitle className="text-base">
+ {isEditMode ? "Edit Seller" : "Add New Seller"}
+ </DialogTitle>
+ <DialogDescription>
+ {isEditMode
+ ? "Edit the seller details"
+ : "Add a new seller to use later in your invoices"}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="overflow-y-auto px-6 py-4">
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="space-y-4"
+ id={SELLER_FORM_ID}
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter seller name"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="address"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Address</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter seller address"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Email</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ type="email"
+ placeholder="[email protected]"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* VAT Number */}
+ <div className="space-y-4">
+ <div className="flex items-end justify-between">
+ <FormField
+ control={form.control}
+ name="vatNo"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>VAT Number</FormLabel>
+ <FormControl>
+ <Input {...field} placeholder="Enter VAT number" />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Show/Hide VAT Number Field in PDF */}
+ <div className="ml-4 flex items-center gap-2">
+ <FormField
+ control={form.control}
+ name="vatNoFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="vatNoFieldIsVisible"
+ />
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="vatNoFieldIsVisible">
+ Show in PDF
+ </Label>
+ }
+ content='Show/Hide the "VAT Number" field in the PDF'
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+
+ <div className="flex items-end justify-between">
+ <FormField
+ control={form.control}
+ name="accountNumber"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>Account Number</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter account number"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div className="ml-4 flex items-center gap-2">
+ <FormField
+ control={form.control}
+ name="accountNumberFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="accountNumberFieldIsVisible"
+ />
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="accountNumberFieldIsVisible">
+ Show in PDF
+ </Label>
+ }
+ content='Show/Hide the "Account Number" field in the PDF'
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+
+ {/* SWIFT/BIC */}
+ <div className="flex items-end justify-between">
+ <FormField
+ control={form.control}
+ name="swiftBic"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>SWIFT/BIC</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter SWIFT/BIC code"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Show/Hide SWIFT/BIC Field in PDF */}
+ <div className="ml-4 flex items-center gap-2">
+ <FormField
+ control={form.control}
+ name="swiftBicFieldIsVisible"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ id="swiftBicFieldIsVisible"
+ />
+ <CustomTooltip
+ trigger={
+ <Label htmlFor="swiftBicFieldIsVisible">
+ Show in PDF
+ </Label>
+ }
+ content='Show/Hide the "SWIFT/BIC" field in the PDF'
+ className="z-[1000]"
+ />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ </form>
+ </Form>
+
+ {/* Apply new seller to current invoice switch */}
+ {!isEditMode ? (
+ <div className="mt-4 flex items-center gap-2">
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={shouldApplyNewSellerToInvoice}
+ onCheckedChange={setShouldApplyNewSellerToInvoice}
+ id="apply-seller-to-current-invoice-switch"
+ />
+ <Label htmlFor="apply-seller-to-current-invoice-switch">
+ Apply Seller to current invoice
+ </Label>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ <DialogFooter className="border-border border-t px-6 py-4">
+ <DialogClose asChild>
+ <Button type="button" _variant="outline">
+ Cancel
+ </Button>
+ </DialogClose>
+ <Button type="submit" form={SELLER_FORM_ID}>
+ Save Seller
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/seller-management.tsx b/src/components/seller-management.tsx
new file mode 100644
index 0000000..b6dddff
--- /dev/null
+++ b/src/components/seller-management.tsx
@@ -0,0 +1,298 @@
+import { Plus, Trash2, Pencil } from "lucide-react";
+
+import { Label } from "@radix-ui/react-label";
+// import { Info } from "lucide-react";
+import { useId, useState, useEffect } from "react";
+import { CustomTooltip } from "./ui/tooltip";
+import { SelectNative } from "./ui/select-native";
+import { Button } from "./ui/button";
+import { SellerDialog } from "./seller-dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "./ui/alert-dialog";
+import type { UseFormSetValue } from "react-hook-form";
+import {
+ DEFAULT_SELLER_DATA,
+ sellerSchema,
+ type InvoiceData,
+ type SellerData,
+} from "@/app/schema";
+import { z } from "zod";
+import { toast } from "sonner";
+import { cn } from "@/lib/utils";
+
+export const SELLERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_SELLERS";
+
+export function SellerManagement({
+ setValue,
+ invoiceData,
+}: {
+ setValue: UseFormSetValue<InvoiceData>;
+ invoiceData: InvoiceData;
+}) {
+ const [isSellerDialogOpen, setIsSellerDialogOpen] = useState(false);
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+ const [sellers, setSellers] = useState<SellerData[]>([]);
+ const [selectedSellerIndex, setSelectedSellerIndex] = useState("");
+ const [editingSeller, setEditingSeller] = useState<SellerData | null>(null);
+
+ const sellerSelectId = useId();
+
+ const isEditMode = Boolean(editingSeller);
+
+ // Load sellers from localStorage on component mount
+ useEffect(() => {
+ try {
+ const savedSellers = localStorage.getItem(SELLERS_LOCAL_STORAGE_KEY);
+ const parsedSellers = savedSellers ? JSON.parse(savedSellers) : [];
+
+ // Validate sellers array with Zod
+ const sellersSchema = z.array(sellerSchema);
+ const validationResult = sellersSchema.safeParse(parsedSellers);
+
+ if (!validationResult.success) {
+ console.error("Invalid sellers data:", validationResult.error);
+ return;
+ }
+
+ const selectedSeller = validationResult.data.find(
+ (seller: SellerData) => {
+ return seller?.id === invoiceData?.seller?.id;
+ }
+ );
+
+ setSellers(validationResult.data);
+ setSelectedSellerIndex(selectedSeller?.id ?? "");
+ } catch (error) {
+ console.error("Failed to load sellers:", error);
+ }
+ }, [invoiceData.seller?.id]);
+
+ // Update sellers when a new one is added
+ const handleSellerAdd = (
+ newSeller: SellerData,
+ {
+ shouldApplyNewSellerToInvoice,
+ }: { shouldApplyNewSellerToInvoice: boolean }
+ ) => {
+ const newSellerWithId = {
+ ...newSeller,
+ // Generate a unique ID for the new seller (IMPORTANT!) =)
+ id: Date.now().toString(),
+ };
+
+ const newSellers = [...sellers, newSellerWithId];
+
+ // Save to localStorage
+ localStorage.setItem(SELLERS_LOCAL_STORAGE_KEY, JSON.stringify(newSellers));
+ setSellers(newSellers);
+
+ // Apply the new seller to the invoice if the user wants to, otherwise just add it to the list and use it later if needed
+ if (shouldApplyNewSellerToInvoice) {
+ setValue("seller", newSellerWithId);
+ setSelectedSellerIndex(newSellerWithId?.id);
+ }
+
+ toast.success("Seller added successfully", {
+ richColors: true,
+ });
+ };
+
+ // Update sellers when edited
+ const handleSellerEdit = (editedSeller: SellerData) => {
+ setSellers((prevSellers) => {
+ const updatedSellers = prevSellers.map((seller) =>
+ seller.id === editedSeller.id ? editedSeller : seller
+ );
+
+ localStorage.setItem(
+ SELLERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(updatedSellers)
+ );
+ return updatedSellers;
+ });
+
+ setValue("seller", editedSeller);
+ setEditingSeller(null);
+
+ toast.success("Seller updated successfully", {
+ richColors: true,
+ });
+ };
+
+ const handleSellerChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
+ const id = event.target.value;
+
+ if (id) {
+ setSelectedSellerIndex(id);
+ const selectedSeller = sellers.find((seller) => seller.id === id);
+
+ if (selectedSeller) {
+ setValue("seller", selectedSeller);
+ }
+ } else {
+ // Clear the seller from the form if the user selects the empty option
+ setSelectedSellerIndex("");
+ setValue("seller", DEFAULT_SELLER_DATA);
+ }
+ };
+
+ const handleDeleteSeller = () => {
+ setSellers((prevSellers) => {
+ const updatedSellers = prevSellers.filter(
+ (seller) => seller.id !== selectedSellerIndex
+ );
+
+ localStorage.setItem(
+ SELLERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(updatedSellers)
+ );
+ return updatedSellers;
+ });
+ setSelectedSellerIndex("");
+ // Clear the seller from the form if it was selected
+ setValue("seller", DEFAULT_SELLER_DATA);
+
+ setIsDeleteDialogOpen(false);
+
+ toast.success("Seller deleted successfully", {
+ richColors: true,
+ });
+ };
+
+ const activeSeller = sellers.find(
+ (seller) => seller.id === selectedSellerIndex
+ );
+
+ return (
+ <>
+ <div className="flex flex-col gap-2">
+ {sellers.length > 0 ? (
+ <div className="space-y-1">
+ <div className="flex items-center gap-1">
+ <Label htmlFor={sellerSelectId} className="text-[12px]">
+ Select Seller
+ </Label>
+ </div>
+ <div className="flex gap-2">
+ <SelectNative
+ id={sellerSelectId}
+ className={cn(
+ "block h-8 max-w-[200px] text-[12px] lg:text-[12px]",
+ !selectedSellerIndex && "italic text-gray-700"
+ )}
+ onChange={handleSellerChange}
+ value={selectedSellerIndex}
+ title={activeSeller?.name}
+ >
+ <option value="">No seller selected (default)</option>
+ {sellers.map((seller) => (
+ <option key={seller.id} value={seller.id}>
+ {seller.name}
+ </option>
+ ))}
+ </SelectNative>
+
+ {selectedSellerIndex ? (
+ <div className="flex items-center gap-2">
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="outline"
+ _size="sm"
+ onClick={() => {
+ if (activeSeller) {
+ setEditingSeller(activeSeller);
+ }
+ }}
+ className="h-8 px-2"
+ >
+ <Pencil className="h-3 w-3" />
+ </Button>
+ }
+ content="Edit seller"
+ />
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="destructive"
+ _size="sm"
+ onClick={() => setIsDeleteDialogOpen(true)}
+ className="h-8 px-2"
+ >
+ <Trash2 className="h-3 w-3" />
+ </Button>
+ }
+ content="Delete seller"
+ />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ ) : null}
+
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="outline"
+ _size="sm"
+ onClick={() => setIsSellerDialogOpen(true)}
+ >
+ New Seller
+ <Plus className="ml-1 h-3 w-3" />
+ </Button>
+ }
+ content="You can save multiple sellers to use them later"
+ />
+ </div>
+
+ <SellerDialog
+ isOpen={isSellerDialogOpen || isEditMode}
+ onClose={() => {
+ setIsSellerDialogOpen(false);
+ setEditingSeller(null);
+ }}
+ handleSellerAdd={handleSellerAdd}
+ handleSellerEdit={handleSellerEdit}
+ initialData={editingSeller}
+ key={editingSeller?.id}
+ isEditMode={isEditMode}
+ />
+
+ {/* Delete alert seller dialog */}
+ <AlertDialog
+ open={isDeleteDialogOpen}
+ onOpenChange={setIsDeleteDialogOpen}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Seller</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete{" "}
+ <span className="font-bold">
+ &quot;{activeSeller?.name}&quot;
+ </span>{" "}
+ seller? This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDeleteSeller}
+ className="bg-red-500 text-red-50 hover:bg-red-500/90"
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/src/components/ui/alert-dialog.tsx b/src/components/ui/alert-dialog.tsx
new file mode 100644
index 0000000..223c378
--- /dev/null
+++ b/src/components/ui/alert-dialog.tsx
@@ -0,0 +1,141 @@
+"use client";
+
+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+import { buttonVariants } from "@/components/ui/button";
+
+const AlertDialog = AlertDialogPrimitive.Root;
+
+const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
+
+const AlertDialogPortal = AlertDialogPrimitive.Portal;
+
+const AlertDialogOverlay = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Overlay
+ className={cn(
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className
+ )}
+ {...props}
+ ref={ref}
+ />
+));
+AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
+
+const AlertDialogContent = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-1/2 top-1/2 z-50 grid max-h-[calc(100%-4rem)] w-full -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto border border-slate-200 bg-white p-6 shadow-lg shadow-black/5 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] dark:border-slate-800 dark:bg-slate-950 sm:max-w-[400px] sm:rounded-xl",
+ className
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+));
+AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
+
+const AlertDialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-1 text-center sm:text-left",
+ className
+ )}
+ {...props}
+ />
+);
+AlertDialogHeader.displayName = "AlertDialogHeader";
+
+const AlertDialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-3",
+ className
+ )}
+ {...props}
+ />
+);
+AlertDialogFooter.displayName = "AlertDialogFooter";
+
+const AlertDialogTitle = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Title
+ ref={ref}
+ className={cn("text-lg font-semibold", className)}
+ {...props}
+ />
+));
+AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
+
+const AlertDialogDescription = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-slate-500 dark:text-slate-400", className)}
+ {...props}
+ />
+));
+AlertDialogDescription.displayName =
+ AlertDialogPrimitive.Description.displayName;
+
+const AlertDialogAction = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Action>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Action
+ ref={ref}
+ className={cn(buttonVariants(), className)}
+ {...props}
+ />
+));
+AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
+
+const AlertDialogCancel = React.forwardRef<
+ React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
+ React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
+>(({ className, ...props }, ref) => (
+ <AlertDialogPrimitive.Cancel
+ ref={ref}
+ className={cn(
+ buttonVariants({ _variant: "outline" }),
+ "mt-2 sm:mt-0",
+ className
+ )}
+ {...props}
+ />
+));
+AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
+
+export {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogOverlay,
+ AlertDialogPortal,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+};
diff --git a/src/components/ui/button-helper.tsx b/src/components/ui/button-helper.tsx
new file mode 100644
index 0000000..c280670
--- /dev/null
+++ b/src/components/ui/button-helper.tsx
@@ -0,0 +1,24 @@
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+
+export const ButtonHelper = ({
+ children,
+ className,
+ ...props
+}: { children: React.ReactNode; className?: string } & React.ComponentProps<
+ typeof Button
+>) => {
+ return (
+ <Button
+ _variant="link"
+ _size="sm"
+ className={cn(
+ "h-5 max-w-full whitespace-normal text-pretty p-0 text-left underline",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </Button>
+ );
+};
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
new file mode 100644
index 0000000..d4ff4be
--- /dev/null
+++ b/src/components/ui/dialog.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "lucide-react";
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+
+const Dialog = DialogPrimitive.Root;
+
+const DialogTrigger = DialogPrimitive.Trigger;
+
+const DialogPortal = DialogPrimitive.Portal;
+
+const DialogClose = DialogPrimitive.Close;
+
+const DialogOverlay = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ "fixed inset-0 z-[101] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className,
+ )}
+ {...props}
+ />
+));
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
+
+const DialogContent = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+>(({ className, children, ...props }, ref) => (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-1/2 top-1/2 z-[101] grid max-h-[calc(100%-4rem)] w-full -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto border border-slate-200 bg-white p-6 shadow-lg shadow-black/5 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:max-w-[400px] sm:rounded-xl dark:border-slate-800 dark:bg-slate-950",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="group absolute right-3 top-3 flex size-7 items-center justify-center rounded-lg outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring/70 disabled:pointer-events-none">
+ <X
+ size={16}
+ strokeWidth={2}
+ className="opacity-60 transition-opacity group-hover:opacity-100"
+ />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+));
+DialogContent.displayName = DialogPrimitive.Content.displayName;
+
+const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
+);
+DialogHeader.displayName = "DialogHeader";
+
+const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end sm:gap-3", className)}
+ {...props}
+ />
+);
+DialogFooter.displayName = "DialogFooter";
+
+const DialogTitle = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn("text-lg font-semibold tracking-tight", className)}
+ {...props}
+ />
+));
+DialogTitle.displayName = DialogPrimitive.Title.displayName;
+
+const DialogDescription = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-slate-500 dark:text-slate-400", className)}
+ {...props}
+ />
+));
+DialogDescription.displayName = DialogPrimitive.Description.displayName;
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+};
diff --git a/src/components/ui/form.tsx b/src/components/ui/form.tsx
new file mode 100644
index 0000000..dad6bcb
--- /dev/null
+++ b/src/components/ui/form.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import * as React from "react";
+import * as LabelPrimitive from "@radix-ui/react-label";
+import { Slot } from "@radix-ui/react-slot";
+import {
+ Controller,
+ ControllerProps,
+ FieldPath,
+ FieldValues,
+ FormProvider,
+ useFormContext,
+} from "react-hook-form";
+
+import { cn } from "@/lib/utils";
+import { Label } from "@/components/ui/label";
+
+const Form = FormProvider;
+
+type FormFieldContextValue<
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+> = {
+ name: TName;
+};
+
+const FormFieldContext = React.createContext<FormFieldContextValue>(
+ {} as FormFieldContextValue
+);
+
+const FormField = <
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
+>({
+ ...props
+}: ControllerProps<TFieldValues, TName>) => {
+ return (
+ <FormFieldContext.Provider value={{ name: props.name }}>
+ <Controller {...props} />
+ </FormFieldContext.Provider>
+ );
+};
+
+const useFormField = () => {
+ const fieldContext = React.useContext(FormFieldContext);
+ const itemContext = React.useContext(FormItemContext);
+ const { getFieldState, formState } = useFormContext();
+
+ const fieldState = getFieldState(fieldContext.name, formState);
+
+ if (!fieldContext) {
+ throw new Error("useFormField should be used within <FormField>");
+ }
+
+ const { id } = itemContext;
+
+ return {
+ id,
+ name: fieldContext.name,
+ formItemId: `${id}-form-item`,
+ formDescriptionId: `${id}-form-item-description`,
+ formMessageId: `${id}-form-item-message`,
+ ...fieldState,
+ };
+};
+
+type FormItemContextValue = {
+ id: string;
+};
+
+const FormItemContext = React.createContext<FormItemContextValue>(
+ {} as FormItemContextValue
+);
+
+const FormItem = React.forwardRef<
+ HTMLDivElement,
+ React.HTMLAttributes<HTMLDivElement>
+>(({ className, ...props }, ref) => {
+ const id = React.useId();
+
+ return (
+ <FormItemContext.Provider value={{ id }}>
+ <div ref={ref} className={cn("space-y-1.5", className)} {...props} />
+ </FormItemContext.Provider>
+ );
+});
+FormItem.displayName = "FormItem";
+
+const FormLabel = React.forwardRef<
+ React.ElementRef<typeof LabelPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
+>(({ className, ...props }, ref) => {
+ const { error, formItemId } = useFormField();
+
+ return (
+ <Label
+ ref={ref}
+ className={cn(error && "text-red-500 dark:text-red-900", className)}
+ htmlFor={formItemId}
+ {...props}
+ />
+ );
+});
+FormLabel.displayName = "FormLabel";
+
+const FormControl = React.forwardRef<
+ React.ElementRef<typeof Slot>,
+ React.ComponentPropsWithoutRef<typeof Slot>
+>(({ ...props }, ref) => {
+ const { error, formItemId, formDescriptionId, formMessageId } =
+ useFormField();
+
+ return (
+ <Slot
+ ref={ref}
+ id={formItemId}
+ aria-describedby={
+ !error
+ ? `${formDescriptionId}`
+ : `${formDescriptionId} ${formMessageId}`
+ }
+ aria-invalid={!!error}
+ {...props}
+ />
+ );
+});
+FormControl.displayName = "FormControl";
+
+const FormDescription = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLParagraphElement>
+>(({ className, ...props }, ref) => {
+ const { formDescriptionId } = useFormField();
+
+ return (
+ <p
+ ref={ref}
+ id={formDescriptionId}
+ className={cn("text-sm text-slate-500 dark:text-slate-400", className)}
+ {...props}
+ />
+ );
+});
+FormDescription.displayName = "FormDescription";
+
+const FormMessage = React.forwardRef<
+ HTMLParagraphElement,
+ React.HTMLAttributes<HTMLParagraphElement>
+>(({ className, children, ...props }, ref) => {
+ const { error, formMessageId } = useFormField();
+ const body = error ? String(error?.message) : children;
+
+ if (!body) {
+ return null;
+ }
+
+ return (
+ <p
+ ref={ref}
+ id={formMessageId}
+ className={cn(
+ "text-[13px] font-medium text-red-500 dark:text-red-900",
+ className
+ )}
+ {...props}
+ >
+ {body}
+ </p>
+ );
+});
+FormMessage.displayName = "FormMessage";
+
+export {
+ useFormField,
+ Form,
+ FormItem,
+ FormLabel,
+ FormControl,
+ FormDescription,
+ FormMessage,
+ FormField,
+};
diff --git a/src/lib/hooks/use-media-query.tsx b/src/hooks/use-media-query.tsx
similarity index 100%
rename from src/lib/hooks/use-media-query.tsx
rename to src/hooks/use-media-query.tsx
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index a5ef193..c46f600 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -1,6 +1,72 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
+import n2words from "n2words";
+import { toast } from "sonner";
+import { SUPPORTED_LANGUAGES, type SupportedLanguages } from "@/app/schema";
+import { z } from "zod";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+
+export function getAmountInWords({
+ amount,
+ language,
+}: {
+ amount: number;
+ language: SupportedLanguages;
+}) {
+ const amountSchema = z
+ .number()
+ .finite()
+ .nonnegative("Amount must be non-negative")
+ .transform(Math.floor);
+
+ const languageSchema = z.enum(SUPPORTED_LANGUAGES).default("en");
+
+ const result = z
+ .object({
+ amount: amountSchema,
+ language: languageSchema,
+ })
+ .safeParse({ amount, language });
+
+ if (!result.success) {
+ console.error("Validation error:", result.error);
+ toast.error("Invalid input data");
+
+ return "-/-";
+ }
+
+ let amountInWords = "";
+ try {
+ amountInWords = n2words(result.data.amount, {
+ lang: result.data.language,
+ });
+ } catch (error) {
+ console.error("Failed to convert number to words:", error);
+ toast.error("Failed to convert number to words");
+
+ amountInWords = Math.floor(amount ?? 0).toString();
+ }
+
+ return amountInWords;
+}
+
+// Get the fractional part of the total
+export function getNumberFractionalPart(total: number = 0) {
+ const schema = z.number().finite().nonnegative("Amount must be non-negative");
+
+ const parsedTotal = schema.safeParse(total);
+
+ if (!parsedTotal.success) {
+ console.error("Validation error:", parsedTotal.error);
+ toast.error("Invalid input data");
+
+ return "-/-";
+ }
+
+ return Math.round((total % 1) * 100)
+ .toString()
+ .padStart(2, "0");
+}