Skip to content

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

feat: Add multi-language PDF download feature with multi-select component and create/edite/delete buyer (#73)

Vlad Sazonau1b3aa7955338
diff --git a/package.json b/package.json
index a3ad116..0370540 100644
--- a/package.json
+++ b/package.json
@@ -2,6 +2,10 @@
"name": "pdf-invoice-generator",
"version": "0.1.0",
"private": true,
+ "packageManager": "[email protected]",
+ "engines": {
+ "node": ">=20.0.0"
+ },
"scripts": {
"dev": "next dev",
"build": "next build",
@@ -25,8 +29,7 @@
"@radix-ui/react-switch": "1.1.3",
"@radix-ui/react-tabs": "1.1.3",
"@radix-ui/react-tooltip": "1.1.8",
- "@react-pdf/layout": "4.3.1",
- "@react-pdf/renderer": "4.2.4",
+ "@react-pdf/renderer": "4.3.0",
"@sentry/nextjs": "9.3.0",
"@vercel/speed-insights": "1.2.0",
"class-variance-authority": "0.7.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f9c6d54..f374cfc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -44,12 +44,9 @@ importers:
'@radix-ui/react-tooltip':
specifier: 1.1.8
- '@react-pdf/layout':
- specifier: 4.3.1
- version: 4.3.1
'@react-pdf/renderer':
- specifier: 4.2.4
- version: 4.2.4([email protected])
+ specifier: 4.3.0
+ version: 4.3.0([email protected])
'@sentry/nextjs':
specifier: 9.3.0
@@ -1149,17 +1146,17 @@ packages:
'@react-pdf/[email protected]':
resolution: {integrity: sha512-qTKGUf0iAMGg2+OsUcp9ffKnKi41RukM/zYIWMDJ4hRVYSr89Q7e3wSDW/Koqx3ea3Uy/z3h2y3wPX6Bdfxk6g==}
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-MGBDVArLL65F+M2o+mwNbU4FuiuBIZpYjs/22L1dFbdhEYodSk9A9nj1e6ykRHzygwOye175ZTMK3ZpHrHXXdg==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-/dAWu7Y2RD1RxarDZ9SkYPHgBYOhmcDnet4W/qN/m8k+A2Hr3ja54GymSR7GGxWBtxjKtNauVKrTa9LS1n8WUw==}
'@react-pdf/[email protected]':
resolution: {integrity: sha512-lvP5ryzYM3wpbO9bvqLZYwEr5XBDX9jcaRICvtnoRqdJOo7PRrMnmB4MMScyb+Xw10mGeIubZAAomNAG5ONQZQ==}
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-kjJDIj5XX5LU2+gvGIjVggWMa3oL3m3r59aEQY7Y/6HtLnKUay0dw2PVAJvLqa8mh3REwkGvLpvKEnTbv89/xA==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-Aq+Cc6JYausWLoks2FvHe3PwK9cTuvksB2uJ0AnkKJEUtQbvCq8eCRb1bjbbwIji9OzFRTTzZij7LzkpKHjIeA==}
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-pyYFAI7YL5Oud60W+wcu9zsN73tg8XgHGtEM8FQ6PY4RgEKp+AXkj+YE2hKuX3eOVB65MPzbJbVWtTjO3MPa5g==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-k+Lsuq8vTwWsCqTp+CCB4+2N+sOTFrzwGA7aw3H9ix/PDWR9QksbmNg0YkzGbLAPI6CeawmiLHcf4trZ5ecLPQ==}
'@react-pdf/[email protected]':
resolution: {integrity: sha512-eSJnEItZ37WPt6Qv5pncQDxLJRK15eaRwPT+gZoujP548CodenOVp49GST8XJvKMFt9YqIBzGBV/j9AgrOQzVA==}
@@ -1172,22 +1169,22 @@ packages:
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-tDFnZ02PuGdDgx4tFoH1ysd/jQ9sH37/MIj+3oMvWfluzFDBmMubp9zzVhe6nDFI0S5yDHBoO2Ak6K/SAV8/dw==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-MdWfWaqO6d7SZD75TZ2z5L35V+cHpyA43YNRlJNG0RJ7/MeVGDQv12y/BXOJgonZKkeEGdzM3EpAt9/g4E22WA==}
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-WakhgFvPTPNbZCOBEZb0Ai0cWYAlFRLSeuJpipsH32GfEzQX9ngU9YSCb4UIXW8LcbHjED/yzOcY6nm6o0ksNw==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-28gpA69fU9ZQrDzmd5xMJa1bDf8t0PT3ApUKBl2PUpoE/x4JlvCB5X66nMXrfFrgF2EZrA72zWQAkvbg7TE8zw==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-kV8aIcFZDgM6cLyzukydvOXLoB+uxNpZz9llDwnzXWhJnmhN5ItFrqrcywrWBK91ChvsC6AoIblYT/IvS2SDIA==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-BGZ2sYNUp38VJUegjva/jsri3iiRGnVNjWI+G9dTwAvLNOmwFvSJzqaCsEnqQ/DW5mrTBk/577FhDY7pv6AidA==}
'@react-pdf/[email protected]':
resolution: {integrity: sha512-fDt19KWaJRK/n2AaFoVm31hgGmpygmTV7LsHGJNGZkgzXcFyLsx+XUl63DTDPH3iqxj3xUX128t104GtOz8tTw==}
- '@react-pdf/[email protected]':
- resolution: {integrity: sha512-FE4BiWdbdPK15KZWO8laiIhqpZgDMGzp+CUdOjAGitdn9ANgsNrlZHHR+fX7uHlNXqs4OwsW7Pv3QYIPfPqtPA==}
+ '@react-pdf/[email protected]':
+ resolution: {integrity: sha512-ckj80vZLlvl9oYrQ4tovEaqKWP3O06Eb1D48/jQWbdwz1Yh7Y9v1cEmwlP8ET+a1Whp8xfdM0xduMexkuPANCQ==}
'@rollup/[email protected]':
resolution: {integrity: sha512-+tNWdlWKbpB3WgBN7ijjYkq9X5uhjmcvyjEght4NmH5fAU++zfQzAJ6wumLS+dNcvwEZhKx2Z+skY8m7v0wGSA==}
@@ -1542,6 +1539,11 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
+ resolution: {integrity: sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==}
+ engines: {node: '>=0.4.0'}
+ hasBin: true
+
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -3265,8 +3267,8 @@ packages:
resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-jDLYqo7oF8tJIttjXO6jBY5Hk8p3A8W4ttih7cCEq64fQFWmgJ4VqAQjKr7WwIDlmXKEc6QeoRb5ecjZ+2afcg==}
+ resolution: {integrity: sha512-vkZjpUjb6OMS7dhV+tILUW6BhpDR7P2L/aQSAv+Uwk+m8KATX9EccViHTJR2qDtACKPIYndLGCyl3FMo+r2LMw==}
engines: {node: '>= 10.13.0'}
peerDependencies:
'@swc/core': '*'
@@ -4548,10 +4550,10 @@ snapshots:
'@react-pdf/[email protected]': {}
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
- '@react-pdf/pdfkit': 4.0.2
- '@react-pdf/types': 2.8.2
+ '@react-pdf/pdfkit': 4.0.3
+ '@react-pdf/types': 2.9.0
fontkit: 2.0.4
is-url: 1.2.4
@@ -4560,19 +4562,19 @@ snapshots:
'@react-pdf/png-js': 3.0.0
jay-peg: 1.1.1
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
'@react-pdf/fns': 3.1.2
'@react-pdf/image': 3.0.3
'@react-pdf/primitives': 4.1.1
- '@react-pdf/stylesheet': 6.0.2
+ '@react-pdf/stylesheet': 6.1.0
'@react-pdf/textkit': 6.0.0
- '@react-pdf/types': 2.8.2
+ '@react-pdf/types': 2.9.0
emoji-regex: 10.4.0
queue: 6.0.2
yoga-layout: 3.2.1
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
'@babel/runtime': 7.26.9
'@react-pdf/png-js': 3.0.0
@@ -4595,40 +4597,40 @@ snapshots:
react: 18.3.1
scheduler: 0.25.0-rc-603e6108-20241029
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
'@babel/runtime': 7.26.9
'@react-pdf/fns': 3.1.2
'@react-pdf/primitives': 4.1.1
'@react-pdf/textkit': 6.0.0
- '@react-pdf/types': 2.8.2
+ '@react-pdf/types': 2.9.0
abs-svg-path: 0.1.1
color-string: 1.9.1
normalize-svg-path: 1.1.0
parse-svg-path: 0.1.2
svg-arc-to-cubic-bezier: 3.2.0
dependencies:
'@babel/runtime': 7.26.9
'@react-pdf/fns': 3.1.2
- '@react-pdf/font': 4.0.1
- '@react-pdf/layout': 4.3.1
- '@react-pdf/pdfkit': 4.0.2
+ '@react-pdf/font': 4.0.2
+ '@react-pdf/layout': 4.4.0
+ '@react-pdf/pdfkit': 4.0.3
'@react-pdf/primitives': 4.1.1
'@react-pdf/reconciler': 1.1.4([email protected])
- '@react-pdf/render': 4.2.1
- '@react-pdf/types': 2.8.2
+ '@react-pdf/render': 4.3.0
+ '@react-pdf/types': 2.9.0
events: 3.3.0
object-assign: 4.1.1
prop-types: 15.8.1
queue: 6.0.2
react: 18.3.1
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
'@react-pdf/fns': 3.1.2
- '@react-pdf/types': 2.8.2
+ '@react-pdf/types': 2.9.0
color-string: 1.9.1
hsl-to-hex: 1.0.0
media-engine: 1.0.3
@@ -4641,11 +4643,11 @@ snapshots:
hyphen: 1.10.6
unicode-properties: 1.4.1
- '@react-pdf/[email protected]':
+ '@react-pdf/[email protected]':
dependencies:
- '@react-pdf/font': 4.0.1
+ '@react-pdf/font': 4.0.2
'@react-pdf/primitives': 4.1.1
- '@react-pdf/stylesheet': 6.0.2
+ '@react-pdf/stylesheet': 6.1.0
dependencies:
@@ -5103,6 +5105,8 @@ snapshots:
+
dependencies:
debug: 4.3.7
@@ -6972,7 +6976,7 @@ snapshots:
dependencies:
'@jridgewell/trace-mapping': 0.3.25
jest-worker: 27.5.1
@@ -6984,7 +6988,7 @@ snapshots:
dependencies:
'@jridgewell/source-map': 0.3.6
- acorn: 8.14.0
+ acorn: 8.14.1
commander: 2.20.3
source-map-support: 0.5.21
@@ -7146,7 +7150,7 @@ snapshots:
'@webassemblyjs/ast': 1.14.1
'@webassemblyjs/wasm-edit': 1.14.1
'@webassemblyjs/wasm-parser': 1.14.1
- acorn: 8.14.0
+ acorn: 8.14.1
browserslist: 4.24.4
chrome-trace-event: 1.0.4
enhanced-resolve: 5.18.1
@@ -7161,7 +7165,7 @@ snapshots:
neo-async: 2.6.2
schema-utils: 4.3.0
tapable: 2.2.1
- terser-webpack-plugin: 5.3.12([email protected])
+ terser-webpack-plugin: 5.3.14([email protected])
watchpack: 2.4.2
webpack-sources: 3.2.3
transitivePeerDependencies:
diff --git a/src/app/components/invoice-form.tsx b/src/app/components/invoice-form.tsx
index b03d52e..0157519 100644
--- a/src/app/components/invoice-form.tsx
+++ b/src/app/components/invoice-form.tsx
@@ -10,13 +10,13 @@ import {
type InvoiceItemData,
} from "@/app/schema";
import { SellerManagement } from "@/components/seller-management";
+import { BuyerManagement } from "@/components/buyer-management";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
-import { Button } from "@/components/ui/button";
import { ButtonHelper } from "@/components/ui/button-helper";
import { Input } from "@/components/ui/input";
import { InputHelperMessage } from "@/components/ui/input-helper-message";
@@ -758,6 +758,7 @@ export function InvoiceForm({
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="relative flex items-end justify-end gap-2">
+ {/* Create/edit/delete seller */}
<SellerManagement
setValue={setValue}
invoiceData={invoiceData}
@@ -1012,34 +1013,10 @@ export function InvoiceForm({
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="relative flex items-end justify-end gap-2">
- {/* New Buyer TEMPORARY Placeholder Button (will be replaced with a real button when the feature is implemented)*/}
- <div className="flex flex-col items-start gap-0.5">
- <CustomTooltip
- trigger={
- <Button
- _variant="outline"
- _size="sm"
- aria-disabled={true}
- className="cursor-not-allowed bg-gray-50 opacity-40 transition-all hover:bg-gray-100 dark:bg-gray-900"
- >
- New Buyer
- <Plus className="ml-1.5 h-3 w-3 text-gray-500" />
- </Button>
- }
- content={
- <span className="flex items-center gap-1">
- <span>Coming soon</span>
- <span className="text-sm">✨</span>
- </span>
- }
- />
- <div className="flex items-center gap-1 xl:hidden">
- <span className="pl-1 text-xs font-medium tracking-wide text-gray-700">
- Coming soon
- </span>
- <span className="text-sm">✨</span>
- </div>
- </div>
+ <BuyerManagement
+ setValue={setValue}
+ invoiceData={invoiceData}
+ />
</div>
<div className="space-y-4">
<div>
diff --git a/src/app/components/invoice-pdf-download-multiple-languages.tsx b/src/app/components/invoice-pdf-download-multiple-languages.tsx
new file mode 100644
index 0000000..cd30e23
--- /dev/null
+++ b/src/app/components/invoice-pdf-download-multiple-languages.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+import { useOpenPanel } from "@openpanel/nextjs";
+import { pdf } from "@react-pdf/renderer";
+import { saveAs } from "file-saver";
+import JSZip from "jszip";
+import { toast } from "sonner";
+import {
+ LANGUAGE_TO_LABEL,
+ SUPPORTED_LANGUAGES,
+ type InvoiceData,
+ type SupportedLanguages,
+} from "../schema";
+import { InvoicePdfTemplate } from "./invoice-pdf-template";
+
+import { MultiSelect } from "@/components/ui/multi-select";
+import { useEffect, useState } from "react";
+
+const SUPPORTED_LANGUAGES_OPTIONS = SUPPORTED_LANGUAGES.map((language) => {
+ return {
+ label: LANGUAGE_TO_LABEL[language],
+ value: language,
+ };
+});
+
+// TODO: add later when PRO version is released, this is PRO FEATURE =)
+// TODO: allow to select languages that user wants to download. Use select multiple component https://github.com/sersavan/shadcn-multi-select-component but style it like a button when merging PR on github with multiple options to select from dropdown
+/**
+ * This component is used to download all PDFs in multiple languages
+ */
+export function InvoicePDFDownloadMultipleLanguages({
+ invoiceData,
+}: {
+ invoiceData: InvoiceData;
+}) {
+ const language = invoiceData.language;
+
+ const [selectedLanguages, setSelectedLanguages] = useState<
+ SupportedLanguages[]
+ >([language]);
+
+ const openPanel = useOpenPanel();
+
+ useEffect(() => {
+ if (language) {
+ setSelectedLanguages([language]);
+ }
+ }, [language]);
+
+ const generateAndZipPDFs = async (
+ selectedLanguages: SupportedLanguages[]
+ ) => {
+ try {
+ // Generate PDF documents for each selected language
+ const pdfPromises = selectedLanguages.map((lang) => {
+ const document = (
+ <InvoicePdfTemplate
+ invoiceData={{ ...invoiceData, language: lang }}
+ />
+ );
+ return pdf(document).toBlob();
+ });
+
+ // Wait for all PDFs to generate
+ const pdfBlobs = await Promise.all(pdfPromises);
+
+ // Track analytics
+ openPanel.track("generate_multiple_pdfs_zip");
+ umamiTrackEvent("generate_multiple_pdfs_zip");
+
+ // If only one language is selected, download directly without zipping
+ if (pdfBlobs.length === 1) {
+ const fileName = `invoice-${selectedLanguages[0]}-${invoiceData.invoiceNumber.replace("/", "-")}.pdf`;
+ saveAs(pdfBlobs[0], fileName);
+ return;
+ }
+
+ const invoiceNumber = invoiceData.invoiceNumber.replace("/", "-");
+
+ // Create zip file for multiple languages
+ const zip = new JSZip();
+
+ // Add each PDF to the zip
+ selectedLanguages.forEach((lang, index) => {
+ zip.file(`invoice-${lang}-${invoiceNumber}.pdf`, pdfBlobs[index]);
+ });
+
+ // 'en-de-fr'
+ const languages = selectedLanguages.join("-");
+
+ // Generate and download zip
+ const zipContent = await zip.generateAsync({ type: "blob" });
+ const zipFileName = `invoice-${invoiceNumber}-${languages}-archive.zip`;
+
+ saveAs(zipContent, zipFileName);
+ } catch (error) {
+ toast.error("Error generating PDF archive");
+ console.error(error);
+ }
+ };
+
+ return (
+ <>
+ <MultiSelect
+ options={SUPPORTED_LANGUAGES_OPTIONS}
+ onValueChange={(value) => {
+ setSelectedLanguages(value as SupportedLanguages[]);
+ }}
+ selectedLanguages={selectedLanguages}
+ setSelectedLanguages={setSelectedLanguages}
+ placeholder="Download PDF"
+ variant="inverted"
+ maxCount={3}
+ handleDownload={() =>
+ generateAndZipPDFs(selectedLanguages.map((lang) => lang))
+ }
+ />
+ </>
+ );
+}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 68f9af6..abbdcd0 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -20,6 +20,7 @@ import { PDF_DATA_LOCAL_STORAGE_KEY } from "./components/invoice-form";
import { InvoicePDFDownloadLink } from "./components/invoice-pdf-download-link";
import { INITIAL_INVOICE_DATA } from "./constants";
import { cn } from "@/lib/utils";
+import { InvoicePDFDownloadMultipleLanguages } from "./components/invoice-pdf-download-multiple-languages";
export default function Home() {
const router = useRouter();
@@ -241,6 +242,13 @@ export default function Home() {
{isDesktop ? (
<InvoicePDFDownloadLink invoiceData={invoiceDataState} />
) : null}
+
+ {/* TODO: add later when PRO version is released, this is PRO FEATURE =) */}
+ {/* {isDesktop ? (
+ <InvoicePDFDownloadMultipleLanguages
+ invoiceData={invoiceDataState}
+ />
+ ) : null} */}
</div>
</div>
<div className="mb-4 flex flex-row items-center justify-center lg:mb-0 lg:mt-4 lg:justify-start xl:mt-0">
diff --git a/src/app/schema/index.ts b/src/app/schema/index.ts
index 1a5cd83..ab904ed 100644
--- a/src/app/schema/index.ts
+++ b/src/app/schema/index.ts
@@ -248,7 +248,17 @@ export const DEFAULT_SELLER_DATA = {
swiftBic: "Seller swift bic",
swiftBicFieldIsVisible: true,
-} as const satisfies SellerData;
+} as const satisfies Omit<SellerData, "id">;
+
+export const DEFAULT_BUYER_DATA = {
+ name: "Buyer name",
+ address: "Buyer address",
+
+ vatNo: "Buyer vat number",
+ vatNoFieldIsVisible: true,
+
+ email: "[email protected]",
+} as const satisfies Omit<BuyerData, "id">;
/**
* Accordion state schema
diff --git a/src/components/buyer-dialog.tsx b/src/components/buyer-dialog.tsx
new file mode 100644
index 0000000..ef5f3cd
--- /dev/null
+++ b/src/components/buyer-dialog.tsx
@@ -0,0 +1,315 @@
+"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 { buyerSchema, type BuyerData } 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 { BUYERS_LOCAL_STORAGE_KEY } from "./buyer-management";
+import { z } from "zod";
+import { useState } from "react";
+import * as Sentry from "@sentry/nextjs";
+
+const BUYER_FORM_ID = "buyer-form";
+
+interface BuyerDialogProps {
+ isOpen: boolean;
+ onClose: React.Dispatch<React.SetStateAction<boolean>>;
+ handleBuyerAdd?: (
+ buyer: BuyerData,
+ { shouldApplyNewBuyerToInvoice }: { shouldApplyNewBuyerToInvoice: boolean }
+ ) => void;
+ handleBuyerEdit?: (buyer: BuyerData) => void;
+ initialData: BuyerData | null;
+ isEditMode: boolean;
+}
+
+export function BuyerDialog({
+ isOpen,
+ onClose,
+ handleBuyerAdd,
+ handleBuyerEdit,
+ initialData,
+ isEditMode,
+}: BuyerDialogProps) {
+ const form = useForm<BuyerData>({
+ resolver: zodResolver(buyerSchema),
+ defaultValues: {
+ id: initialData?.id ?? "",
+ name: initialData?.name ?? "",
+ address: initialData?.address ?? "",
+ vatNo: initialData?.vatNo ?? "",
+ email: initialData?.email ?? "",
+ vatNoFieldIsVisible: initialData?.vatNoFieldIsVisible ?? true,
+ },
+ });
+
+ const [shouldApplyNewBuyerToInvoice, setShouldApplyNewBuyerToInvoice] =
+ useState(false);
+
+ function onSubmit(formValues: BuyerData) {
+ try {
+ // **RUNNING SOME VALIDATIONS FIRST**
+
+ // Get existing buyers or initialize empty array
+ const buyers = localStorage.getItem(BUYERS_LOCAL_STORAGE_KEY);
+ const existingBuyers = buyers ? JSON.parse(buyers) : [];
+
+ // Validate existing buyers array with Zod
+ const existingBuyersValidationResult = z
+ .array(buyerSchema)
+ .safeParse(existingBuyers);
+
+ if (!existingBuyersValidationResult.success) {
+ console.error(
+ "Invalid existing buyers data:",
+ existingBuyersValidationResult.error
+ );
+
+ // Show error toast
+ toast.error("Error loading existing buyers", {
+ richColors: true,
+ description: "Please try again",
+ });
+
+ // Reset localStorage if validation fails
+ localStorage.setItem(BUYERS_LOCAL_STORAGE_KEY, JSON.stringify([]));
+
+ return;
+ }
+
+ // Validate buyer data against existing buyers
+ const isDuplicateName = existingBuyers.some(
+ (buyer: BuyerData) =>
+ buyer.name === formValues.name && buyer.id !== formValues.id
+ );
+
+ if (isDuplicateName) {
+ form.setError("name", {
+ type: "manual",
+ message: "A buyer 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 buyer with this name already exists", {
+ richColors: true,
+ });
+
+ return;
+ }
+
+ if (isEditMode) {
+ // Edit buyer
+ handleBuyerEdit?.(formValues);
+ } else {
+ // Add new buyer
+ handleBuyerAdd?.(formValues, { shouldApplyNewBuyerToInvoice });
+ }
+
+ // Close dialog
+ onClose(false);
+
+ // Reset form
+ form.reset();
+ } catch (error) {
+ console.error("Failed to save buyer:", error);
+
+ toast.error("Failed to save buyer", {
+ description: "Please try again",
+ richColors: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ }
+
+ 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 Buyer" : "Add New Buyer"}
+ </DialogTitle>
+ <DialogDescription>
+ {isEditMode
+ ? "Edit the buyer details"
+ : "Add a new buyer 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={BUYER_FORM_ID}
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter buyer name"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="address"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Address</FormLabel>
+ <FormControl>
+ <Textarea
+ {...field}
+ rows={3}
+ placeholder="Enter buyer 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>
+ </form>
+ </Form>
+
+ {/* Apply new buyer to current invoice switch */}
+ {!isEditMode ? (
+ <div className="mt-4 flex items-center gap-2">
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={shouldApplyNewBuyerToInvoice}
+ onCheckedChange={setShouldApplyNewBuyerToInvoice}
+ id="apply-buyer-to-current-invoice-switch"
+ />
+ <Label htmlFor="apply-buyer-to-current-invoice-switch">
+ Apply Buyer 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="button"
+ onClick={async () => {
+ // validate the form
+ const isValid = await form.trigger();
+ if (!isValid) return;
+
+ // submit the form
+ onSubmit(form.getValues());
+ }}
+ form={BUYER_FORM_ID}
+ >
+ Save Buyer
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/buyer-management.tsx b/src/components/buyer-management.tsx
new file mode 100644
index 0000000..b4847b4
--- /dev/null
+++ b/src/components/buyer-management.tsx
@@ -0,0 +1,380 @@
+"use client";
+
+import { Plus, Trash2, Pencil } 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 { BuyerDialog } from "./buyer-dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "./ui/alert-dialog";
+import type { UseFormSetValue } from "react-hook-form";
+import {
+ DEFAULT_BUYER_DATA,
+ buyerSchema,
+ type InvoiceData,
+ type BuyerData,
+} from "@/app/schema";
+import { z } from "zod";
+import { toast } from "sonner";
+import { cn } from "@/lib/utils";
+import { Label } from "./ui/label";
+import { useOpenPanel } from "@openpanel/nextjs";
+import { isLocalStorageAvailable } from "@/lib/check-local-storage";
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+import * as Sentry from "@sentry/nextjs";
+
+export const BUYERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_BUYERS";
+
+export function BuyerManagement({
+ setValue,
+ invoiceData,
+}: {
+ setValue: UseFormSetValue<InvoiceData>;
+ invoiceData: InvoiceData;
+}) {
+ const [isBuyerDialogOpen, setIsBuyerDialogOpen] = useState(false);
+ const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
+
+ const [buyersSelectOptions, setBuyersSelectOptions] = useState<BuyerData[]>(
+ []
+ );
+ const [selectedBuyerIndex, setSelectedBuyerIndex] = useState("");
+ const [editingBuyer, setEditingBuyer] = useState<BuyerData | null>(null);
+
+ const openPanel = useOpenPanel();
+ const buyerSelectId = useId();
+
+ const isEditMode = Boolean(editingBuyer);
+
+ // Load buyers from localStorage on component mount
+ useEffect(() => {
+ try {
+ const savedBuyers = localStorage.getItem(BUYERS_LOCAL_STORAGE_KEY);
+ const parsedBuyers = savedBuyers ? JSON.parse(savedBuyers) : [];
+
+ // Validate buyers array with Zod
+ const buyersSchema = z.array(buyerSchema);
+ const validationResult = buyersSchema.safeParse(parsedBuyers);
+
+ if (!validationResult.success) {
+ console.error("Invalid buyers data:", validationResult.error);
+ return;
+ }
+
+ const selectedBuyer = validationResult.data.find((buyer: BuyerData) => {
+ return buyer?.id === invoiceData?.buyer?.id;
+ });
+
+ setBuyersSelectOptions(validationResult.data);
+ setSelectedBuyerIndex(selectedBuyer?.id ?? "");
+ } catch (error) {
+ console.error("Failed to load buyers:", error);
+
+ Sentry.captureException(error);
+ }
+ }, [invoiceData?.buyer?.id]);
+
+ // Update buyers when a new one is added
+ const handleBuyerAdd = (
+ newBuyer: BuyerData,
+ { shouldApplyNewBuyerToInvoice }: { shouldApplyNewBuyerToInvoice: boolean }
+ ) => {
+ try {
+ const newBuyerWithId = {
+ ...newBuyer,
+ // Generate a unique ID for the new buyer (IMPORTANT!) =)
+ id: Date.now().toString(),
+ };
+
+ const newBuyers = [...buyersSelectOptions, newBuyerWithId];
+
+ // Save to localStorage
+ localStorage.setItem(BUYERS_LOCAL_STORAGE_KEY, JSON.stringify(newBuyers));
+
+ // Update the buyers state
+ setBuyersSelectOptions(newBuyers);
+
+ // Apply the new buyer to the invoice if the user wants to, otherwise just add it to the list and use it later if needed
+ if (shouldApplyNewBuyerToInvoice) {
+ setValue("buyer", newBuyerWithId);
+ setSelectedBuyerIndex(newBuyerWithId?.id);
+ }
+
+ toast.success("Buyer added successfully", {
+ richColors: true,
+ });
+
+ // analytics track event
+ openPanel.track("add_buyer_success");
+ umamiTrackEvent("add_buyer_success");
+ } catch (error) {
+ console.error("Failed to add buyer:", error);
+
+ toast.error("Failed to add buyer", {
+ closeButton: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ };
+
+ // Update buyers when edited
+ const handleBuyerEdit = (editedBuyer: BuyerData) => {
+ try {
+ const updatedBuyers = buyersSelectOptions.map((buyer) =>
+ buyer.id === editedBuyer.id ? editedBuyer : buyer
+ );
+
+ localStorage.setItem(
+ BUYERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(updatedBuyers)
+ );
+
+ setBuyersSelectOptions(updatedBuyers);
+ setValue("buyer", editedBuyer);
+
+ // end edit mode
+ setEditingBuyer(null);
+
+ toast.success("Buyer updated successfully", {
+ richColors: true,
+ });
+
+ // analytics track event
+ openPanel.track("edit_buyer_success");
+ umamiTrackEvent("edit_buyer_success");
+ } catch (error) {
+ console.error("Failed to edit buyer:", error);
+
+ toast.error("Failed to edit buyer", {
+ closeButton: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ };
+
+ const handleBuyerChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
+ const id = event.target.value;
+
+ if (id) {
+ setSelectedBuyerIndex(id);
+ const selectedBuyer = buyersSelectOptions.find(
+ (buyer) => buyer.id === id
+ );
+
+ if (selectedBuyer) {
+ setValue("buyer", selectedBuyer);
+ }
+ } else {
+ // Clear the buyer from the form if the user selects the empty option
+ setSelectedBuyerIndex("");
+ setValue("buyer", DEFAULT_BUYER_DATA);
+ }
+
+ // analytics track event
+ openPanel.track("change_buyer");
+ umamiTrackEvent("change_buyer");
+ };
+
+ const handleDeleteBuyer = () => {
+ try {
+ setBuyersSelectOptions((prevBuyers) => {
+ const updatedBuyers = prevBuyers.filter(
+ (buyer) => buyer.id !== selectedBuyerIndex
+ );
+
+ localStorage.setItem(
+ BUYERS_LOCAL_STORAGE_KEY,
+ JSON.stringify(updatedBuyers)
+ );
+ return updatedBuyers;
+ });
+ // Clear the selected buyer index
+ setSelectedBuyerIndex("");
+ // Clear the buyer from the form if it was selected
+ setValue("buyer", DEFAULT_BUYER_DATA);
+
+ // Close the delete dialog
+ setIsDeleteDialogOpen(false);
+
+ toast.success("Buyer deleted successfully", {
+ richColors: true,
+ });
+
+ // analytics track event
+ openPanel.track("delete_buyer_success");
+ umamiTrackEvent("delete_buyer_success");
+ } catch (error) {
+ console.error("Failed to delete buyer:", error);
+
+ toast.error("Failed to delete buyer", {
+ closeButton: true,
+ });
+
+ Sentry.captureException(error);
+ }
+ };
+
+ const activeBuyer = buyersSelectOptions.find(
+ (buyer) => buyer.id === selectedBuyerIndex
+ );
+
+ return (
+ <>
+ <div className="flex flex-col gap-2">
+ {buyersSelectOptions.length > 0 ? (
+ <div className="space-y-1">
+ <div className="flex items-center gap-1">
+ <Label htmlFor={buyerSelectId} className="">
+ Select Buyer
+ </Label>
+ </div>
+ <div className="flex gap-2">
+ <SelectNative
+ id={buyerSelectId}
+ className={cn(
+ "block h-8 max-w-[200px] text-[12px]",
+ !selectedBuyerIndex && "italic text-gray-700"
+ )}
+ onChange={handleBuyerChange}
+ value={selectedBuyerIndex}
+ title={activeBuyer?.name}
+ >
+ <option value="">No buyer selected (default)</option>
+ {buyersSelectOptions.map((buyer) => (
+ <option key={buyer.id} value={buyer.id}>
+ {buyer.name}
+ </option>
+ ))}
+ </SelectNative>
+
+ {selectedBuyerIndex ? (
+ <div className="flex items-center gap-2">
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="outline"
+ _size="sm"
+ onClick={() => {
+ if (activeBuyer) {
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ setEditingBuyer(activeBuyer);
+ setIsBuyerDialogOpen(true);
+ }
+ }}
+ className="h-8 px-2"
+ >
+ <Pencil className="h-3 w-3" />
+ </Button>
+ }
+ content="Edit buyer"
+ />
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="destructive"
+ _size="sm"
+ onClick={() => {
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ setIsDeleteDialogOpen(true);
+ }}
+ className="h-8 px-2"
+ >
+ <Trash2 className="h-3 w-3" />
+ </Button>
+ }
+ content="Delete buyer"
+ />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ ) : null}
+
+ <CustomTooltip
+ trigger={
+ <Button
+ _variant="outline"
+ _size="sm"
+ onClick={() => {
+ if (isLocalStorageAvailable) {
+ // dismiss any existing toast for better UX
+ toast.dismiss();
+
+ // open buyer dialog
+ setIsBuyerDialogOpen(true);
+ }
+ }}
+ aria-disabled={!isLocalStorageAvailable}
+ className={cn(
+ !isLocalStorageAvailable && "cursor-not-allowed opacity-40"
+ )}
+ >
+ New Buyer
+ <Plus className="ml-1 h-3 w-3" />
+ </Button>
+ }
+ content={
+ isLocalStorageAvailable
+ ? "You can save multiple buyers to use them later"
+ : "Local storage is not available in your browser. Please enable it or try another browser"
+ }
+ />
+ </div>
+
+ <BuyerDialog
+ // we need to rerender the dialog when the editingBuyer changes
+ key={editingBuyer?.id}
+ isOpen={isBuyerDialogOpen}
+ onClose={() => {
+ setIsBuyerDialogOpen(false);
+ setEditingBuyer(null);
+ }}
+ handleBuyerAdd={handleBuyerAdd}
+ handleBuyerEdit={handleBuyerEdit}
+ initialData={editingBuyer}
+ isEditMode={isEditMode}
+ />
+
+ {/* Delete alert buyer dialog */}
+ <AlertDialog
+ open={isDeleteDialogOpen}
+ onOpenChange={setIsDeleteDialogOpen}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Buyer</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete{" "}
+ <span className="font-bold">&quot;{activeBuyer?.name}&quot;</span>{" "}
+ buyer? This action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleDeleteBuyer}
+ className="bg-red-500 text-red-50 hover:bg-red-500/90"
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx
new file mode 100644
index 0000000..217baa6
--- /dev/null
+++ b/src/components/ui/badge.tsx
@@ -0,0 +1,36 @@
+import * as React from "react"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+
+const badgeVariants = cva(
+ "inline-flex items-center rounded-full border border-slate-200 px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-slate-950 focus:ring-offset-2 dark:border-slate-800 dark:focus:ring-slate-300",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-transparent bg-slate-900 text-slate-50 hover:bg-slate-900/80 dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/80",
+ secondary:
+ "border-transparent bg-slate-100 text-slate-900 hover:bg-slate-100/80 dark:bg-slate-800 dark:text-slate-50 dark:hover:bg-slate-800/80",
+ destructive:
+ "border-transparent bg-red-500 text-slate-50 hover:bg-red-500/80 dark:bg-red-900 dark:text-slate-50 dark:hover:bg-red-900/80",
+ outline: "text-slate-950 dark:text-slate-50",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+)
+
+export interface BadgeProps
+ extends React.HTMLAttributes<HTMLDivElement>,
+ VariantProps<typeof badgeVariants> {}
+
+function Badge({ className, variant, ...props }: BadgeProps) {
+ return (
+ <div className={cn(badgeVariants({ variant }), className)} {...props} />
+ )
+}
+
+export { Badge, badgeVariants }
diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx
new file mode 100644
index 0000000..6cac29a
--- /dev/null
+++ b/src/components/ui/command.tsx
@@ -0,0 +1,153 @@
+"use client";
+
+import * as React from "react";
+import { type DialogProps } from "@radix-ui/react-dialog";
+import { Command as CommandPrimitive } from "cmdk";
+import { Search } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
+
+const Command = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive
+ ref={ref}
+ className={cn(
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-slate-950 dark:bg-slate-950 dark:text-slate-50",
+ className
+ )}
+ {...props}
+ />
+));
+Command.displayName = CommandPrimitive.displayName;
+
+const CommandDialog = ({ children, ...props }: DialogProps) => {
+ return (
+ <Dialog {...props}>
+ <DialogContent className="overflow-hidden p-0 shadow-lg">
+ <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-slate-500 dark:[&_[cmdk-group-heading]]:text-slate-400 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
+ {children}
+ </Command>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+const CommandInput = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Input>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
+>(({ className, ...props }, ref) => (
+ <div className="flex items-center border-b px-3" cmdk-input-wrapper="">
+ <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ ref={ref}
+ className={cn(
+ "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-slate-500 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-slate-400",
+ className
+ )}
+ {...props}
+ />
+ </div>
+));
+
+CommandInput.displayName = CommandPrimitive.Input.displayName;
+
+const CommandList = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.List>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.List
+ ref={ref}
+ className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
+ {...props}
+ />
+));
+
+CommandList.displayName = CommandPrimitive.List.displayName;
+
+const CommandEmpty = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Empty>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
+>((props, ref) => (
+ <CommandPrimitive.Empty
+ ref={ref}
+ className="py-6 text-center text-sm"
+ {...props}
+ />
+));
+
+CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
+
+const CommandGroup = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Group>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Group
+ ref={ref}
+ className={cn(
+ "overflow-hidden p-1 text-slate-950 dark:text-slate-50 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-slate-500 dark:[&_[cmdk-group-heading]]:text-slate-400",
+ className
+ )}
+ {...props}
+ />
+));
+
+CommandGroup.displayName = CommandPrimitive.Group.displayName;
+
+const CommandSeparator = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 h-px bg-slate-200 dark:bg-slate-800", className)}
+ {...props}
+ />
+));
+CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
+
+const CommandItem = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-slate-100 data-[selected=true]:text-slate-900 data-[disabled=true]:opacity-50 dark:data-[selected='true']:bg-slate-800 dark:data-[selected=true]:text-slate-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ className
+ )}
+ {...props}
+ />
+));
+
+CommandItem.displayName = CommandPrimitive.Item.displayName;
+
+const CommandShortcut = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span
+ className={cn(
+ "ml-auto text-xs tracking-widest text-slate-500 dark:text-slate-400",
+ className
+ )}
+ {...props}
+ />
+ );
+};
+CommandShortcut.displayName = "CommandShortcut";
+
+export {
+ Command,
+ CommandDialog,
+ CommandInput,
+ CommandList,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandShortcut,
+ CommandSeparator,
+};
diff --git a/src/components/ui/money-input.tsx b/src/components/ui/money-input.tsx
index 160e839..efbe5f8 100644
--- a/src/components/ui/money-input.tsx
+++ b/src/components/ui/money-input.tsx
@@ -35,7 +35,7 @@ const MoneyInput = React.forwardRef<
)}
placeholder="0.00"
/>
- <span className="border-input text-muted-foreground inline-flex items-center rounded-e-lg border bg-background px-3 text-sm">
+ <span className="inline-flex items-center rounded-e-lg border border-gray-300 bg-background px-3 text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow">
{shownCurrencyText}
</span>
</div>
@@ -73,7 +73,7 @@ const ReadOnlyMoneyInput = React.forwardRef<
readOnly
title="This field is read-only"
/>
- <span className="inline-flex cursor-default items-center rounded-e-lg border border-gray-300 bg-gray-100 px-3 text-sm">
+ <span className="inline-flex cursor-default items-center rounded-e-lg border border-gray-300 bg-gray-100 px-3 text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow">
{shownCurrencyText}
</span>
</div>
diff --git a/src/components/ui/multi-select.tsx b/src/components/ui/multi-select.tsx
new file mode 100644
index 0000000..ea13b03
--- /dev/null
+++ b/src/components/ui/multi-select.tsx
@@ -0,0 +1,376 @@
+// src/components/multi-select.tsx
+
+import * as React from "react";
+import { cva, type VariantProps } from "class-variance-authority";
+import { CheckIcon, XCircle, ChevronDown, XIcon } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { Separator } from "@/components/ui/separator";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import { LANGUAGE_TO_LABEL } from "@/app/schema";
+import type { SupportedLanguages } from "@/app/schema";
+import { CustomTooltip } from "./tooltip";
+
+/**
+ * Variants for the multi-select component to handle different styles.
+ * Uses class-variance-authority (cva) to define different styles based on "variant" prop.
+ */
+const multiSelectVariants = cva(
+ "m-1 transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-300",
+ {
+ variants: {
+ variant: {
+ default:
+ "border-foreground/10 text-foreground bg-card hover:bg-card/80",
+ secondary:
+ "border-foreground/10 bg-secondary text-secondary-foreground hover:bg-secondary/80",
+ destructive:
+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
+ inverted: "inverted",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ }
+);
+
+/**
+ * Props for MultiSelect component
+ */
+interface MultiSelectProps
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof multiSelectVariants> {
+ /**
+ * An array of option objects to be displayed in the multi-select component.
+ * Each option object has a label, value, and an optional icon.
+ */
+ options: {
+ /** The text to display for the option. */
+ label: string;
+ /** The unique value associated with the option. */
+ value: string;
+ /** Optional icon component to display alongside the option. */
+ icon?: React.ComponentType<{ className?: string }>;
+ }[];
+
+ /**
+ * Callback function triggered when the selected values change.
+ * Receives an array of the new selected values.
+ */
+ onValueChange: (value: string[]) => void;
+
+ /** The default selected values when the component mounts. */
+ defaultValue?: string[];
+
+ /**
+ * Placeholder text to be displayed when no values are selected.
+ * Optional, defaults to "Select options".
+ */
+ placeholder?: string;
+
+ /**
+ * Animation duration in seconds for the visual effects (e.g., bouncing badges).
+ * Optional, defaults to 0 (no animation).
+ */
+ animation?: number;
+
+ /**
+ * Maximum number of items to display. Extra selected items will be summarized.
+ * Optional, defaults to 3.
+ */
+ maxCount?: number;
+
+ /**
+ * The modality of the popover. When set to true, interaction with outside elements
+ * will be disabled and only popover content will be visible to screen readers.
+ * Optional, defaults to false.
+ */
+ modalPopover?: boolean;
+
+ /**
+ * If true, renders the multi-select component as a child of another component.
+ * Optional, defaults to false.
+ */
+ asChild?: boolean;
+
+ /**
+ * Additional class names to apply custom styles to the multi-select component.
+ * Optional, can be used to add custom styles.
+ */
+ className?: string;
+
+ /**
+ * A function to handle the download action.
+ */
+ handleDownload?: () => Promise<void>;
+
+ /**
+ * The selected languages to be displayed in the multi-select component.
+ */
+ selectedLanguages: SupportedLanguages[];
+
+ /**
+ * A function to set the selected languages in the multi-select component.
+ */
+ setSelectedLanguages: (languages: SupportedLanguages[]) => void;
+}
+
+/**
+ * https://github.com/sersavan/shadcn-multi-select-component
+ */
+export const MultiSelect = React.forwardRef<
+ HTMLButtonElement,
+ MultiSelectProps
+>(
+ (
+ {
+ options,
+ onValueChange,
+ variant,
+ selectedLanguages = [],
+ setSelectedLanguages,
+ placeholder = "Select options",
+ maxCount = 3,
+ modalPopover = false,
+ // asChild = false,
+ className,
+ handleDownload,
+ ...props
+ },
+ ref
+ ) => {
+ const [isPopoverOpen, setIsPopoverOpen] = React.useState(false);
+
+ const handleInputKeyDown = (
+ event: React.KeyboardEvent<HTMLInputElement>
+ ) => {
+ if (event.key === "Enter") {
+ setIsPopoverOpen(true);
+ } else if (event.key === "Backspace" && !event.currentTarget.value) {
+ const newSelectedValues = [...selectedLanguages];
+ newSelectedValues.pop();
+ setSelectedLanguages(newSelectedValues);
+ onValueChange(newSelectedValues);
+ }
+ };
+
+ const toggleOption = (option: SupportedLanguages) => {
+ const newSelectedValues = selectedLanguages.includes(option)
+ ? selectedLanguages.filter((value) => value !== option)
+ : [...selectedLanguages, option];
+ setSelectedLanguages(newSelectedValues);
+ onValueChange(newSelectedValues);
+ };
+
+ const handleClear = () => {
+ setSelectedLanguages([]);
+ onValueChange([]);
+ };
+
+ const handleTogglePopover = () => {
+ setIsPopoverOpen((prev) => !prev);
+ };
+
+ const clearExtraOptions = () => {
+ const newSelectedValues = selectedLanguages.slice(0, maxCount);
+ setSelectedLanguages(newSelectedValues);
+ onValueChange(newSelectedValues);
+ };
+
+ return (
+ <Popover
+ open={isPopoverOpen}
+ onOpenChange={setIsPopoverOpen}
+ modal={modalPopover}
+ >
+ <PopoverTrigger asChild>
+ <div className="flex">
+ <CustomTooltip
+ content="Download PDF in selected languages"
+ trigger={
+ <Button
+ ref={ref}
+ {...props}
+ onClick={async (e) => {
+ e.stopPropagation();
+ if (selectedLanguages.length > 0 && handleDownload) {
+ await handleDownload();
+ } else if (selectedLanguages.length === 0) {
+ // If no languages are selected, open the popover
+ handleTogglePopover();
+ }
+ }}
+ className={cn(
+ "min-h- mb-4 h-auto rounded-l-lg rounded-r-none border-r-0 bg-slate-900 px-4 py-2 text-center text-sm font-medium text-slate-50 shadow-sm shadow-black/5 outline-offset-2 hover:bg-slate-900/90 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90 lg:mb-0",
+ selectedLanguages.length === 0 && "lg:w-[120px]",
+ selectedLanguages.length === 1 && "lg:w-[200px]",
+ selectedLanguages.length === 2 && "lg:w-[240px]",
+ selectedLanguages.length >= 3 && "lg:w-[280px]",
+ className
+ )}
+ >
+ <div className="flex w-full items-center">
+ <div className="flex flex-wrap items-center">
+ <span className="mr-1 text-sm">
+ {selectedLanguages.length > 0
+ ? "Download PDF in "
+ : placeholder}
+ </span>
+ {selectedLanguages
+ .slice(0, maxCount)
+ .map((value, index) => {
+ const isLast = index === selectedLanguages.length - 1;
+ const label =
+ LANGUAGE_TO_LABEL[value as SupportedLanguages];
+
+ return (
+ <React.Fragment key={value}>
+ {label}
+ {isLast ? "" : ", "}
+ </React.Fragment>
+ );
+ })}
+ {selectedLanguages.length > maxCount && (
+ <Badge
+ className={cn(
+ "border-foreground/1 bg-transparent text-foreground hover:bg-transparent",
+ multiSelectVariants({ variant })
+ )}
+ >
+ {`+ ${selectedLanguages.length - maxCount} more`}
+ <XCircle
+ className="ml-2 h-4 w-4 cursor-pointer"
+ onClick={(event) => {
+ event.stopPropagation();
+ clearExtraOptions();
+ }}
+ />
+ </Badge>
+ )}
+ </div>
+ </div>
+ </Button>
+ }
+ />
+ <div className="relative flex items-center">
+ <Separator orientation="vertical" className="h-[20px]" />
+ </div>
+ <CustomTooltip
+ content="Select languages to download"
+ trigger={
+ <Button
+ onClick={handleTogglePopover}
+ className={cn(
+ "mb-4 h-auto rounded-l-none rounded-r-lg border-l-0 bg-slate-900 px-2 py-2 text-center text-sm font-medium text-slate-50 shadow-sm shadow-black/5 outline-offset-2 hover:bg-slate-900/90 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90 lg:mb-0"
+ )}
+ >
+ <ChevronDown className="text-muted-foreground h-4 w-4" />
+ </Button>
+ }
+ ></CustomTooltip>
+ </div>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-auto p-0"
+ align="start"
+ onEscapeKeyDown={() => setIsPopoverOpen(false)}
+ >
+ <Command>
+ <CommandInput
+ placeholder="Search..."
+ onKeyDown={handleInputKeyDown}
+ />
+ <CommandList>
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandGroup>
+ {options.map((option) => {
+ const isSelected = selectedLanguages.includes(
+ option.value as SupportedLanguages
+ );
+ return (
+ <CommandItem
+ key={option.value}
+ onSelect={() =>
+ toggleOption(option.value as SupportedLanguages)
+ }
+ className="cursor-pointer"
+ >
+ <div
+ className={cn(
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-gray-500",
+ isSelected
+ ? "bg-gray-50 text-gray-900"
+ : "opacity-50 [&_svg]:invisible"
+ )}
+ >
+ <CheckIcon className="h-4 w-4" />
+ </div>
+ {option.icon && (
+ <option.icon className="mr-2 h-4 w-4 text-gray-500" />
+ )}
+ <span>{option.label}</span>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ <CommandSeparator />
+ <CommandGroup>
+ <div className="flex items-center justify-between gap-1">
+ {selectedLanguages.length > 0 && (
+ <>
+ <CommandItem
+ onSelect={handleClear}
+ className="max-w-full flex-1 cursor-pointer justify-center"
+ >
+ Clear
+ </CommandItem>
+ <Separator
+ orientation="vertical"
+ className="flex h-full min-h-6"
+ />
+ <CommandItem
+ onSelect={async () => {
+ setIsPopoverOpen(false);
+ if (handleDownload) await handleDownload();
+ }}
+ className="max-w-full flex-1 cursor-pointer justify-center bg-slate-900 text-slate-50 data-[selected='true']:bg-slate-900/90 data-[selected='true']:text-white dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90"
+ >
+ Download
+ </CommandItem>
+ </>
+ )}
+ {selectedLanguages.length === 0 && (
+ <CommandItem
+ onSelect={() => setIsPopoverOpen(false)}
+ className="max-w-full flex-1 cursor-pointer justify-center"
+ >
+ Close
+ </CommandItem>
+ )}
+ </div>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+);
+
+MultiSelect.displayName = "MultiSelect";
diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsx
new file mode 100644
index 0000000..eb3e6a9
--- /dev/null
+++ b/src/components/ui/popover.tsx
@@ -0,0 +1,31 @@
+"use client"
+
+import * as React from "react"
+import * as PopoverPrimitive from "@radix-ui/react-popover"
+
+import { cn } from "@/lib/utils"
+
+const Popover = PopoverPrimitive.Root
+
+const PopoverTrigger = PopoverPrimitive.Trigger
+
+const PopoverContent = React.forwardRef<
+ React.ElementRef<typeof PopoverPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
+>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 w-72 rounded-md border border-slate-200 bg-white p-4 text-slate-950 shadow-md outline-none 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-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50",
+ className
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+))
+PopoverContent.displayName = PopoverPrimitive.Content.displayName
+
+export { Popover, PopoverTrigger, PopoverContent }
diff --git a/src/components/ui/separator.tsx b/src/components/ui/separator.tsx
new file mode 100644
index 0000000..f2cd15a
--- /dev/null
+++ b/src/components/ui/separator.tsx
@@ -0,0 +1,31 @@
+"use client"
+
+import * as React from "react"
+import * as SeparatorPrimitive from "@radix-ui/react-separator"
+
+import { cn } from "@/lib/utils"
+
+const Separator = React.forwardRef<
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
+>(
+ (
+ { className, orientation = "horizontal", decorative = true, ...props },
+ ref
+ ) => (
+ <SeparatorPrimitive.Root
+ ref={ref}
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-slate-200 dark:bg-slate-800",
+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
+ className
+ )}
+ {...props}
+ />
+ )
+)
+Separator.displayName = SeparatorPrimitive.Root.displayName
+
+export { Separator }