Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.
TypeScript fintechinvoiceinvoice-generatorinvoice-pdfinvoice-templateinvoicesnextjsopen-sourcequotesreactreact-pdf-rendererself-hostedshadcn-uitailwindcsstypescript
feat: refactoring and improvements (#78)
Vlad Sazonauccefb5e30184
diff --git a/src/app/components/invoice-form.tsx b/src/app/components/invoice-form.tsxdeleted file mode 100644index 0157519..0000000--- a/src/app/components/invoice-form.tsx+++ /dev/null@@ -1,2167 +0,0 @@-import {- ACCORDION_STATE_LOCAL_STORAGE_KEY,- accordionSchema,- invoiceItemSchema,- invoiceSchema,- SUPPORTED_CURRENCIES,- SUPPORTED_DATE_FORMATS,- SUPPORTED_LANGUAGES,- type InvoiceData,- 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 { 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";-import {- CURRENCY_SYMBOLS,- MoneyInput,- ReadOnlyMoneyInput,-} from "@/components/ui/money-input";-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 { umamiTrackEvent } from "@/lib/umami-analytics-track-event";-import { getAmountInWords, getNumberFractionalPart } from "@/lib/utils";-import { zodResolver } from "@hookform/resolvers/zod";-import { useOpenPanel } from "@openpanel/nextjs";-import dayjs from "dayjs";-import { AlertTriangle, Plus, Trash2 } from "lucide-react";-import React, { useCallback, useEffect, useState } from "react";-import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";-import { toast } from "sonner";-import { useDebouncedCallback } from "use-debounce";-import { z } from "zod";-import * as Sentry from "@sentry/nextjs";-import type { FormPrefixId } from ".";--export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";-export const INVOICE_PDF_HTML_FORM_ID = "pdfInvoiceForm";-export const DEBOUNCE_TIMEOUT = 500;-export const LOADING_BUTTON_TIMEOUT = 400;-export const LOADING_BUTTON_TEXT = "Generating Document...";--const DEFAULT_ACCORDION_VALUES = [- "general",- "seller",- "buyer",- "invoiceItems",-] as const;--const ACCORDION_GENERAL = DEFAULT_ACCORDION_VALUES[0];-const ACCORDION_SELLER = DEFAULT_ACCORDION_VALUES[1];-const ACCORDION_BUYER = DEFAULT_ACCORDION_VALUES[2];-const ACCORDION_ITEMS = DEFAULT_ACCORDION_VALUES[3];--type NonReadonly<T> = {- -readonly [P in keyof T]: T[P] extends object ? NonReadonly<T[P]> : T[P];-};--const checkIfDateOnInvoiceIsInCurrentMonth = (date: string) => {- const today = dayjs();-- if (!date) return false;-- const d2 = dayjs(date);-- if (!d2.isValid()) return false;-- const isSameMonth = today.isSame(d2, "month");-- return isSameMonth;-};--const calculateItemTotals = (item: InvoiceItemData | null) => {- if (!item) return null;-- const amount = Number(item.amount) || 0;- const netPrice = Number(item.netPrice) || 0;- const calculatedNetAmount = amount * netPrice;- const formattedNetAmount = Number(calculatedNetAmount.toFixed(2));-- let vatAmount = 0;- if (item.vat && item.vat !== "NP" && item.vat !== "OO") {- vatAmount = (formattedNetAmount * Number(item.vat)) / 100;- }-- const formattedVatAmount = Number(vatAmount.toFixed(2));- const formattedPreTaxAmount = Number(- (formattedNetAmount + formattedVatAmount).toFixed(2)- );-- return {- ...item,- netAmount: formattedNetAmount,- vatAmount: formattedVatAmount,- preTaxAmount: formattedPreTaxAmount,- };-};--const ErrorMessage = ({ children }: { children: React.ReactNode }) => {- return <p className="mt-1 text-xs text-red-600">{children}</p>;-};--const Legend = ({ children }: { children: React.ReactNode }) => {- return (- <legend className="text-lg font-semibold text-gray-900">{children}</legend>- );-};--const AlertIcon = () => {- return <AlertTriangle className="mr-1 inline-block h-3 w-3 text-amber-500" />;-};--type AccordionKeys = Array<(typeof DEFAULT_ACCORDION_VALUES)[number]>;--type Prettify<T> = {- [K in keyof T]: T[K];-} & {};--interface InvoiceFormProps {- invoiceData: InvoiceData;- onInvoiceDataChange: (updatedData: InvoiceData) => void;- /**- * we need this to generate unique ids for the form fields for mobile and desktop views- * otherwise the ids will be the same and the form will not work correctly + accessibility issues- */- formPrefixId: FormPrefixId;-}--export function InvoiceForm({- invoiceData,- onInvoiceDataChange,- formPrefixId,-}: InvoiceFormProps) {- const openPanel = useOpenPanel();-- const form = useForm<InvoiceData>({- resolver: zodResolver(invoiceSchema),- defaultValues: invoiceData,- mode: "onChange",- });-- const {- control,- handleSubmit,- setValue,- formState: { errors },- watch,- } = form;-- const currency = useWatch({ control, name: "currency" });- const invoiceItems = useWatch({ control, name: "items" });-- const invoiceNumber = useWatch({ control, name: "invoiceNumber" });- 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);-- const isDateOfServiceInCurrentMonth =- checkIfDateOnInvoiceIsInCurrentMonth(dateOfService);-- const isPaymentDueBeforeDateOfIssue = dayjs(paymentDue).isBefore(- dayjs(dateOfIssue)- );-- // payment due date is 14 days after the date of issue or the same day- const isPaymentDue14DaysFromDateOfIssue =- dayjs(paymentDue).isAfter(dayjs(dateOfIssue).add(14, "days")) ||- dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"));-- const extractInvoiceMonthAndYear = invoiceNumber?.split("/")?.[1];-- const isInvoiceNumberInCurrentMonth =- extractInvoiceMonthAndYear === dayjs().format("MM-YYYY");-- const { fields, append, remove } = useFieldArray({- control,- name: "items",- });-- // calculate totals and other values when invoice items change- useEffect(() => {- // run validations before calculations because user can input invalid data- const validatedItems = z.array(invoiceItemSchema).safeParse(invoiceItems);-- if (!validatedItems.success) {- console.error("Invalid items:", validatedItems.error);- return;- }-- // Always calculate total, even when no items- const total = invoiceItems?.length- ? Number(- invoiceItems- .reduce((sum, item) => sum + (item?.preTaxAmount || 0), 0)- .toFixed(2)- )- : 0;-- // Update total first- setValue("total", total, { shouldValidate: true });-- // Skip rest of calculations if no items- if (!invoiceItems?.length) return;-- // Check if any relevant values have changed- const hasChanges = invoiceItems.some((item) => {- const calculated = calculateItemTotals(item);- return (- calculated?.netAmount !== item.netAmount ||- calculated?.vatAmount !== item.vatAmount ||- calculated?.preTaxAmount !== item.preTaxAmount- );- });- if (!hasChanges) return;-- // Only update if there are actual changes- const updatedItems = invoiceItems- .map(calculateItemTotals)- .filter(Boolean) as InvoiceItemData[];-- // Batch updates- updatedItems.forEach((item, index) => {- setValue(`items.${index}`, item, {- shouldValidate: false, // Prevent validation during intermediate updates- });- });- }, [invoiceItems, setValue]);-- // regenerate pdf on every input change with debounce- const debouncedRegeneratePdfOnFormChange = useDebouncedCallback(- (data) => {- // submit form e.g. regenerates pdf and run form validations- handleSubmit(onSubmit)(data);-- // validate with zod and save to local storage- const result = invoiceSchema.safeParse(data);-- if (!result.success) {- console.error("Invalid data:", result.error);- } else {- // success validation- const stringifiedData = JSON.stringify(result.data);-- try {- localStorage.setItem(PDF_DATA_LOCAL_STORAGE_KEY, stringifiedData);- } catch (error) {- console.error("Error saving to local storage:", error);-- Sentry.captureException(error);- }- }- },- // debounce delay in ms- DEBOUNCE_TIMEOUT- );-- // subscribe to form changes to regenerate pdf on every input change- useEffect(() => {- const subscription = watch((value) => {- debouncedRegeneratePdfOnFormChange(value);- });-- return () => subscription.unsubscribe();- }, [debouncedRegeneratePdfOnFormChange, watch]);-- // Add a wrapper function for remove item that triggers the form update- const handleRemoveItem = useCallback(- (index: number) => {- remove(index);-- // analytics track event- openPanel.track("remove_invoice_item");- umamiTrackEvent("remove_invoice_item");-- // Manually trigger form submission after removal- const currentFormData = watch();- debouncedRegeneratePdfOnFormChange(currentFormData);- },- [remove, openPanel, watch, debouncedRegeneratePdfOnFormChange]- );-- // TODO: refactor this and debouncedRegeneratePdfOnFormChange(), so data is saved to local storage, basically copy everything from debouncedRegeneratePdfOnFormChange() and use this onSubmit function in two places- const onSubmit = (data: InvoiceData) => {- onInvoiceDataChange(data);- };-- /**- * All open accordion sections will be in the array of strings- * ['general', 'seller', 'invoiceItems'] -> means that general, seller and invoiceItems accordion sections are open- * [] -> means that all accordion sections are closed- */- const [accordionValues, setAccordionValues] = useState<- Prettify<AccordionKeys>- >(() => {- // Try to load from localStorage- try {- const savedState = localStorage.getItem(- ACCORDION_STATE_LOCAL_STORAGE_KEY- );-- if (savedState) {- const parsedState = JSON.parse(savedState);-- const validatedState = accordionSchema.safeParse(parsedState);-- if (validatedState.success) {- const arrayOfOpenSections = Object.entries(validatedState.data)- // eslint-disable-next-line @typescript-eslint/no-unused-vars- .filter(([_, isOpen]) => isOpen)- .map(([section]) => section) as Prettify<AccordionKeys>;-- return arrayOfOpenSections;- }- }- } catch (error) {- console.error("Error loading accordion state:", error);-- Sentry.captureException(error);- }-- // Default to all sections open if no valid state found- return DEFAULT_ACCORDION_VALUES as NonReadonly<- typeof DEFAULT_ACCORDION_VALUES- >;- });-- // Save accordion state changes to localStorage- const handleAccordionValueChange = (value: Prettify<AccordionKeys>) => {- setAccordionValues(value);-- try {- // parse the value to the accordion schema- const stateToSave = accordionSchema.parse({- general: value.includes(ACCORDION_GENERAL),- seller: value.includes(ACCORDION_SELLER),- buyer: value.includes(ACCORDION_BUYER),- invoiceItems: value.includes(ACCORDION_ITEMS),- });-- localStorage.setItem(- ACCORDION_STATE_LOCAL_STORAGE_KEY,- JSON.stringify(stateToSave)- );- } catch (error) {- console.error("Error saving accordion state:", error);-- Sentry.captureException(error);- }- };-- return (- <>- <form- id={formPrefixId}- className="mb-4 space-y-3.5"- 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,- }- );- })}- >- <Accordion- type="multiple"- value={accordionValues}- onValueChange={handleAccordionValueChange}- className="space-y-4"- >- {/* General Information */}- <AccordionItem- value={ACCORDION_GENERAL}- className="rounded-lg border shadow"- >- <AccordionTrigger className="px-4 py-3">- <Legend>General Information</Legend>- </AccordionTrigger>- <AccordionContent className="px-4 pb-4">- <div className="space-y-4">- {/* Language PDF Select */}- <div>- <Label htmlFor={`${formPrefixId}-language`} className="mb-1">- Invoice PDF Language- </Label>- <Controller- name="language"- control={control}- render={({ field }) => (- <SelectNative- {...field}- id={`${formPrefixId}-language`}- className="block"- >- {SUPPORTED_LANGUAGES.map((lang) => (- <option key={lang} value={lang}>- {lang === "en" ? "English" : "Polish"}- </option>- ))}- </SelectNative>- )}- />- {errors.language ? (- <ErrorMessage>{errors.language.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the language of the invoice- </InputHelperMessage>- )}- </div>-- {/* Currency Select */}- <div>- <Label htmlFor={`${formPrefixId}-currency`} className="mb-1">- Currency- </Label>- <Controller- name="currency"- control={control}- render={({ field }) => {- return (- <SelectNative- {...field}- id={`${formPrefixId}-currency`}- className="block"- >- {SUPPORTED_CURRENCIES.map((currency) => {- const currencySymbol =- CURRENCY_SYMBOLS[currency] || null;-- return (- <option- key={currency}- value={currency}- defaultValue={SUPPORTED_CURRENCIES[0]}- >- {currency} {currencySymbol}- </option>- );- })}- </SelectNative>- );- }}- />-- {errors.currency ? (- <ErrorMessage>{errors.currency.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the currency of the invoice- </InputHelperMessage>- )}- </div>-- {/* Date Format */}- <div>- <Label- htmlFor={`${formPrefixId}-dateFormat`}- className="mb-1"- >- Date Format- </Label>- <Controller- name="dateFormat"- control={control}- render={({ field }) => (- <SelectNative- {...field}- id={`${formPrefixId}-dateFormat`}- className="block"- >- {SUPPORTED_DATE_FORMATS.map((format) => {- const preview = dayjs().format(format);- const isDefault =- format === SUPPORTED_DATE_FORMATS[0];-- return (- <option key={format} value={format}>- {format} (Preview: {preview}){" "}- {isDefault ? "(default)" : ""}- </option>- );- })}- </SelectNative>- )}- />-- {errors.dateFormat ? (- <ErrorMessage>{errors.dateFormat.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Select the date format of the invoice- </InputHelperMessage>- )}- </div>-- {/* Invoice Number */}- <div>- <Label- htmlFor={`${formPrefixId}-invoiceNumber`}- className="mb-1"- >- Invoice Number- </Label>- <Controller- name="invoiceNumber"- control={control}- render={({ field }) => (- <Input- {...field}- type="text"- id={`${formPrefixId}-invoiceNumber`}- className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm"- />- )}- />- {errors.invoiceNumber && (- <ErrorMessage>{errors.invoiceNumber.message}</ErrorMessage>- )}- {!isInvoiceNumberInCurrentMonth && !errors.invoiceNumber ? (- <InputHelperMessage>- <span className="flex items-center text-balance">- <AlertIcon />- Invoice number does not match current month- </span>-- <ButtonHelper- onClick={() => {- const currentMonth = dayjs().format("MM-YYYY");- setValue("invoiceNumber", `1/${currentMonth}`);- }}- >- Click to set the invoice number to the current month (- {dayjs().format("MM-YYYY")})- </ButtonHelper>- </InputHelperMessage>- ) : null}- </div>-- {/* Date of Issue */}- <div>- <Label- htmlFor={`${formPrefixId}-dateOfIssue`}- className="mb-1"- >- Date of Issue- </Label>- <Controller- name="dateOfIssue"- control={control}- render={({ field }) => (- <Input- {...field}- type="date"- id={`${formPrefixId}-dateOfIssue`}- className=""- />- )}- />- {errors.dateOfIssue && (- <ErrorMessage>{errors.dateOfIssue.message}</ErrorMessage>- )}- {!isDateOfIssueInCurrentMonth && !errors.dateOfIssue ? (- <InputHelperMessage>- <span className="flex items-center">- <AlertIcon />- Date of issue does not match current month- </span>-- <ButtonHelper- onClick={() => {- const currentMonth = dayjs().format("YYYY-MM-DD");-- setValue("dateOfIssue", currentMonth);- }}- >- Click to set the date to today (- {dayjs().format("DD/MM/YYYY")})- </ButtonHelper>- </InputHelperMessage>- ) : null}- </div>-- {/* Date of Service */}- <div>- <Label- htmlFor={`${formPrefixId}-dateOfService`}- className="mb-1"- >- Date of Service- </Label>- <Controller- name="dateOfService"- control={control}- render={({ field }) => (- <Input- {...field}- type="date"- id={`${formPrefixId}-dateOfService`}- className=""- />- )}- />- {errors.dateOfService && (- <ErrorMessage>{errors.dateOfService.message}</ErrorMessage>- )}-- {!isDateOfServiceInCurrentMonth && !errors.dateOfService ? (- <InputHelperMessage>- <span className="flex items-center">- <AlertIcon />- Date of service does not match current month- </span>-- <ButtonHelper- onClick={() => {- const lastDayOfCurrentMonth = dayjs()- .endOf("month")- .format("YYYY-MM-DD");-- setValue("dateOfService", lastDayOfCurrentMonth);- }}- >- Click to set the date to the last day of the current- month ({dayjs().endOf("month").format("DD/MM/YYYY")})- </ButtonHelper>- </InputHelperMessage>- ) : null}- </div>-- {/* Invoice Type */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-invoiceType`} className="">- Invoice Type- </Label>-- {/* Show/hide Invoice Type field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`invoiceTypeFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-invoiceTypeFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-invoiceTypeFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "Invoice Type" Field in the PDF'- />- </div>- </div>-- <Controller- name="invoiceType"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-invoiceType`}- rows={2}- className=""- placeholder="Enter invoice type"- />- )}- />- {errors.invoiceType && (- <ErrorMessage>{errors.invoiceType.message}</ErrorMessage>- )}- </div>- </div>- </AccordionContent>- </AccordionItem>-- {/* Seller Information */}- <AccordionItem- value={ACCORDION_SELLER}- className="rounded-lg border shadow"- >- <AccordionTrigger className="px-4 py-3">- <Legend>Seller Information</Legend>- </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}- />- </div>- <div className="mt-5 space-y-4">- <div>- <Label- htmlFor={`${formPrefixId}-sellerName`}- className="mb-1"- >- Name- </Label>- <Controller- name="seller.name"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-sellerName`}- rows={3}- className=""- />- )}- />- {errors.seller?.name && (- <ErrorMessage>{errors.seller.name.message}</ErrorMessage>- )}- </div>-- <div>- <Label- htmlFor={`${formPrefixId}-sellerAddress`}- className="mb-1"- >- Address- </Label>- <Controller- name="seller.address"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-sellerAddress`}- rows={3}- className=""- />- )}- />- {errors.seller?.address && (- <ErrorMessage>{errors.seller.address.message}</ErrorMessage>- )}- </div>-- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-sellerVatNo`} className="">- VAT Number- </Label>-- {/* Show/hide Seller VAT Number field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`seller.vatNoFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-sellerVatNoFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-sellerVatNoFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "Seller VAT Number" Field in the PDF'- />- </div>- </div>- <Controller- name="seller.vatNo"- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-sellerVatNo`}- type="text"- className=""- />- )}- />- {errors.seller?.vatNo && (- <ErrorMessage>{errors.seller.vatNo.message}</ErrorMessage>- )}- </div>-- <div>- <Label- htmlFor={`${formPrefixId}-sellerEmail`}- className="mb-1"- >- </Label>- <Controller- name="seller.email"- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-sellerEmail`}- type="email"- className=""- />- )}- />- {errors.seller?.email && (- <ErrorMessage>{errors.seller.email.message}</ErrorMessage>- )}- </div>-- {/* Account Number */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-sellerAccountNumber`}- className=""- >- Account Number- </Label>-- {/* Show/hide Account Number field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`seller.accountNumberFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-sellerAccountNumberFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-sellerAccountNumberFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "Account Number" Field in the PDF'- />- </div>- </div>- <Controller- name="seller.accountNumber"- control={control}- render={({ field }) => (- <Textarea- {...field}- id="sellerAccountNumber"- rows={3}- className=""- />- )}- />- {errors.seller?.accountNumber && (- <ErrorMessage>- {errors.seller.accountNumber.message}- </ErrorMessage>- )}- </div>-- {/* SWIFT/BIC */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-sellerSwiftBic`}- className=""- >- SWIFT/BIC- </Label>-- {/* Show/hide SWIFT/BIC field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`seller.swiftBicFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-sellerSwiftBicFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-sellerSwiftBicFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "SWIFT/BIC" Field in the PDF'- />- </div>- </div>-- <Controller- name="seller.swiftBic"- control={control}- render={({ field }) => (- <Textarea- {...field}- id="sellerSwiftBic"- rows={3}- className=""- />- )}- />- {errors.seller?.swiftBic && (- <ErrorMessage>- {errors.seller.swiftBic.message}- </ErrorMessage>- )}- </div>- </div>- </AccordionContent>- </AccordionItem>-- {/* Buyer Information */}- <AccordionItem- value={ACCORDION_BUYER}- className="rounded-lg border shadow"- >- <AccordionTrigger className="px-4 py-3">- <Legend>Buyer Information</Legend>- </AccordionTrigger>- <AccordionContent className="px-4 pb-4">- <div className="relative flex items-end justify-end gap-2">- <BuyerManagement- setValue={setValue}- invoiceData={invoiceData}- />- </div>- <div className="space-y-4">- <div>- <Label htmlFor={`${formPrefixId}-buyerName`} className="mb-1">- Name- </Label>- <Controller- name="buyer.name"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-buyerName`}- rows={3}- className=""- />- )}- />- {errors.buyer?.name && (- <ErrorMessage>{errors.buyer.name.message}</ErrorMessage>- )}- </div>-- <div>- <Label- htmlFor={`${formPrefixId}-buyerAddress`}- className="mb-1"- >- Address- </Label>- <Controller- name="buyer.address"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-buyerAddress`}- rows={3}- className=""- />- )}- />- {errors.buyer?.address && (- <ErrorMessage>{errors.buyer.address.message}</ErrorMessage>- )}- </div>-- {/* Buyer VAT Number */}- <div>- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-buyerVatNo`} className="">- VAT Number- </Label>-- {/* Show/hide Buyer VAT Number field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`buyer.vatNoFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-buyerVatNoFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-buyerVatNoFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "Buyer VAT Number" Field in the PDF'- />- </div>- </div>-- <Controller- name="buyer.vatNo"- control={control}- render={({ field }) => (- <Textarea- {...field}- id="buyerVatNo"- rows={3}- className=""- />- )}- />- {errors.buyer?.vatNo && (- <ErrorMessage>{errors.buyer.vatNo.message}</ErrorMessage>- )}- </div>-- <div>- <Label- htmlFor={`${formPrefixId}-buyerEmail`}- className="mb-1"- >- </Label>- <Controller- name="buyer.email"- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-buyerEmail`}- type="email"- className=""- />- )}- />- {errors.buyer?.email && (- <ErrorMessage>{errors.buyer.email.message}</ErrorMessage>- )}- </div>- </div>- </AccordionContent>- </AccordionItem>-- {/* Invoice Items */}- <AccordionItem- value={ACCORDION_ITEMS}- className="rounded-lg border shadow"- >- <AccordionTrigger className="px-4 py-3">- <Legend>Invoice Items</Legend>- </AccordionTrigger>- <AccordionContent className="px-4 pb-4">- <div className="mb-3 space-y-4">- {/* Show Number column on PDF switch */}- <div className="relative flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemInvoiceItemNumberIsVisible0`}- >- Show "Number" Column in the Invoice Items Table- </Label>-- <Controller- name={`items.0.invoiceItemNumberIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-itemInvoiceItemNumberIsVisible0`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- </div>-- {/* Show VAT Table Summary in PDF switch */}- <div className="relative flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-vatTableSummaryIsVisible`}>- Show "VAT Table Summary" in the PDF- </Label>-- <Controller- name={`vatTableSummaryIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-vatTableSummaryIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- </div>- </div>-- {fields.map((field, index) => {- const isNotFirstItem = index > 0;- const isFirstItem = index === 0;-- return (- <fieldset- key={field.id}- className="relative mb-4 rounded-lg border p-4 shadow"- >- {/* Delete invoice item button */}- {isNotFirstItem ? (- <div className="absolute -right-3 -top-10">- <CustomTooltip- trigger={- <button- type="button"- onClick={() => handleRemoveItem(index)}- className="flex items-center justify-center rounded-full bg-red-600 p-2 transition-colors hover:bg-red-700"- >- <Trash2 className="h-4 w-4 text-white" />- </button>- }- content={`Delete Invoice Item ${index + 1}`}- />- </div>- ) : null}- <Legend>Item {index + 1}</Legend>- <div className="relative mb-8 space-y-4">- <div>- {/* Invoice Item Name */}- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemName${index}`}- className=""- >- Name- </Label>-- {/* Show/hide Name field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.nameFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemNameFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemNameFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content="Show/hide the 'Name of Goods/Service' Column in the PDF"- />- </div>- ) : null}- </div>-- {/* Name input */}- <Controller- name={`items.${index}.name`}- control={control}- render={({ field }) => (- <Textarea- {...field}- rows={4}- id={`${formPrefixId}-itemName${index}`}- className=""- />- )}- />- {errors.items?.[index]?.name && (- <ErrorMessage>- {errors.items[index]?.name?.message}- </ErrorMessage>- )}- </div>-- {/* Invoice Item Type of GTU */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemTypeOfGTU${index}`}- className=""- >- Type of GTU- </Label>-- {/* Show/hide Type of GTU field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.typeOfGTUFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemTypeOfGTUFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemTypeOfGTUFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Type of GTU" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Type of GTU input */}- <Controller- name={`items.${index}.typeOfGTU`}- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-itemTypeOfGTU${index}`}- className=""- type="text"- />- )}- />- {errors.items?.[index]?.typeOfGTU && (- <ErrorMessage>- {errors.items[index]?.typeOfGTU?.message}- </ErrorMessage>- )}- </div>-- {/* Invoice Item Amount */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemAmount${index}`}- className=""- >- Amount- </Label>-- {/* Show/hide Amount field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.amountFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemAmountFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemAmountFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Amount" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Amount input */}- <Controller- name={`items.${index}.amount`}- control={control}- render={({ field }) => {- const fieldValueNumber = Number(field.value) || 0;- const previewFormattedValue =- fieldValueNumber.toLocaleString("en-US", {- style: "decimal",- maximumFractionDigits: 3,- });-- return (- <>- <Input- {...field}- id={`${formPrefixId}-itemAmount${index}`}- type="number"- step="0.01"- min="0"- className=""- />- {!errors.items?.[index]?.amount && (- <InputHelperMessage>- Preview: {previewFormattedValue}- </InputHelperMessage>- )}- </>- );- }}- />- {errors.items?.[index]?.amount && (- <ErrorMessage>- {errors.items[index].amount.message}- </ErrorMessage>- )}- </div>-- {/* Invoice Item Unit */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemUnit${index}`}- className=""- >- Unit- </Label>-- {/* Show/hide Unit field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.unitFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemUnitFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemUnitFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Unit" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Unit input */}- <Controller- name={`items.${index}.unit`}- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-itemUnit${index}`}- type="text"- />- )}- />- {errors.items?.[index]?.unit && (- <ErrorMessage>- {errors.items[index].unit.message}- </ErrorMessage>- )}- </div>-- {/* Invoice Item Net Price */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemNetPrice${index}`}- className=""- >- Net Price- </Label>-- {/* Show/hide Net Price field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.netPriceFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemNetPriceFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemNetPriceFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Net Price" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Net price input */}- <div className="flex items-center gap-2">- <Controller- name={`items.${index}.netPrice`}- control={control}- 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={`${formPrefixId}-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 && (- <ErrorMessage>- {errors.items[index].netPrice.message}- </ErrorMessage>- )}- </div>-- {/* Invoice Item VAT */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemVat${index}`}- className=""- >- VAT- </Label>-- {/* Show/hide VAT field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.vatFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemVatFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemVatFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "VAT" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* VAT input */}- <Controller- name={`items.${index}.vat`}- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-itemVat${index}`}- type="text"- className=""- />- )}- />-- {errors.items?.[index]?.vat ? (- <ErrorMessage>- {errors.items[index].vat.message}- </ErrorMessage>- ) : (- <InputHelperMessage>- Enter NP, OO or percentage value (0-100)- </InputHelperMessage>- )}- </div>-- {/* Invoice Item Net Amount */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemNetAmount${index}`}- className=""- >- Net Amount- </Label>-- {/* Show/hide Net Amount field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.netAmountFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemNetAmountFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemNetAmountFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Net Amount" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Invoice Item Net Amount (calculated automatically) */}- <Controller- name={`items.${index}.netAmount`}- control={control}- render={({ field }) => {- return (- <ReadOnlyMoneyInput- {...field}- id={`${formPrefixId}-itemNetAmount${index}`}- currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- />- );- }}- />-- {errors.items?.[index]?.netAmount ? (- <ErrorMessage>- {errors.items[index].netAmount.message}- </ErrorMessage>- ) : (- <InputHelperMessage>- Calculated automatically based on Amount and Net- Price- </InputHelperMessage>- )}- </div>-- {/* Invoice Item VAT Amount (calculated automatically) */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemVatAmount${index}`}- className=""- >- VAT Amount- </Label>-- {/* Show/hide VAT Amount field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.vatAmountFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemVatAmountFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemVatAmountFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "VAT Amount" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* VAT amount input */}- <Controller- name={`items.${index}.vatAmount`}- control={control}- render={({ field }) => (- <ReadOnlyMoneyInput- {...field}- id={`${formPrefixId}-itemVatAmount${index}`}- currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- />- )}- />-- {errors.items?.[index]?.vatAmount ? (- <ErrorMessage>- {errors.items[index].vatAmount.message}- </ErrorMessage>- ) : (- <InputHelperMessage>- Calculated automatically based on Net Amount and VAT- </InputHelperMessage>- )}- </div>-- {/* Pre-tax Amount field */}- <div>- <div className="mb-2 flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-itemPreTaxAmount${index}`}- className=""- >- Pre-tax Amount- </Label>-- {/* Show/hide Pre-tax Amount field in PDF switch */}- {isFirstItem ? (- <div className="inline-flex items-center gap-2">- <Controller- name={`items.${index}.preTaxAmountFieldIsVisible`}- control={control}- render={({- field: { value, onChange, ...field },- }) => (- <Switch- {...field}- id={`${formPrefixId}-itemPreTaxAmountFieldIsVisible${index}`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-itemPreTaxAmountFieldIsVisible${index}`}- >- Show in PDF- </Label>- }- content='Show/hide the "Pre-tax Amount" Column in the PDF'- />- </div>- ) : null}- </div>-- {/* Pre-tax amount input */}- <Controller- name={`items.${index}.preTaxAmount`}- control={control}- render={({ field }) => (- <ReadOnlyMoneyInput- {...field}- id={`${formPrefixId}-itemPreTaxAmount${index}`}- currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- />- )}- />-- {errors.items?.[index]?.preTaxAmount ? (- <ErrorMessage>- {errors.items[index].preTaxAmount.message}- </ErrorMessage>- ) : (- <InputHelperMessage>- Calculated automatically based on Net Amount and VAT- </InputHelperMessage>- )}- </div>- </div>- </fieldset>- );- })}-- <button- type="button"- onClick={() => {- append({- invoiceItemNumberIsVisible: true,- name: "",- nameFieldIsVisible: true,- amount: 1,- amountFieldIsVisible: true,- unit: "",- unitFieldIsVisible: true,- netPrice: 0,- netPriceFieldIsVisible: true,- vat: "NP",- vatFieldIsVisible: true,- netAmount: 0,- netAmountFieldIsVisible: true,- vatAmount: 0,- vatAmountFieldIsVisible: true,- preTaxAmount: 0,- preTaxAmountFieldIsVisible: true,- typeOfGTU: "",- typeOfGTUFieldIsVisible: true,- });-- // analytics track event- openPanel.track("add_invoice_item");- umamiTrackEvent("add_invoice_item");- }}- className="mb-1 flex items-center text-sm font-medium text-gray-700 hover:text-black"- >- <Plus className="mr-2 h-4 w-4" />- Add invoice item- </button>- </AccordionContent>- </AccordionItem>- </Accordion>-- {/* Final section */}- <div className="space-y-4">- <div className="">- {/* Total field (with currency) */}- <div className="mt-5" />- <Label htmlFor={`${formPrefixId}-total`} className="mb-1">- Total- </Label>- <div className="relative mt-1 rounded-md shadow-sm">- <Controller- name="total"- control={control}- render={({ field }) => (- <ReadOnlyMoneyInput- {...field}- id={`${formPrefixId}-total`}- currency={currency}- value={field.value.toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })}- />- )}- />- </div>- {errors.total ? (- <ErrorMessage>{errors.total.message}</ErrorMessage>- ) : (- <InputHelperMessage>- Calculated automatically based on (Net Amount + VAT Amount) *- Number of invoice items- </InputHelperMessage>- )}- </div>-- {/* Payment Method */}- <div>- <div className="relative mb-2 mt-6 flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-paymentMethod`} className="">- Payment Method- </Label>-- {/* Show/hide Payment Method field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`paymentMethodFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-paymentMethodFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label- htmlFor={`${formPrefixId}-paymentMethodFieldIsVisible`}- >- Show in PDF- </Label>- }- content='Show/Hide the "Payment Method" Field in the PDF'- />- </div>- </div>-- <Controller- name="paymentMethod"- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-paymentMethod`}- type="text"- className="mt-1"- />- )}- />- {errors.paymentMethod && (- <ErrorMessage>{errors.paymentMethod.message}</ErrorMessage>- )}- </div>-- {/* Payment Due */}- <div>- <div className="mb-6">- <Label htmlFor={`${formPrefixId}-paymentDue`} className="mb-1">- Payment Due- </Label>- <Controller- name="paymentDue"- control={control}- render={({ field }) => (- <Input- {...field}- id={`${formPrefixId}-paymentDue`}- type="date"- className=""- />- )}- />- {errors.paymentDue && (- <ErrorMessage>{errors.paymentDue.message}</ErrorMessage>- )}- {!errors.paymentDue && isPaymentDueBeforeDateOfIssue ? (- <InputHelperMessage>- <span className="flex items-center text-balance">- <AlertIcon />- Payment due date is before date of issue (- {dayjs(dateOfIssue).format("DD.MM.YYYY")})- </span>- <ButtonHelper- onClick={() => {- const newPaymentDue = dayjs(dateOfIssue)- .add(14, "days")- .format("YYYY-MM-DD");-- setValue("paymentDue", newPaymentDue);- }}- >- Click to set payment due date 14 days after the date of- issue (- {dayjs(dateOfIssue).add(14, "days").format("DD/MM/YYYY")})- </ButtonHelper>- </InputHelperMessage>- ) : null}- {/* If there are no errors and the payment due date is not before the date of issue and the payment due date is not 14 days after the date of issue, show the button to set the payment due date to 14 days after the date of issue (probably a bit better UX) */}- {!errors.paymentDue &&- !isPaymentDueBeforeDateOfIssue &&- !isPaymentDue14DaysFromDateOfIssue ? (- <ButtonHelper- className="whitespace-normal"- onClick={() => {- const newPaymentDue = dayjs(dateOfIssue)- .add(14, "days")- .format("YYYY-MM-DD");-- setValue("paymentDue", newPaymentDue);- }}- >- Click to set payment due date 14 days after the date of issue- ({dayjs(dateOfIssue).add(14, "days").format("DD/MM/YYYY")})- </ButtonHelper>- ) : null}- </div>- </div>-- {/* Notes */}- <div className="">- <div className="relative mb-2 flex items-center justify-between">- <Label htmlFor={`${formPrefixId}-notes`} className="">- Notes- </Label>-- {/* Show/hide Notes field in PDF switch */}- <div className="inline-flex items-center gap-2">- <Controller- name={`notesFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-notesFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- <CustomTooltip- trigger={- <Label htmlFor={`${formPrefixId}-notesFieldIsVisible`}>- Show in PDF- </Label>- }- content='Show/Hide the "Notes" Field in the PDF'- />- </div>- </div>- <Controller- name="notes"- control={control}- render={({ field }) => (- <Textarea- {...field}- id={`${formPrefixId}-notes`}- rows={3}- className=""- />- )}- />- {errors?.notes && (- <ErrorMessage>{errors?.notes?.message}</ErrorMessage>- )}- </div>-- <div>- <div className="relative mt-5 space-y-4">- {/* Show/hide Person Authorized to Receive field in PDF switch */}- <div className="flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-personAuthorizedToReceiveFieldIsVisible`}- >- Show "Person Authorized to Receive" Signature Field- in the PDF- </Label>-- <Controller- name={`personAuthorizedToReceiveFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-personAuthorizedToReceiveFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- </div>-- {/* Show/hide Person Authorized to Issue field in PDF switch */}- <div className="flex items-center justify-between">- <Label- htmlFor={`${formPrefixId}-personAuthorizedToIssueFieldIsVisible`}- >- Show "Person Authorized to Issue" Signature Field in- the PDF- </Label>-- <Controller- name={`personAuthorizedToIssueFieldIsVisible`}- control={control}- render={({ field: { value, onChange, ...field } }) => (- <Switch- {...field}- id={`${formPrefixId}-personAuthorizedToIssueFieldIsVisible`}- checked={value}- onCheckedChange={onChange}- className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"- />- )}- />- </div>- </div>- </div>- </div>- </form>- </>- );-}diff --git a/src/app/components/invoice-form/index.tsx b/src/app/components/invoice-form/index.tsxnew file mode 100644index 0000000..72778fe--- /dev/null+++ b/src/app/components/invoice-form/index.tsx@@ -0,0 +1,729 @@+"use client";++import {+ ACCORDION_STATE_LOCAL_STORAGE_KEY,+ accordionSchema,+ invoiceItemSchema,+ invoiceSchema,+ type InvoiceData,+ type InvoiceItemData,+} from "@/app/schema";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+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";+import { ReadOnlyMoneyInput } from "@/components/ui/money-input";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { CustomTooltip } from "@/components/ui/tooltip";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";+import { zodResolver } from "@hookform/resolvers/zod";+import { useOpenPanel } from "@openpanel/nextjs";+import * as Sentry from "@sentry/nextjs";+import dayjs from "dayjs";+import { AlertTriangle } from "lucide-react";+import React, { memo, useCallback, useEffect, useState } from "react";+import { Controller, useFieldArray, useForm, useWatch } from "react-hook-form";+import { toast } from "sonner";+import { useDebouncedCallback } from "use-debounce";+import { z } from "zod";+import type { FormPrefixId } from "..";+import { BuyerInformation } from "./sections/buyer-information";+import { GeneralInformation } from "./sections/general-information";+import { InvoiceItems } from "./sections/invoice-items";+import { SellerInformation } from "./sections/seller-information";++export const PDF_DATA_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_DATA";+export const INVOICE_PDF_HTML_FORM_ID = "pdfInvoiceForm";+export const DEBOUNCE_TIMEOUT = 500;+export const LOADING_BUTTON_TIMEOUT = 400;+export const LOADING_BUTTON_TEXT = "Generating Document...";++const DEFAULT_ACCORDION_VALUES = [+ "general",+ "seller",+ "buyer",+ "invoiceItems",+] as const;++const ACCORDION_GENERAL = DEFAULT_ACCORDION_VALUES[0];+const ACCORDION_SELLER = DEFAULT_ACCORDION_VALUES[1];+const ACCORDION_BUYER = DEFAULT_ACCORDION_VALUES[2];+const ACCORDION_ITEMS = DEFAULT_ACCORDION_VALUES[3];++type NonReadonly<T> = {+ -readonly [P in keyof T]: T[P] extends object ? NonReadonly<T[P]> : T[P];+};++const calculateItemTotals = (item: InvoiceItemData | null) => {+ if (!item) return null;++ const amount = Number(item.amount) || 0;+ const netPrice = Number(item.netPrice) || 0;+ const calculatedNetAmount = amount * netPrice;+ const formattedNetAmount = Number(calculatedNetAmount.toFixed(2));++ let vatAmount = 0;+ if (item.vat && item.vat !== "NP" && item.vat !== "OO") {+ vatAmount = (formattedNetAmount * Number(item.vat)) / 100;+ }++ const formattedVatAmount = Number(vatAmount.toFixed(2));+ const formattedPreTaxAmount = Number(+ (formattedNetAmount + formattedVatAmount).toFixed(2)+ );++ return {+ ...item,+ netAmount: formattedNetAmount,+ vatAmount: formattedVatAmount,+ preTaxAmount: formattedPreTaxAmount,+ };+};++const ErrorMessage = ({ children }: { children: React.ReactNode }) => {+ return <p className="mt-1 text-xs text-red-600">{children}</p>;+};++const Legend = ({ children }: { children: React.ReactNode }) => {+ return (+ <legend className="text-lg font-semibold text-gray-900">{children}</legend>+ );+};++const AlertIcon = () => {+ return <AlertTriangle className="mr-1 inline-block h-3 w-3 text-amber-500" />;+};++type AccordionKeys = Array<(typeof DEFAULT_ACCORDION_VALUES)[number]>;++type Prettify<T> = {+ [K in keyof T]: T[K];+} & {};++interface InvoiceFormProps {+ invoiceData: InvoiceData;+ onInvoiceDataChange: (updatedData: InvoiceData) => void;+ /**+ * we need this to generate unique ids for the form fields for mobile and desktop views+ * otherwise the ids will be the same and the form will not work correctly + accessibility issues+ */+ formPrefixId: FormPrefixId;+}++export const InvoiceForm = memo(function InvoiceForm({+ invoiceData,+ onInvoiceDataChange,+ formPrefixId,+}: InvoiceFormProps) {+ const openPanel = useOpenPanel();++ const form = useForm<InvoiceData>({+ resolver: zodResolver(invoiceSchema),+ defaultValues: invoiceData,+ mode: "onChange",+ });++ const {+ control,+ handleSubmit,+ setValue,+ formState: { errors },+ watch,+ } = form;++ const currency = useWatch({ control, name: "currency" });+ const invoiceItems = useWatch({ control, name: "items" });++ const dateOfIssue = useWatch({ control, name: "dateOfIssue" });++ const paymentDue = useWatch({ control, name: "paymentDue" });+ const language = useWatch({ control, name: "language" });++ const isPaymentDueBeforeDateOfIssue = dayjs(paymentDue).isBefore(+ dayjs(dateOfIssue)+ );++ // payment due date is 14 days after the date of issue or the same day+ const isPaymentDue14DaysFromDateOfIssue =+ dayjs(paymentDue).isAfter(dayjs(dateOfIssue).add(14, "days")) ||+ dayjs(paymentDue).isSame(dayjs(dateOfIssue).add(14, "days"));++ const { fields, append, remove } = useFieldArray({+ control,+ name: "items",+ });++ // calculate totals and other values when invoice items change+ useEffect(() => {+ // run validations before calculations because user can input invalid data+ const validatedItems = z.array(invoiceItemSchema).safeParse(invoiceItems);++ if (!validatedItems.success) {+ console.error("Invalid items:", validatedItems.error);+ return;+ }++ // Always calculate total, even when no items+ const total = invoiceItems?.length+ ? Number(+ invoiceItems+ .reduce((sum, item) => sum + (item?.preTaxAmount || 0), 0)+ .toFixed(2)+ )+ : 0;++ // Update total first+ setValue("total", total, { shouldValidate: true });++ // Skip rest of calculations if no items+ if (!invoiceItems?.length) return;++ // Check if any relevant values have changed+ const hasChanges = invoiceItems.some((item) => {+ const calculated = calculateItemTotals(item);+ return (+ calculated?.netAmount !== item.netAmount ||+ calculated?.vatAmount !== item.vatAmount ||+ calculated?.preTaxAmount !== item.preTaxAmount+ );+ });+ if (!hasChanges) return;++ // Only update if there are actual changes+ const updatedItems = invoiceItems+ .map(calculateItemTotals)+ .filter(Boolean) as InvoiceItemData[];++ // Batch updates+ updatedItems.forEach((item, index) => {+ setValue(`items.${index}`, item, {+ shouldValidate: false, // Prevent validation during intermediate updates+ });+ });+ }, [invoiceItems, setValue]);++ // regenerate pdf on every input change with debounce+ const debouncedRegeneratePdfOnFormChange = useDebouncedCallback(+ (data) => {+ // submit form e.g. regenerates pdf and run form validations+ handleSubmit(onSubmit)(data);++ // data should be already validated+ const stringifiedData = JSON.stringify(data);++ try {+ localStorage.setItem(PDF_DATA_LOCAL_STORAGE_KEY, stringifiedData);+ } catch (error) {+ console.error("Error saving to local storage:", error);++ Sentry.captureException(error);+ }+ },+ // debounce delay in ms+ DEBOUNCE_TIMEOUT+ );++ // subscribe to form changes to regenerate pdf on every input change+ useEffect(() => {+ const subscription = watch((value) => {+ debouncedRegeneratePdfOnFormChange(value);+ });++ return () => subscription.unsubscribe();+ }, [debouncedRegeneratePdfOnFormChange, watch]);++ // Add a wrapper function for remove item that triggers the form update+ const handleRemoveItem = useCallback(+ (index: number) => {+ remove(index);++ // analytics track event+ openPanel.track("remove_invoice_item");+ umamiTrackEvent("remove_invoice_item");++ // Manually trigger form submission after removal+ const currentFormData = watch();+ debouncedRegeneratePdfOnFormChange(currentFormData);+ },+ [remove, openPanel, watch, debouncedRegeneratePdfOnFormChange]+ );++ // TODO: refactor this and debouncedRegeneratePdfOnFormChange(), so data is saved to local storage, basically copy everything from debouncedRegeneratePdfOnFormChange() and use this onSubmit function in two places+ const onSubmit = (data: InvoiceData) => {+ onInvoiceDataChange(data);+ };++ /**+ * All open accordion sections will be in the array of strings+ * ['general', 'seller', 'invoiceItems'] -> means that general, seller and invoiceItems accordion sections are open+ * [] -> means that all accordion sections are closed+ */+ const [accordionValues, setAccordionValues] = useState<+ Prettify<AccordionKeys>+ >(() => {+ // Try to load from localStorage+ try {+ const savedState = localStorage.getItem(+ ACCORDION_STATE_LOCAL_STORAGE_KEY+ );++ if (savedState) {+ const parsedState = JSON.parse(savedState);++ const validatedState = accordionSchema.safeParse(parsedState);++ if (validatedState.success) {+ const arrayOfOpenSections = Object.entries(validatedState.data)+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ .filter(([_, isOpen]) => isOpen)+ .map(([section]) => section) as Prettify<AccordionKeys>;++ return arrayOfOpenSections;+ }+ }+ } catch (error) {+ console.error("Error loading accordion state:", error);++ Sentry.captureException(error);+ }++ // Default to all sections open if no valid state found+ return DEFAULT_ACCORDION_VALUES as NonReadonly<+ typeof DEFAULT_ACCORDION_VALUES+ >;+ });++ // Save accordion state changes to localStorage+ const handleAccordionValueChange = (value: Prettify<AccordionKeys>) => {+ setAccordionValues(value);++ try {+ // parse the value to the accordion schema+ const stateToSave = accordionSchema.parse({+ general: value.includes(ACCORDION_GENERAL),+ seller: value.includes(ACCORDION_SELLER),+ buyer: value.includes(ACCORDION_BUYER),+ invoiceItems: value.includes(ACCORDION_ITEMS),+ });++ localStorage.setItem(+ ACCORDION_STATE_LOCAL_STORAGE_KEY,+ JSON.stringify(stateToSave)+ );+ } catch (error) {+ console.error("Error saving accordion state:", error);++ Sentry.captureException(error);+ }+ };++ return (+ <form+ id={formPrefixId}+ className="mb-4 space-y-3.5"+ 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,+ }+ );+ })}+ >+ <Accordion+ type="multiple"+ value={accordionValues}+ onValueChange={handleAccordionValueChange}+ className="space-y-4"+ >+ {/* General Information */}+ <AccordionItem+ value={ACCORDION_GENERAL}+ className="rounded-lg border shadow"+ >+ <AccordionTrigger className="px-4 py-3">+ <Legend>General Information</Legend>+ </AccordionTrigger>+ <AccordionContent className="px-4 pb-4">+ <GeneralInformation+ control={control}+ errors={errors}+ setValue={setValue}+ formPrefixId={formPrefixId}+ dateOfIssue={dateOfIssue}+ />+ </AccordionContent>+ </AccordionItem>++ {/* Seller Information */}+ <AccordionItem+ value={ACCORDION_SELLER}+ className="rounded-lg border shadow"+ >+ <AccordionTrigger className="px-4 py-3">+ <Legend>Seller Information</Legend>+ </AccordionTrigger>+ <AccordionContent className="px-4 pb-4">+ <SellerInformation+ control={control}+ errors={errors}+ setValue={setValue}+ formPrefixId={formPrefixId}+ invoiceData={invoiceData}+ />+ </AccordionContent>+ </AccordionItem>++ {/* Buyer Information */}+ <AccordionItem+ value={ACCORDION_BUYER}+ className="rounded-lg border shadow"+ >+ <AccordionTrigger className="px-4 py-3">+ <Legend>Buyer Information</Legend>+ </AccordionTrigger>+ <AccordionContent className="px-4 pb-4">+ <BuyerInformation+ control={control}+ errors={errors}+ setValue={setValue}+ formPrefixId={formPrefixId}+ invoiceData={invoiceData}+ />+ </AccordionContent>+ </AccordionItem>++ {/* Invoice Items */}+ <AccordionItem+ value={ACCORDION_ITEMS}+ className="rounded-lg border shadow"+ >+ <AccordionTrigger className="px-4 py-3">+ <Legend>Invoice Items</Legend>+ </AccordionTrigger>+ <AccordionContent className="px-4 pb-4">+ <InvoiceItems+ control={control}+ formPrefixId={formPrefixId}+ fields={fields}+ handleRemoveItem={handleRemoveItem}+ errors={errors}+ currency={currency}+ language={language}+ append={append}+ />+ </AccordionContent>+ </AccordionItem>+ </Accordion>++ {/* Final section */}+ <div className="space-y-4">+ <div className="">+ {/* Total field (with currency) */}+ <div className="mt-5" />+ <Label htmlFor={`${formPrefixId}-total`} className="mb-1">+ Total+ </Label>+ <div className="relative mt-1 rounded-md shadow-sm">+ <Controller+ name="total"+ control={control}+ render={({ field }) => (+ <ReadOnlyMoneyInput+ {...field}+ id={`${formPrefixId}-total`}+ currency={currency}+ value={field.value.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ />+ )}+ />+ </div>+ {errors.total ? (+ <ErrorMessage>{errors.total.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Calculated automatically based on (Net Amount + VAT Amount) *+ Number of invoice items+ </InputHelperMessage>+ )}+ </div>++ {/* Payment Method */}+ <div>+ <div className="relative mb-2 mt-6 flex items-center justify-between">+ <Label htmlFor={`${formPrefixId}-paymentMethod`} className="">+ Payment Method+ </Label>++ {/* Show/hide Payment Method field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`paymentMethodFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-paymentMethodFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-paymentMethodFieldIsVisible`}+ >+ Show in PDF+ </Label>+ }+ content='Show/Hide the "Payment Method" Field in the PDF'+ />+ </div>+ </div>++ <Controller+ name="paymentMethod"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-paymentMethod`}+ type="text"+ className="mt-1"+ />+ )}+ />+ {errors.paymentMethod && (+ <ErrorMessage>{errors.paymentMethod.message}</ErrorMessage>+ )}+ </div>++ {/* Payment Due */}+ <div>+ <div className="mb-6">+ <Label htmlFor={`${formPrefixId}-paymentDue`} className="mb-1">+ Payment Due+ </Label>+ <Controller+ name="paymentDue"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-paymentDue`}+ type="date"+ className=""+ />+ )}+ />+ {errors.paymentDue && (+ <ErrorMessage>{errors.paymentDue.message}</ErrorMessage>+ )}+ {!errors.paymentDue && isPaymentDueBeforeDateOfIssue ? (+ <InputHelperMessage>+ <span className="flex items-center text-balance">+ <AlertIcon />+ Payment due date is before date of issue (+ {dayjs(dateOfIssue).format("DD.MM.YYYY")})+ </span>+ <ButtonHelper+ onClick={() => {+ const newPaymentDue = dayjs(dateOfIssue)+ .add(14, "days")+ .format("YYYY-MM-DD");++ setValue("paymentDue", newPaymentDue);+ }}+ >+ Click to set payment due date 14 days after the date of issue+ ({dayjs(dateOfIssue).add(14, "days").format("DD/MM/YYYY")})+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ {/* If there are no errors and the payment due date is not before the date of issue and the payment due date is not 14 days after the date of issue, show the button to set the payment due date to 14 days after the date of issue (probably a bit better UX) */}+ {!errors.paymentDue &&+ !isPaymentDueBeforeDateOfIssue &&+ !isPaymentDue14DaysFromDateOfIssue ? (+ <ButtonHelper+ className="whitespace-normal"+ onClick={() => {+ const newPaymentDue = dayjs(dateOfIssue)+ .add(14, "days")+ .format("YYYY-MM-DD");++ setValue("paymentDue", newPaymentDue);+ }}+ >+ Click to set payment due date 14 days after the date of issue (+ {dayjs(dateOfIssue).add(14, "days").format("DD/MM/YYYY")})+ </ButtonHelper>+ ) : null}+ </div>+ </div>++ {/* Notes */}+ <div className="">+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor={`${formPrefixId}-notes`} className="">+ Notes+ </Label>++ {/* Show/hide Notes field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`notesFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-notesFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor={`${formPrefixId}-notesFieldIsVisible`}>+ Show in PDF+ </Label>+ }+ content='Show/Hide the "Notes" Field in the PDF'+ />+ </div>+ </div>+ <Controller+ name="notes"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-notes`}+ rows={3}+ className=""+ />+ )}+ />+ {errors?.notes && (+ <ErrorMessage>{errors?.notes?.message}</ErrorMessage>+ )}+ </div>++ <div>+ <div className="relative mt-5 space-y-4">+ {/* Show/hide Person Authorized to Receive field in PDF switch */}+ <div className="flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-personAuthorizedToReceiveFieldIsVisible`}+ >+ Show "Person Authorized to Receive" Signature Field in+ the PDF+ </Label>++ <Controller+ name={`personAuthorizedToReceiveFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-personAuthorizedToReceiveFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ </div>++ {/* Show/hide Person Authorized to Issue field in PDF switch */}+ <div className="flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-personAuthorizedToIssueFieldIsVisible`}+ >+ Show "Person Authorized to Issue" Signature Field in+ the PDF+ </Label>++ <Controller+ name={`personAuthorizedToIssueFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-personAuthorizedToIssueFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ </div>+ </div>+ </div>+ </div>+ </form>+ );+});diff --git a/src/app/components/invoice-form/sections/buyer-information.tsx b/src/app/components/invoice-form/sections/buyer-information.tsxnew file mode 100644index 0000000..435eb64--- /dev/null+++ b/src/app/components/invoice-form/sections/buyer-information.tsx@@ -0,0 +1,216 @@+import {+ Control,+ Controller,+ FieldErrors,+ UseFormSetValue,+} from "react-hook-form";+import { InvoiceData, type BuyerData } from "@/app/schema";+import { BuyerManagement } from "@/components/buyer-management";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { CustomTooltip } from "@/components/ui/tooltip";+import { memo, useState } from "react";+import type { FormPrefixId } from "../..";+import { LabelWithEditIcon } from "@/components/label-with-edit-icon";++const ErrorMessage = ({ children }: { children: React.ReactNode }) => {+ return <p className="mt-1 text-xs text-red-600">{children}</p>;+};++const BUYER_TOOLTIP_CONTENT =+ "Click the edit button next to the 'Select Buyer' dropdown to modify buyer details. Any changes will be automatically saved.";++interface BuyerInformationProps {+ control: Control<InvoiceData>;+ errors: FieldErrors<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+ formPrefixId: FormPrefixId;+ invoiceData: InvoiceData;+}++export const BuyerInformation = memo(function BuyerInformation({+ control,+ errors,+ setValue,+ formPrefixId,+ invoiceData,+}: BuyerInformationProps) {+ const [selectedBuyerId, setSelectedBuyerId] = useState("");+ const isBuyerSelected = !!selectedBuyerId;++ // Get current form values to pass to BuyerManagement+ const currentFormValues = {+ name: invoiceData.buyer.name,+ address: invoiceData.buyer.address,+ vatNo: invoiceData.buyer.vatNo,+ email: invoiceData.buyer.email,+ vatNoFieldIsVisible: invoiceData.buyer.vatNoFieldIsVisible,+ } satisfies Partial<BuyerData>;++ return (+ <div>+ <div className="relative flex items-end justify-end gap-2">+ <BuyerManagement+ setValue={setValue}+ invoiceData={invoiceData}+ selectedBuyerId={selectedBuyerId}+ setSelectedBuyerId={setSelectedBuyerId}+ formValues={currentFormValues}+ />+ </div>+ <fieldset className="mt-5 space-y-4" disabled={isBuyerSelected}>+ <div>+ {isBuyerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-buyerName`}+ content={BUYER_TOOLTIP_CONTENT}+ >+ Name+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-buyerName`} className="mb-1">+ Name+ </Label>+ )}+ <Controller+ name="buyer.name"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-buyerName`}+ rows={3}+ className=""+ />+ )}+ />+ {errors.buyer?.name && (+ <ErrorMessage>{errors.buyer.name.message}</ErrorMessage>+ )}+ </div>++ <div>+ {isBuyerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-buyerAddress`}+ content={BUYER_TOOLTIP_CONTENT}+ >+ Address+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-buyerAddress`} className="mb-1">+ Address+ </Label>+ )}+ <Controller+ name="buyer.address"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-buyerAddress`}+ rows={3}+ className=""+ />+ )}+ />+ {errors.buyer?.address && (+ <ErrorMessage>{errors.buyer.address.message}</ErrorMessage>+ )}+ </div>++ <div>+ <div className="relative mb-2 flex items-center justify-between">+ {isBuyerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-buyerVatNo`}+ content={BUYER_TOOLTIP_CONTENT}+ >+ VAT Number+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-buyerVatNo`} className="">+ VAT Number+ </Label>+ )}++ <div className="inline-flex items-center gap-2">+ <Controller+ name={`buyer.vatNoFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-buyerVatNoFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor={`${formPrefixId}-buyerVatNoFieldIsVisible`}>+ Show in PDF+ </Label>+ }+ content={+ isBuyerSelected+ ? null+ : 'Show/Hide the "Buyer VAT Number" Field in the PDF'+ }+ />+ </div>+ </div>+ <Controller+ name="buyer.vatNo"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-buyerVatNo`}+ type="text"+ className=""+ />+ )}+ />+ {errors.buyer?.vatNo && (+ <ErrorMessage>{errors.buyer.vatNo.message}</ErrorMessage>+ )}+ </div>++ <div>+ {isBuyerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-buyerEmail`}+ content={BUYER_TOOLTIP_CONTENT}+ >+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-buyerEmail`} className="mb-1">+ </Label>+ )}+ <Controller+ name="buyer.email"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-buyerEmail`}+ type="email"+ className=""+ />+ )}+ />+ {errors.buyer?.email && (+ <ErrorMessage>{errors.buyer.email.message}</ErrorMessage>+ )}+ </div>+ </fieldset>+ </div>+ );+});diff --git a/src/app/components/invoice-form/sections/general-information.tsx b/src/app/components/invoice-form/sections/general-information.tsxnew file mode 100644index 0000000..efba2b7--- /dev/null+++ b/src/app/components/invoice-form/sections/general-information.tsx@@ -0,0 +1,354 @@+import {+ Control,+ Controller,+ FieldErrors,+ UseFormSetValue,+ useWatch,+} from "react-hook-form";+import { InvoiceData } from "@/app/schema";+import {+ SUPPORTED_CURRENCIES,+ SUPPORTED_DATE_FORMATS,+ SUPPORTED_LANGUAGES,+} from "@/app/schema";+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";+import { CURRENCY_SYMBOLS } from "@/components/ui/money-input";+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 dayjs from "dayjs";+import { AlertTriangle } from "lucide-react";+import { memo } from "react";+import type { FormPrefixId } from "../..";++const AlertIcon = () => {+ return <AlertTriangle className="mr-1 inline-block h-3 w-3 text-amber-500" />;+};++const ErrorMessage = ({ children }: { children: React.ReactNode }) => {+ return <p className="mt-1 text-xs text-red-600">{children}</p>;+};++interface GeneralInformationProps {+ control: Control<InvoiceData>;+ errors: FieldErrors<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+ formPrefixId: FormPrefixId;+ dateOfIssue: string;+}++export const GeneralInformation = memo(function GeneralInformation({+ control,+ errors,+ setValue,+ formPrefixId,+ dateOfIssue,+}: GeneralInformationProps) {+ const invoiceNumber = useWatch({ control, name: "invoiceNumber" });+ const dateOfService = useWatch({ control, name: "dateOfService" });++ const isDateOfIssueNotToday = !dayjs(dateOfIssue).isSame(dayjs(), "day");++ const isDateOfServiceEqualsEndOfCurrentMonth = dayjs(dateOfService).isSame(+ dayjs().endOf("month"),+ "day"+ );++ const extractInvoiceMonthAndYear = invoiceNumber?.split("/")?.[1];++ const isInvoiceNumberInCurrentMonth =+ extractInvoiceMonthAndYear === dayjs().format("MM-YYYY");++ return (+ <div className="space-y-4">+ {/* Language PDF Select */}+ <div>+ <Label htmlFor={`${formPrefixId}-language`} className="mb-1">+ Invoice PDF Language+ </Label>+ <Controller+ name="language"+ control={control}+ render={({ field }) => (+ <SelectNative+ {...field}+ id={`${formPrefixId}-language`}+ className="block"+ >+ {SUPPORTED_LANGUAGES.map((lang) => (+ <option key={lang} value={lang}>+ {lang === "en" ? "English" : "Polish"}+ </option>+ ))}+ </SelectNative>+ )}+ />+ {errors.language ? (+ <ErrorMessage>{errors.language.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Select the language of the invoice+ </InputHelperMessage>+ )}+ </div>++ {/* Currency Select */}+ <div>+ <Label htmlFor={`${formPrefixId}-currency`} className="mb-1">+ Currency+ </Label>+ <Controller+ name="currency"+ control={control}+ render={({ field }) => {+ return (+ <SelectNative+ {...field}+ id={`${formPrefixId}-currency`}+ className="block"+ >+ {SUPPORTED_CURRENCIES.map((currency) => {+ const currencySymbol = CURRENCY_SYMBOLS[currency] || null;++ return (+ <option+ key={currency}+ value={currency}+ defaultValue={SUPPORTED_CURRENCIES[0]}+ >+ {currency} {currencySymbol}+ </option>+ );+ })}+ </SelectNative>+ );+ }}+ />++ {errors.currency ? (+ <ErrorMessage>{errors.currency.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Select the currency of the invoice+ </InputHelperMessage>+ )}+ </div>++ {/* Date Format */}+ <div>+ <Label htmlFor={`${formPrefixId}-dateFormat`} className="mb-1">+ Date Format+ </Label>+ <Controller+ name="dateFormat"+ control={control}+ render={({ field }) => (+ <SelectNative+ {...field}+ id={`${formPrefixId}-dateFormat`}+ className="block"+ >+ {SUPPORTED_DATE_FORMATS.map((format) => {+ const preview = dayjs().format(format);+ const isDefault = format === SUPPORTED_DATE_FORMATS[0];++ return (+ <option key={format} value={format}>+ {format} (Preview: {preview}) {isDefault ? "(default)" : ""}+ </option>+ );+ })}+ </SelectNative>+ )}+ />++ {errors.dateFormat ? (+ <ErrorMessage>{errors.dateFormat.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Select the date format of the invoice+ </InputHelperMessage>+ )}+ </div>++ {/* Invoice Number */}+ <div>+ <Label htmlFor={`${formPrefixId}-invoiceNumber`} className="mb-1">+ Invoice Number+ </Label>+ <Controller+ name="invoiceNumber"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ type="text"+ id={`${formPrefixId}-invoiceNumber`}+ className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm"+ />+ )}+ />+ {errors.invoiceNumber && (+ <ErrorMessage>{errors.invoiceNumber.message}</ErrorMessage>+ )}+ {!isInvoiceNumberInCurrentMonth && !errors.invoiceNumber ? (+ <InputHelperMessage>+ <span className="flex items-center text-balance">+ <AlertIcon />+ Invoice number does not match current month+ </span>++ <ButtonHelper+ onClick={() => {+ const currentMonth = dayjs().format("MM-YYYY");+ setValue("invoiceNumber", `1/${currentMonth}`);+ }}+ >+ Click to set the invoice number to the current month (+ {dayjs().format("MM-YYYY")})+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>++ {/* Date of Issue */}+ <div>+ <Label htmlFor={`${formPrefixId}-dateOfIssue`} className="mb-1">+ Date of Issue+ </Label>+ <Controller+ name="dateOfIssue"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ type="date"+ id={`${formPrefixId}-dateOfIssue`}+ className=""+ />+ )}+ />+ {errors.dateOfIssue && (+ <ErrorMessage>{errors.dateOfIssue.message}</ErrorMessage>+ )}+ {isDateOfIssueNotToday && !errors.dateOfIssue ? (+ <InputHelperMessage>+ <span className="flex items-center">+ <AlertIcon />+ Date of issue is not today+ </span>++ <ButtonHelper+ onClick={() => {+ const currentMonth = dayjs().format("YYYY-MM-DD");++ setValue("dateOfIssue", currentMonth);+ }}+ >+ Click to set the date to today ({dayjs().format("DD/MM/YYYY")})+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>++ {/* Date of Service */}+ <div>+ <Label htmlFor={`${formPrefixId}-dateOfService`} className="mb-1">+ Date of Service+ </Label>+ <Controller+ name="dateOfService"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ type="date"+ id={`${formPrefixId}-dateOfService`}+ className=""+ />+ )}+ />+ {errors.dateOfService && (+ <ErrorMessage>{errors.dateOfService.message}</ErrorMessage>+ )}++ {!isDateOfServiceEqualsEndOfCurrentMonth && !errors.dateOfService ? (+ <InputHelperMessage>+ <span className="flex items-center">+ <AlertIcon />+ Date of service is not the last day of the current month+ </span>++ <ButtonHelper+ onClick={() => {+ const lastDayOfCurrentMonth = dayjs()+ .endOf("month")+ .format("YYYY-MM-DD");++ setValue("dateOfService", lastDayOfCurrentMonth);+ }}+ >+ Click to set the date to the last day of the current month (+ {dayjs().endOf("month").format("DD/MM/YYYY")})+ </ButtonHelper>+ </InputHelperMessage>+ ) : null}+ </div>++ {/* Invoice Type */}+ <div>+ <div className="relative mb-2 flex items-center justify-between">+ <Label htmlFor={`${formPrefixId}-invoiceType`} className="">+ Invoice Type+ </Label>++ {/* Show/hide Invoice Type field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`invoiceTypeFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-invoiceTypeFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor={`${formPrefixId}-invoiceTypeFieldIsVisible`}>+ Show in PDF+ </Label>+ }+ content='Show/Hide the "Invoice Type" Field in the PDF'+ />+ </div>+ </div>++ <Controller+ name="invoiceType"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-invoiceType`}+ rows={2}+ className=""+ placeholder="Enter invoice type"+ />+ )}+ />+ {errors.invoiceType && (+ <ErrorMessage>{errors.invoiceType.message}</ErrorMessage>+ )}+ </div>+ </div>+ );+});diff --git a/src/app/components/invoice-form/sections/invoice-items.tsx b/src/app/components/invoice-form/sections/invoice-items.tsxnew file mode 100644index 0000000..aedb956--- /dev/null+++ b/src/app/components/invoice-form/sections/invoice-items.tsx@@ -0,0 +1,792 @@+import {+ InvoiceData,+ type SupportedCurrencies,+ type SupportedLanguages,+} from "@/app/schema";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { memo } from "react";+import {+ Control,+ Controller,+ type FieldArrayWithId,+ type FieldErrors,+ type UseFieldArrayAppend,+} from "react-hook-form";+import type { FormPrefixId } from "../..";++import { Input } from "@/components/ui/input";+import { InputHelperMessage } from "@/components/ui/input-helper-message";+import { MoneyInput, ReadOnlyMoneyInput } from "@/components/ui/money-input";+import { Textarea } from "@/components/ui/textarea";+import { CustomTooltip } from "@/components/ui/tooltip";+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";+import { getAmountInWords, getNumberFractionalPart } from "@/lib/utils";+import { useOpenPanel } from "@openpanel/nextjs";+import { Plus, Trash2 } from "lucide-react";++const Legend = ({ children }: { children: React.ReactNode }) => {+ return (+ <legend className="text-lg font-semibold text-gray-900">{children}</legend>+ );+};++const ErrorMessage = ({ children }: { children: React.ReactNode }) => {+ return <p className="mt-1 text-xs text-red-600">{children}</p>;+};++interface InvoiceItemsSettingsProps {+ control: Control<InvoiceData>;+ formPrefixId: FormPrefixId;+ fields: FieldArrayWithId<InvoiceData, "items", "id">[];+ handleRemoveItem: (index: number) => void;+ append: UseFieldArrayAppend<InvoiceData, "items">;+ errors: FieldErrors<InvoiceData>;+ currency: SupportedCurrencies;+ language: SupportedLanguages;+}++export const InvoiceItems = memo(function InvoiceItems({+ control,+ formPrefixId,+ fields,+ handleRemoveItem,+ errors,+ currency,+ language,+ append,+}: InvoiceItemsSettingsProps) {+ const openPanel = useOpenPanel();+ return (+ <>+ <div className="mb-3 space-y-4">+ {/* Show Number column on PDF switch */}+ <div className="relative flex items-center justify-between">+ <Label htmlFor={`${formPrefixId}-itemInvoiceItemNumberIsVisible0`}>+ Show "Number" Column in the Invoice Items Table+ </Label>++ <Controller+ name={`items.0.invoiceItemNumberIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemInvoiceItemNumberIsVisible0`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ </div>++ {/* Show VAT Table Summary in PDF switch */}+ <div className="relative flex items-center justify-between">+ <Label htmlFor={`${formPrefixId}-vatTableSummaryIsVisible`}>+ Show "VAT Table Summary" in the PDF+ </Label>++ <Controller+ name={`vatTableSummaryIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-vatTableSummaryIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ </div>+ </div>+ {fields.map((field, index) => {+ const isNotFirstItem = index > 0;+ const isFirstItem = index === 0;++ return (+ <fieldset+ key={field.id}+ className="relative mb-4 rounded-lg border p-4 shadow"+ >+ {/* Delete invoice item button */}+ {isNotFirstItem ? (+ <div className="absolute -right-3 -top-10">+ <CustomTooltip+ trigger={+ <button+ type="button"+ onClick={() => handleRemoveItem(index)}+ className="flex items-center justify-center rounded-full bg-red-600 p-2 transition-colors hover:bg-red-700"+ >+ <Trash2 className="h-4 w-4 text-white" />+ </button>+ }+ content={`Delete Invoice Item ${index + 1}`}+ />+ </div>+ ) : null}+ <Legend>Item {index + 1}</Legend>+ <div className="relative mb-8 space-y-4">+ <div>+ {/* Invoice Item Name */}+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemName${index}`}+ className=""+ >+ Name+ </Label>++ {/* Show/hide Name field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.nameFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemNameFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemNameFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content="Show/hide the 'Name of Goods/Service' Column in the PDF"+ />+ </div>+ ) : null}+ </div>++ {/* Name input */}+ <Controller+ name={`items.${index}.name`}+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ rows={4}+ id={`${formPrefixId}-itemName${index}`}+ className=""+ />+ )}+ />+ {errors.items?.[index]?.name && (+ <ErrorMessage>+ {errors.items[index]?.name?.message}+ </ErrorMessage>+ )}+ </div>++ {/* Invoice Item Type of GTU */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemTypeOfGTU${index}`}+ className=""+ >+ Type of GTU+ </Label>++ {/* Show/hide Type of GTU field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.typeOfGTUFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemTypeOfGTUFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemTypeOfGTUFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Type of GTU" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Type of GTU input */}+ <Controller+ name={`items.${index}.typeOfGTU`}+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-itemTypeOfGTU${index}`}+ className=""+ type="text"+ />+ )}+ />+ {errors.items?.[index]?.typeOfGTU && (+ <ErrorMessage>+ {errors.items[index]?.typeOfGTU?.message}+ </ErrorMessage>+ )}+ </div>++ {/* Invoice Item Amount */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemAmount${index}`}+ className=""+ >+ Amount+ </Label>++ {/* Show/hide Amount field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.amountFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemAmountFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemAmountFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Amount" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Amount input */}+ <Controller+ name={`items.${index}.amount`}+ control={control}+ render={({ field }) => {+ const fieldValueNumber = Number(field.value) || 0;+ const previewFormattedValue =+ fieldValueNumber.toLocaleString("en-US", {+ style: "decimal",+ maximumFractionDigits: 3,+ });++ return (+ <>+ <Input+ {...field}+ id={`${formPrefixId}-itemAmount${index}`}+ type="number"+ step="0.01"+ min="0"+ className=""+ />+ {!errors.items?.[index]?.amount && (+ <InputHelperMessage>+ Preview: {previewFormattedValue}+ </InputHelperMessage>+ )}+ </>+ );+ }}+ />+ {errors.items?.[index]?.amount && (+ <ErrorMessage>+ {errors.items[index].amount.message}+ </ErrorMessage>+ )}+ </div>++ {/* Invoice Item Unit */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemUnit${index}`}+ className=""+ >+ Unit+ </Label>++ {/* Show/hide Unit field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.unitFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemUnitFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemUnitFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Unit" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Unit input */}+ <Controller+ name={`items.${index}.unit`}+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-itemUnit${index}`}+ type="text"+ />+ )}+ />+ {errors.items?.[index]?.unit && (+ <ErrorMessage>+ {errors.items[index].unit.message}+ </ErrorMessage>+ )}+ </div>++ {/* Invoice Item Net Price */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemNetPrice${index}`}+ className=""+ >+ Net Price+ </Label>++ {/* Show/hide Net Price field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.netPriceFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemNetPriceFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemNetPriceFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Net Price" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Net price input */}+ <div className="flex items-center gap-2">+ <Controller+ name={`items.${index}.netPrice`}+ control={control}+ 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={`${formPrefixId}-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 && (+ <ErrorMessage>+ {errors.items[index].netPrice.message}+ </ErrorMessage>+ )}+ </div>++ {/* Invoice Item VAT */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemVat${index}`}+ className=""+ >+ VAT+ </Label>++ {/* Show/hide VAT field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.vatFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemVatFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemVatFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "VAT" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* VAT input */}+ <Controller+ name={`items.${index}.vat`}+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-itemVat${index}`}+ type="text"+ className=""+ />+ )}+ />++ {errors.items?.[index]?.vat ? (+ <ErrorMessage>{errors.items[index].vat.message}</ErrorMessage>+ ) : (+ <InputHelperMessage>+ Enter NP, OO or percentage value (0-100)+ </InputHelperMessage>+ )}+ </div>++ {/* Invoice Item Net Amount */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemNetAmount${index}`}+ className=""+ >+ Net Amount+ </Label>++ {/* Show/hide Net Amount field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.netAmountFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemNetAmountFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemNetAmountFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Net Amount" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Invoice Item Net Amount (calculated automatically) */}+ <Controller+ name={`items.${index}.netAmount`}+ control={control}+ render={({ field }) => {+ return (+ <ReadOnlyMoneyInput+ {...field}+ id={`${formPrefixId}-itemNetAmount${index}`}+ currency={currency}+ value={field.value.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ />+ );+ }}+ />++ {errors.items?.[index]?.netAmount ? (+ <ErrorMessage>+ {errors.items[index].netAmount.message}+ </ErrorMessage>+ ) : (+ <InputHelperMessage>+ Calculated automatically based on Amount and Net Price+ </InputHelperMessage>+ )}+ </div>++ {/* Invoice Item VAT Amount (calculated automatically) */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemVatAmount${index}`}+ className=""+ >+ VAT Amount+ </Label>++ {/* Show/hide VAT Amount field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.vatAmountFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemVatAmountFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemVatAmountFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "VAT Amount" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* VAT amount input */}+ <Controller+ name={`items.${index}.vatAmount`}+ control={control}+ render={({ field }) => (+ <ReadOnlyMoneyInput+ {...field}+ id={`${formPrefixId}-itemVatAmount${index}`}+ currency={currency}+ value={field.value.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ />+ )}+ />++ {errors.items?.[index]?.vatAmount ? (+ <ErrorMessage>+ {errors.items[index].vatAmount.message}+ </ErrorMessage>+ ) : (+ <InputHelperMessage>+ Calculated automatically based on Net Amount and VAT+ </InputHelperMessage>+ )}+ </div>++ {/* Pre-tax Amount field */}+ <div>+ <div className="mb-2 flex items-center justify-between">+ <Label+ htmlFor={`${formPrefixId}-itemPreTaxAmount${index}`}+ className=""+ >+ Pre-tax Amount+ </Label>++ {/* Show/hide Pre-tax Amount field in PDF switch */}+ {isFirstItem ? (+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`items.${index}.preTaxAmountFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-itemPreTaxAmountFieldIsVisible${index}`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-itemPreTaxAmountFieldIsVisible${index}`}+ >+ Show in PDF+ </Label>+ }+ content='Show/hide the "Pre-tax Amount" Column in the PDF'+ />+ </div>+ ) : null}+ </div>++ {/* Pre-tax amount input */}+ <Controller+ name={`items.${index}.preTaxAmount`}+ control={control}+ render={({ field }) => (+ <ReadOnlyMoneyInput+ {...field}+ id={`${formPrefixId}-itemPreTaxAmount${index}`}+ currency={currency}+ value={field.value.toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })}+ />+ )}+ />++ {errors.items?.[index]?.preTaxAmount ? (+ <ErrorMessage>+ {errors.items[index].preTaxAmount.message}+ </ErrorMessage>+ ) : (+ <InputHelperMessage>+ Calculated automatically based on Net Amount and VAT+ </InputHelperMessage>+ )}+ </div>+ </div>+ </fieldset>+ );+ })}+ <button+ type="button"+ onClick={() => {+ append({+ invoiceItemNumberIsVisible: true,+ name: "",+ nameFieldIsVisible: true,+ amount: 1,+ amountFieldIsVisible: true,+ unit: "",+ unitFieldIsVisible: true,+ netPrice: 0,+ netPriceFieldIsVisible: true,+ vat: "NP",+ vatFieldIsVisible: true,+ netAmount: 0,+ netAmountFieldIsVisible: true,+ vatAmount: 0,+ vatAmountFieldIsVisible: true,+ preTaxAmount: 0,+ preTaxAmountFieldIsVisible: true,+ typeOfGTU: "",+ typeOfGTUFieldIsVisible: true,+ });++ // analytics track event+ openPanel.track("add_invoice_item");+ umamiTrackEvent("add_invoice_item");+ }}+ className="mb-1 flex items-center text-sm font-medium text-gray-700 hover:text-black"+ >+ <Plus className="mr-2 h-4 w-4" />+ Add invoice item+ </button>+ </>+ );+});diff --git a/src/app/components/invoice-form/sections/seller-information.tsx b/src/app/components/invoice-form/sections/seller-information.tsxnew file mode 100644index 0000000..25ad63f--- /dev/null+++ b/src/app/components/invoice-form/sections/seller-information.tsx@@ -0,0 +1,349 @@+import {+ Control,+ Controller,+ FieldErrors,+ UseFormSetValue,+} from "react-hook-form";+import { InvoiceData, type SellerData } from "@/app/schema";+import { SellerManagement } from "@/components/seller-management";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { CustomTooltip } from "@/components/ui/tooltip";+import { memo, useState } from "react";+import type { FormPrefixId } from "../..";+import { LabelWithEditIcon } from "@/components/label-with-edit-icon";++const ErrorMessage = ({ children }: { children: React.ReactNode }) => {+ return <p className="mt-1 text-xs text-red-600">{children}</p>;+};++const SELLER_TOOLTIP_CONTENT =+ "Click the edit button next to the 'Select Seller' dropdown to modify seller details. Any changes will be automatically saved.";++interface SellerInformationProps {+ control: Control<InvoiceData>;+ errors: FieldErrors<InvoiceData>;+ setValue: UseFormSetValue<InvoiceData>;+ formPrefixId: FormPrefixId;+ invoiceData: InvoiceData;+}++export const SellerInformation = memo(function SellerInformation({+ control,+ errors,+ setValue,+ formPrefixId,+ invoiceData,+}: SellerInformationProps) {+ const [selectedSellerId, setSelectedSellerId] = useState("");+ const isSellerSelected = !!selectedSellerId;++ // Get current form values to pass to SellerManagement+ const currentFormValues = {+ name: invoiceData.seller.name,+ address: invoiceData.seller.address,+ vatNo: invoiceData.seller.vatNo,+ email: invoiceData.seller.email,+ accountNumber: invoiceData.seller.accountNumber,+ swiftBic: invoiceData.seller.swiftBic,+ vatNoFieldIsVisible: invoiceData.seller.vatNoFieldIsVisible,+ accountNumberFieldIsVisible: invoiceData.seller.accountNumberFieldIsVisible,+ swiftBicFieldIsVisible: invoiceData.seller.swiftBicFieldIsVisible,+ } satisfies Partial<SellerData>;++ return (+ <div>+ <div className="relative flex items-end justify-end gap-2">+ <SellerManagement+ setValue={setValue}+ invoiceData={invoiceData}+ selectedSellerId={selectedSellerId}+ setSelectedSellerId={setSelectedSellerId}+ formValues={currentFormValues}+ />+ </div>+ <fieldset className="mt-5 space-y-4" disabled={isSellerSelected}>+ <div>+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerName`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ Name+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-sellerName`} className="mb-1">+ Name+ </Label>+ )}+ <Controller+ name="seller.name"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-sellerName`}+ rows={3}+ className=""+ />+ )}+ />+ {errors.seller?.name && (+ <ErrorMessage>{errors.seller.name.message}</ErrorMessage>+ )}+ </div>++ <div>+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerAddress`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ Address+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-sellerAddress`} className="mb-1">+ Address+ </Label>+ )}+ <Controller+ name="seller.address"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id={`${formPrefixId}-sellerAddress`}+ rows={3}+ className=""+ disabled={!!selectedSellerId}+ />+ )}+ />+ {errors.seller?.address && (+ <ErrorMessage>{errors.seller.address.message}</ErrorMessage>+ )}+ </div>++ <div>+ <div className="relative mb-2 flex items-center justify-between">+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerVatNo`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ VAT Number+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-sellerVatNo`} className="">+ VAT Number+ </Label>+ )}++ {/* Show/hide Seller VAT Number field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`seller.vatNoFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-sellerVatNoFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label htmlFor={`${formPrefixId}-sellerVatNoFieldIsVisible`}>+ Show in PDF+ </Label>+ }+ content={+ isSellerSelected+ ? null+ : "Show/Hide the 'Seller VAT Number' Field in the PDF"+ }+ />+ </div>+ </div>+ <Controller+ name="seller.vatNo"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-sellerVatNo`}+ type="text"+ className=""+ />+ )}+ />+ {errors.seller?.vatNo && (+ <ErrorMessage>{errors.seller.vatNo.message}</ErrorMessage>+ )}+ </div>++ <div>+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerEmail`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-sellerEmail`} className="mb-1">+ </Label>+ )}+ <Controller+ name="seller.email"+ control={control}+ render={({ field }) => (+ <Input+ {...field}+ id={`${formPrefixId}-sellerEmail`}+ type="email"+ className=""+ />+ )}+ />+ {errors.seller?.email && (+ <ErrorMessage>{errors.seller.email.message}</ErrorMessage>+ )}+ </div>++ {/* Account Number */}+ <div>+ <div className="relative mb-2 flex items-center justify-between">+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerAccountNumber`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ Account Number+ </LabelWithEditIcon>+ ) : (+ <Label+ htmlFor={`${formPrefixId}-sellerAccountNumber`}+ className=""+ >+ Account Number+ </Label>+ )}++ {/* Show/hide Account Number field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`seller.accountNumberFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-sellerAccountNumberFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-sellerAccountNumberFieldIsVisible`}+ >+ Show in PDF+ </Label>+ }+ content={+ isSellerSelected+ ? null+ : "Show/Hide the 'Account Number' Field in the PDF"+ }+ />+ </div>+ </div>+ <Controller+ name="seller.accountNumber"+ control={control}+ render={({ field }) => (+ <Textarea+ {...field}+ id="sellerAccountNumber"+ rows={3}+ className=""+ />+ )}+ />+ {errors.seller?.accountNumber && (+ <ErrorMessage>{errors.seller.accountNumber.message}</ErrorMessage>+ )}+ </div>++ {/* SWIFT/BIC */}+ <div>+ <div className="relative mb-2 flex items-center justify-between">+ {isSellerSelected ? (+ <LabelWithEditIcon+ htmlFor={`${formPrefixId}-sellerSwiftBic`}+ content={SELLER_TOOLTIP_CONTENT}+ >+ SWIFT/BIC+ </LabelWithEditIcon>+ ) : (+ <Label htmlFor={`${formPrefixId}-sellerSwiftBic`} className="">+ SWIFT/BIC+ </Label>+ )}++ {/* Show/hide SWIFT/BIC field in PDF switch */}+ <div className="inline-flex items-center gap-2">+ <Controller+ name={`seller.swiftBicFieldIsVisible`}+ control={control}+ render={({ field: { value, onChange, ...field } }) => (+ <Switch+ {...field}+ id={`${formPrefixId}-sellerSwiftBicFieldIsVisible`}+ checked={value}+ onCheckedChange={onChange}+ className="h-5 w-8 [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-3 rtl:[&_span]:data-[state=checked]:-translate-x-3"+ />+ )}+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor={`${formPrefixId}-sellerSwiftBicFieldIsVisible`}+ >+ Show in PDF+ </Label>+ }+ content={+ isSellerSelected+ ? null+ : "Show/Hide the 'SWIFT/BIC' Field in the PDF"+ }+ />+ </div>+ </div>++ <Controller+ name="seller.swiftBic"+ control={control}+ render={({ field }) => (+ <Textarea {...field} id="sellerSwiftBic" rows={3} className="" />+ )}+ />+ {errors.seller?.swiftBic && (+ <ErrorMessage>{errors.seller.swiftBic.message}</ErrorMessage>+ )}+ </div>+ </fieldset>+ </div>+ );+});diff --git a/src/app/components/invoice-pdf-download-link.tsx b/src/app/components/invoice-pdf-download-link.tsxindex 360cc4e..a488b69 100644--- a/src/app/components/invoice-pdf-download-link.tsx+++ b/src/app/components/invoice-pdf-download-link.tsx@@ -1,8 +1,12 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useState, useMemo, useCallback } from "react";import { usePDF } from "@react-pdf/renderer";-import type { InvoiceData } from "@/app/schema";+import {+ LANGUAGE_TO_LABEL,+ type InvoiceData,+ type SupportedLanguages,+} from "@/app/schema";import { InvoicePdfTemplate } from "./invoice-pdf-template";import { cn } from "@/lib/utils";import { Loader2 } from "lucide-react";@@ -13,111 +17,137 @@ import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";import { ErrorGeneratingPdfToast } from "@/components/ui/toasts/error-generating-pdf-toast";import * as Sentry from "@sentry/nextjs";+// Move static content outside component to prevent recreation+const DONATION_TOAST_CONFIG = {+ title: "Consider Supporting Us!",+ description:+ "If you find this tool helpful, please consider making a small donation to support our work.",+ duration: Infinity,+ closeButton: true,+} as const;++const DONATION_URL = "https://dub.sh/easyinvoice-donate" as const;++// Separate button states into a memoized component+const ButtonContent = ({+ isLoading,+ language,+}: {+ isLoading: boolean;+ language: SupportedLanguages;+}) => {+ if (isLoading) {+ return (+ <span className="inline-flex items-center">+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ <span className="animate-pulse">{LOADING_BUTTON_TEXT}</span>+ </span>+ );+ }++ const languageLabel = LANGUAGE_TO_LABEL[language];++ return `Download PDF in ${languageLabel}`;+};+export function InvoicePDFDownloadLink({invoiceData,}: {invoiceData: InvoiceData;}) {- const filename = `invoice-${- invoiceData.language- }-${invoiceData.invoiceNumber.replace("/", "-")}.pdf`;-const openPanel = useOpenPanel();- const [{ loading: pdfLoading, url, error }, updatePdfInstance] = usePDF();+ // Memoize static values+ const filename = useMemo(+ () =>+ `invoice-${invoiceData.language}-${invoiceData.invoiceNumber.replace("/", "-")}.pdf`,+ [invoiceData.language, invoiceData.invoiceNumber]+ );++ const PdfDocument = useMemo(+ () => <InvoicePdfTemplate invoiceData={invoiceData} />,+ [invoiceData]+ );+ // Combine loading states+ const [{ loading: pdfLoading, url, error }, updatePdfInstance] = usePDF();const [isLoading, setIsLoading] = useState(false);- // https://github.com/diegomura/react-pdf/pull/2247/files- // allow the pdf to be updated correctly when the invoice data changes+ // Memoize tracking functions+ const trackDownload = useCallback(() => {+ openPanel.track("download_invoice");+ umamiTrackEvent("download_invoice");+ }, [openPanel]);++ const trackDonationClick = useCallback(() => {+ openPanel.track("donate_button_clicked_download_pdf_toast");+ umamiTrackEvent("donate_button_clicked_download_pdf_toast");+ }, [openPanel]);++ const showDonationToast = useCallback(() => {+ toast(DONATION_TOAST_CONFIG.title, {+ ...DONATION_TOAST_CONFIG,+ action: {+ label: "Donate",+ onClick: () => {+ window.open(DONATION_URL, "_blank", "noopener,noreferrer");+ trackDonationClick();+ },+ },+ });+ }, [trackDonationClick]);++ const handleClick = useCallback(() => {+ if (!isLoading && url) {+ trackDownload();+ toast.dismiss();+ setTimeout(showDonationToast, 3000);+ }+ }, [isLoading, url, trackDownload, showDonationToast]);++ // Handle PDF updatesuseEffect(() => {- updatePdfInstance(<InvoicePdfTemplate invoiceData={invoiceData} />);- }, [invoiceData, updatePdfInstance]);+ updatePdfInstance(PdfDocument);+ }, [PdfDocument, updatePdfInstance]);+ // Handle loading stateuseEffect(() => {- if (pdfLoading) {- setIsLoading(true);- } else {- // wait before hiding the loader to avoid flickering- const timer = setTimeout(() => {- setIsLoading(false);- }, LOADING_BUTTON_TIMEOUT);+ if (!pdfLoading) {+ const timer = setTimeout(+ () => setIsLoading(false),+ LOADING_BUTTON_TIMEOUT+ );return () => clearTimeout(timer);}+ setIsLoading(true);}, [pdfLoading]);+ // Handle errorsuseEffect(() => {if (error) {ErrorGeneratingPdfToast();-- openPanel.track("error_generating_document_link", {- data: {- error: error,- },- });- umamiTrackEvent("error_generating_document_link", {- data: {- error: error,- },- });-+ openPanel.track("error_generating_document_link", { data: { error } });+ umamiTrackEvent("error_generating_document_link", { data: { error } });Sentry.captureException(error);}}, [error, openPanel]);return (- <>- <a- href={url || "#"}- download={filename}- onClick={() => {- if (!isLoading && url) {- openPanel.track("download_invoice");- umamiTrackEvent("download_invoice");-- // dismiss any existing toast for better UX- toast.dismiss();-- // Show donation toast after 3 seconds- setTimeout(() => {- toast("Consider Supporting Us!", {- description:- "If you find this tool helpful, please consider making a small donation to support our work.",- action: {- label: "Donate",- onClick: () => {- window.open(- "https://dub.sh/easyinvoice-donate",- "_blank",- "noopener,noreferrer"- );-- openPanel.track("donate_button_clicked_download_pdf_toast");- umamiTrackEvent("donate_button_clicked_download_pdf_toast");- },- },- duration: Infinity, // Show indefinitely until the user closes it- closeButton: true,- });- }, 3000);- }- }}- className={cn(- "mb-4 h-[36px] w-full rounded-lg 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 lg:w-[210px]",- {- "pointer-events-none opacity-70": isLoading,- }- )}- >- {isLoading ? (- <span className="inline-flex items-center">- <Loader2 className="mr-2 h-4 w-4 animate-spin" />- <span className="animate-pulse">{LOADING_BUTTON_TEXT}</span>- </span>- ) : (- "Download PDF"- )}- </a>- </>+ <a+ href={url || "#"}+ download={filename}+ onClick={handleClick}+ className={cn(+ "mb-4 h-[36px] w-full rounded-lg 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 lg:w-[210px]",+ {+ "pointer-events-none opacity-70": isLoading,+ }+ )}+ >+ <ButtonContent isLoading={isLoading} language={invoiceData.language} />+ </a>);}diff --git a/src/app/components/invoice-pdf-template/index.tsx b/src/app/components/invoice-pdf-template/index.tsxindex 0d61123..0d9f604 100644--- a/src/app/components/invoice-pdf-template/index.tsx+++ b/src/app/components/invoice-pdf-template/index.tsx@@ -17,6 +17,7 @@ import { InvoicePaymentInfo } from "./invoice-payment-info";import { InvoiceVATSummaryTable } from "./invoice-vat-summary-table";import { InvoicePaymentTotals } from "./invoice-payment-totals";import { translations } from "./translations";+import { memo, useMemo } from "react";const PROD_WEBSITE_URL = "https://dub.sh/easy-invoice";@@ -177,27 +178,37 @@ export const styles = StyleSheet.create({},} as const);-// PDF Document component-export const InvoicePdfTemplate = ({+// Memoize the PDF Document component+export const InvoicePdfTemplate = memo(function InvoicePdfTemplate({invoiceData,}: {invoiceData: InvoiceData;-}) => {- const formattedInvoiceTotal = invoiceData?.total- .toLocaleString("en-US", {- minimumFractionDigits: 2,- maximumFractionDigits: 2,- })- .replaceAll(",", " ");+}) {+ const formattedInvoiceTotal = useMemo(() => {+ return invoiceData?.total+ .toLocaleString("en-US", {+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ })+ .replaceAll(",", " ");+ }, [invoiceData?.total]);const language = invoiceData.language;const t = translations[language];- const invoiceDocTitle = `${t.invoiceNumber} ${invoiceData.invoiceNumber} | Created with https://easyinvoicepdf.com`;+ const invoiceDocTitle = useMemo(() => {+ return `${t.invoiceNumber} ${invoiceData.invoiceNumber} | Created with https://easyinvoicepdf.com`;+ }, [t.invoiceNumber, invoiceData.invoiceNumber]);- const signatureSectionIsVisible =- invoiceData.personAuthorizedToReceiveFieldIsVisible ||- invoiceData.personAuthorizedToIssueFieldIsVisible;+ const signatureSectionIsVisible = useMemo(() => {+ return (+ invoiceData.personAuthorizedToReceiveFieldIsVisible ||+ invoiceData.personAuthorizedToIssueFieldIsVisible+ );+ }, [+ invoiceData.personAuthorizedToReceiveFieldIsVisible,+ invoiceData.personAuthorizedToIssueFieldIsVisible,+ ]);const vatTableSummaryIsVisible = invoiceData.vatTableSummaryIsVisible;@@ -290,4 +301,4 @@ export const InvoicePdfTemplate = ({</Page></Document>);-};+});diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 60673cc..7e24450 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -58,6 +58,15 @@ export default function RootLayout({}>) {return (<html lang="en">+ {process.env.VERCEL_ENV === "development" && (+ <head>+ {/* eslint-disable-next-line @next/next/no-sync-scripts */}+ <script+ crossOrigin="anonymous"+ src="//unpkg.com/react-scan/dist/auto.global.js"+ />+ </head>+ )}<body className={`antialiased`}><NuqsAdapter>{children}</NuqsAdapter>diff --git a/src/app/schema/index.ts b/src/app/schema/index.tsindex ab904ed..8a85145 100644--- a/src/app/schema/index.ts+++ b/src/app/schema/index.ts@@ -1,6 +1,7 @@import { z } from "zod";export const SUPPORTED_CURRENCIES = ["EUR", "USD", "GBP", "PLN"] as const;+export type SupportedCurrencies = (typeof SUPPORTED_CURRENCIES)[number];export const SUPPORTED_LANGUAGES = ["en", "pl"] as const;export type SupportedLanguages = (typeof SUPPORTED_LANGUAGES)[number];diff --git a/src/components/buyer-dialog.tsx b/src/components/buyer-dialog.tsxindex 261b99d..2251b5f 100644--- a/src/components/buyer-dialog.tsx+++ b/src/components/buyer-dialog.tsx@@ -29,7 +29,7 @@ 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 { useState, useEffect } from "react";import * as Sentry from "@sentry/nextjs";const BUYER_FORM_ID = "buyer-form";@@ -44,6 +44,7 @@ interface BuyerDialogProps {handleBuyerEdit?: (buyer: BuyerData) => void;initialData: BuyerData | null;isEditMode: boolean;+ formValues?: Partial<BuyerData>;}export function BuyerDialog({@@ -53,6 +54,7 @@ export function BuyerDialog({handleBuyerEdit,initialData,isEditMode,+ formValues,}: BuyerDialogProps) {const form = useForm<BuyerData>({resolver: zodResolver(buyerSchema),@@ -70,6 +72,33 @@ export function BuyerDialog({const [shouldApplyNewBuyerToInvoice, setShouldApplyNewBuyerToInvoice] =useState(true);+ const [shouldApplyFormValues, setShouldApplyFormValues] = useState(false);++ // Effect to update form values when switch is toggled+ useEffect(() => {+ // if the switch is on and we have form values, we want to apply the form values to the form+ if (shouldApplyFormValues && formValues && !isEditMode) {+ form.reset({+ ...form.getValues(),+ ...formValues,+ });+ }++ // if the switch is off and we have initial data, we want to apply the initial data to the form+ else if (!shouldApplyFormValues && !isEditMode) {+ form.reset(+ initialData ?? {+ id: "",+ name: "",+ address: "",+ vatNo: "",+ email: "",+ vatNoFieldIsVisible: true,+ }+ );+ }+ }, [shouldApplyFormValues, formValues, initialData, isEditMode, form]);+function onSubmit(formValues: BuyerData) {try {// **RUNNING SOME VALIDATIONS FIRST**@@ -172,6 +201,29 @@ export function BuyerDialog({</DialogHeader><div className="overflow-y-auto px-6 py-4">+ {/* Add Use Current Form Values switch */}+ {!isEditMode && (+ <div className="mb-4 flex items-center gap-2">+ <Switch+ checked={shouldApplyFormValues}+ onCheckedChange={setShouldApplyFormValues}+ id="apply-form-values-switch"+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor="apply-form-values-switch"+ className="cursor-pointer"+ >+ Use Current Form Values+ </Label>+ }+ content="Pre-fill with values from the current invoice form"+ className="z-[1000]"+ />+ </div>+ )}+<Form {...form}><formonSubmit={form.handleSubmit(onSubmit)}@@ -281,21 +333,28 @@ export function BuyerDialog({</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 New Buyer to Current Invoice- </Label>- </div>+ {/* Apply to Current Invoice switch remains at bottom */}+ {!isEditMode && (+ <div className="mt-4 flex items-center gap-2 border-t pt-4">+ <Switch+ checked={shouldApplyNewBuyerToInvoice}+ onCheckedChange={setShouldApplyNewBuyerToInvoice}+ id="apply-buyer-to-current-invoice-switch"+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor="apply-buyer-to-current-invoice-switch"+ className="cursor-pointer"+ >+ Apply to Current Invoice+ </Label>+ }+ content="When enabled, the newly created buyer will be automatically applied to your current invoice form"+ className="z-[1000]"+ /></div>- ) : null}+ )}</div><DialogFooter className="border-border border-t px-6 py-4"><DialogClose asChild>diff --git a/src/components/buyer-management.tsx b/src/components/buyer-management.tsxindex b4847b4..ef668d2 100644--- a/src/components/buyer-management.tsx+++ b/src/components/buyer-management.tsx@@ -34,20 +34,28 @@ import * as Sentry from "@sentry/nextjs";export const BUYERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_BUYERS";+interface BuyerManagementProps {+ setValue: UseFormSetValue<InvoiceData>;+ invoiceData: InvoiceData;+ selectedBuyerId: string;+ setSelectedBuyerId: (id: string) => void;+ formValues?: Partial<BuyerData>;+}+export function BuyerManagement({setValue,invoiceData,-}: {- setValue: UseFormSetValue<InvoiceData>;- invoiceData: InvoiceData;-}) {+ selectedBuyerId,+ setSelectedBuyerId,+ formValues,+}: BuyerManagementProps) {const [isBuyerDialogOpen, setIsBuyerDialogOpen] = useState(false);const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);const [buyersSelectOptions, setBuyersSelectOptions] = useState<BuyerData[]>([]);- const [selectedBuyerIndex, setSelectedBuyerIndex] = useState("");+ // const [selectedBuyerId, setSelectedBuyerId] = useState("");const [editingBuyer, setEditingBuyer] = useState<BuyerData | null>(null);const openPanel = useOpenPanel();@@ -75,13 +83,13 @@ export function BuyerManagement({});setBuyersSelectOptions(validationResult.data);- setSelectedBuyerIndex(selectedBuyer?.id ?? "");+ setSelectedBuyerId(selectedBuyer?.id ?? "");} catch (error) {console.error("Failed to load buyers:", error);Sentry.captureException(error);}- }, [invoiceData?.buyer?.id]);+ }, [invoiceData?.buyer?.id, setSelectedBuyerId]);// Update buyers when a new one is addedconst handleBuyerAdd = (@@ -106,7 +114,7 @@ export function BuyerManagement({// Apply the new buyer to the invoice if the user wants to, otherwise just add it to the list and use it later if neededif (shouldApplyNewBuyerToInvoice) {setValue("buyer", newBuyerWithId);- setSelectedBuyerIndex(newBuyerWithId?.id);+ setSelectedBuyerId(newBuyerWithId?.id);}toast.success("Buyer added successfully", {@@ -167,7 +175,7 @@ export function BuyerManagement({const id = event.target.value;if (id) {- setSelectedBuyerIndex(id);+ setSelectedBuyerId(id);const selectedBuyer = buyersSelectOptions.find((buyer) => buyer.id === id);@@ -177,7 +185,7 @@ export function BuyerManagement({}} else {// Clear the buyer from the form if the user selects the empty option- setSelectedBuyerIndex("");+ setSelectedBuyerId("");setValue("buyer", DEFAULT_BUYER_DATA);}@@ -190,7 +198,7 @@ export function BuyerManagement({try {setBuyersSelectOptions((prevBuyers) => {const updatedBuyers = prevBuyers.filter(- (buyer) => buyer.id !== selectedBuyerIndex+ (buyer) => buyer.id !== selectedBuyerId);localStorage.setItem(@@ -200,7 +208,7 @@ export function BuyerManagement({return updatedBuyers;});// Clear the selected buyer index- setSelectedBuyerIndex("");+ setSelectedBuyerId("");// Clear the buyer from the form if it was selectedsetValue("buyer", DEFAULT_BUYER_DATA);@@ -226,7 +234,7 @@ export function BuyerManagement({};const activeBuyer = buyersSelectOptions.find(- (buyer) => buyer.id === selectedBuyerIndex+ (buyer) => buyer.id === selectedBuyerId);return (@@ -244,10 +252,10 @@ export function BuyerManagement({id={buyerSelectId}className={cn("block h-8 max-w-[200px] text-[12px]",- !selectedBuyerIndex && "italic text-gray-700"+ !selectedBuyerId && "italic text-gray-700")}onChange={handleBuyerChange}- value={selectedBuyerIndex}+ value={selectedBuyerId}title={activeBuyer?.name}><option value="">No buyer selected (default)</option>@@ -258,7 +266,7 @@ export function BuyerManagement({))}</SelectNative>- {selectedBuyerIndex ? (+ {selectedBuyerId ? (<div className="flex items-center gap-2"><CustomTooltiptrigger={@@ -348,6 +356,7 @@ export function BuyerManagement({handleBuyerEdit={handleBuyerEdit}initialData={editingBuyer}isEditMode={isEditMode}+ formValues={formValues}/>{/* Delete alert buyer dialog */}diff --git a/src/components/label-with-edit-icon.tsx b/src/components/label-with-edit-icon.tsxnew file mode 100644index 0000000..7d5e7e5--- /dev/null+++ b/src/components/label-with-edit-icon.tsx@@ -0,0 +1,47 @@+import { Info } from "lucide-react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { Label } from "@/components/ui/label";+import { CustomTooltip } from "@/components/ui/tooltip";++/**+ * A component that displays a label with an edit icon and a tooltip.+ */+export const LabelWithEditIcon = ({+ htmlFor,+ children,+ content,+}: {+ htmlFor: string;+ children: React.ReactNode;+ content: string;+}) => {+ return (+ <div className="flex items-center gap-1">+ <Label htmlFor={htmlFor} className="mb-1">+ {children}+ </Label>+ <div className="hidden md:block">+ <CustomTooltip+ trigger={+ <Info className="mb-1 h-3.5 w-3.5 cursor-pointer text-gray-800" />+ }+ content={content}+ />+ </div>+ <div className="block md:hidden">+ <Popover>+ <PopoverTrigger asChild>+ <Info className="mb-1 h-3.5 w-3.5 cursor-pointer text-gray-800" />+ </PopoverTrigger>+ <PopoverContent className="w-[200px] text-sm">+ {content}+ </PopoverContent>+ </Popover>+ </div>+ </div>+ );+};diff --git a/src/components/seller-dialog.tsx b/src/components/seller-dialog.tsxindex 3571b34..967f348 100644--- a/src/components/seller-dialog.tsx+++ b/src/components/seller-dialog.tsx@@ -29,7 +29,7 @@ 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";+import { useState, useEffect } from "react";import * as Sentry from "@sentry/nextjs";const SELLER_FORM_ID = "seller-form";@@ -46,6 +46,7 @@ interface SellerDialogProps {handleSellerEdit?: (seller: SellerData) => void;initialData: SellerData | null;isEditMode: boolean;+ formValues?: Partial<SellerData>;}export function SellerDialog({@@ -55,6 +56,7 @@ export function SellerDialog({handleSellerEdit,initialData,isEditMode,+ formValues,}: SellerDialogProps) {const form = useForm<SellerData>({resolver: zodResolver(sellerSchema),@@ -77,6 +79,38 @@ export function SellerDialog({const [shouldApplyNewSellerToInvoice, setShouldApplyNewSellerToInvoice] =useState(true);+ // Add state for applying form values+ const [shouldApplyFormValues, setShouldApplyFormValues] = useState(false);++ // Effect to update form values when switch is toggled+ useEffect(() => {+ // if the switch is on and we have form values, we want to apply the form values to the form+ if (shouldApplyFormValues && formValues && !isEditMode) {+ form.reset({+ ...form.getValues(),+ ...formValues,+ });+ }++ // if the switch is off and we have initial data, we want to apply the initial data to the form+ else if (!shouldApplyFormValues && !isEditMode) {+ form.reset(+ initialData ?? {+ id: "",+ name: "",+ address: "",+ vatNo: "",+ email: "",+ accountNumber: "",+ swiftBic: "",+ vatNoFieldIsVisible: true,+ accountNumberFieldIsVisible: true,+ swiftBicFieldIsVisible: true,+ }+ );+ }+ }, [shouldApplyFormValues, formValues, initialData, isEditMode, form]);+function onSubmit(formValues: SellerData) {try {// **RUNNING SOME VALIDATIONS FIRST**@@ -181,6 +215,29 @@ export function SellerDialog({</DialogHeader><div className="overflow-y-auto px-6 py-4">+ {/* Show Use Current Form Values switch only when creating new seller */}+ {!isEditMode && (+ <div className="mb-4 flex items-center gap-2">+ <Switch+ checked={shouldApplyFormValues}+ onCheckedChange={setShouldApplyFormValues}+ id="apply-form-values-switch"+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor="apply-form-values-switch"+ className="cursor-pointer"+ >+ Pre-fill with values from the current invoice form+ </Label>+ }+ content="Use the seller details already entered in the invoice form to pre-fill this dialog"+ className="z-[1000]"+ />+ </div>+ )}+<Form {...form}><formonSubmit={form.handleSubmit(onSubmit)}@@ -386,21 +443,28 @@ export function SellerDialog({</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 New Seller to Current Invoice- </Label>- </div>+ {/* Apply to Current Invoice switch remains at the bottom */}+ {!isEditMode && (+ <div className="mt-4 flex items-center gap-2 border-t pt-4">+ <Switch+ checked={shouldApplyNewSellerToInvoice}+ onCheckedChange={setShouldApplyNewSellerToInvoice}+ id="apply-seller-to-current-invoice-switch"+ />+ <CustomTooltip+ trigger={+ <Label+ htmlFor="apply-seller-to-current-invoice-switch"+ className="cursor-pointer"+ >+ Apply to Current Invoice+ </Label>+ }+ content="When enabled, the newly created seller will be automatically applied to your current invoice form"+ className="z-[1000]"+ /></div>- ) : null}+ )}</div><DialogFooter className="border-border border-t px-6 py-4"><DialogClose asChild>diff --git a/src/components/seller-management.tsx b/src/components/seller-management.tsxindex 54b4eb0..f5edb80 100644--- a/src/components/seller-management.tsx+++ b/src/components/seller-management.tsx@@ -1,7 +1,12 @@import { Plus, Trash2, Pencil } from "lucide-react";-// import { Info } from "lucide-react";-import { useId, useState, useEffect } from "react";+import {+ useId,+ useState,+ useEffect,+ type Dispatch,+ type SetStateAction,+} from "react";import { CustomTooltip } from "./ui/tooltip";import { SelectNative } from "./ui/select-native";import { Button } from "./ui/button";@@ -34,20 +39,28 @@ import * as Sentry from "@sentry/nextjs";export const SELLERS_LOCAL_STORAGE_KEY = "EASY_INVOICE_PDF_SELLERS";+interface SellerManagementProps {+ setValue: UseFormSetValue<InvoiceData>;+ invoiceData: InvoiceData;+ selectedSellerId: string;+ setSelectedSellerId: Dispatch<SetStateAction<string>>;+ formValues?: Partial<SellerData>;+}+export function SellerManagement({setValue,invoiceData,-}: {- setValue: UseFormSetValue<InvoiceData>;- invoiceData: InvoiceData;-}) {+ selectedSellerId,+ setSelectedSellerId,+ formValues,+}: SellerManagementProps) {const [isSellerDialogOpen, setIsSellerDialogOpen] = useState(false);const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);const [sellersSelectOptions, setSellersSelectOptions] = useState<SellerData[]>([]);- const [selectedSellerIndex, setSelectedSellerIndex] = useState("");+ // const [selectedSellerIndex, setSelectedSellerIndex] = useState("");const [editingSeller, setEditingSeller] = useState<SellerData | null>(null);const openPanel = useOpenPanel();@@ -77,13 +90,13 @@ export function SellerManagement({);setSellersSelectOptions(validationResult.data);- setSelectedSellerIndex(selectedSeller?.id ?? "");+ setSelectedSellerId(selectedSeller?.id ?? "");} catch (error) {console.error("Failed to load sellers:", error);Sentry.captureException(error);}- }, [invoiceData?.seller?.id]);+ }, [invoiceData?.seller?.id, setSelectedSellerId]);// Update sellers when a new one is addedconst handleSellerAdd = (@@ -113,7 +126,7 @@ export function SellerManagement({// Apply the new seller to the invoice if the user wants to, otherwise just add it to the list and use it later if neededif (shouldApplyNewSellerToInvoice) {setValue("seller", newSellerWithId);- setSelectedSellerIndex(newSellerWithId?.id);+ setSelectedSellerId(newSellerWithId?.id);}toast.success("Seller added successfully", {@@ -174,7 +187,7 @@ export function SellerManagement({const id = event.target.value;if (id) {- setSelectedSellerIndex(id);+ setSelectedSellerId(id);const selectedSeller = sellersSelectOptions.find((seller) => seller.id === id);@@ -184,7 +197,7 @@ export function SellerManagement({}} else {// Clear the seller from the form if the user selects the empty option- setSelectedSellerIndex("");+ setSelectedSellerId("");setValue("seller", DEFAULT_SELLER_DATA);}@@ -197,7 +210,7 @@ export function SellerManagement({try {setSellersSelectOptions((prevSellers) => {const updatedSellers = prevSellers.filter(- (seller) => seller.id !== selectedSellerIndex+ (seller) => seller.id !== selectedSellerId);localStorage.setItem(@@ -207,7 +220,7 @@ export function SellerManagement({return updatedSellers;});// Clear the selected seller index- setSelectedSellerIndex("");+ setSelectedSellerId("");// Clear the seller from the form if it was selectedsetValue("seller", DEFAULT_SELLER_DATA);@@ -233,7 +246,7 @@ export function SellerManagement({};const activeSeller = sellersSelectOptions.find(- (seller) => seller.id === selectedSellerIndex+ (seller) => seller.id === selectedSellerId);return (@@ -251,10 +264,10 @@ export function SellerManagement({id={sellerSelectId}className={cn("block h-8 max-w-[200px] text-[12px]",- !selectedSellerIndex && "italic text-gray-700"+ !selectedSellerId && "italic text-gray-700")}onChange={handleSellerChange}- value={selectedSellerIndex}+ value={selectedSellerId}title={activeSeller?.name}><option value="">No seller selected (default)</option>@@ -265,7 +278,7 @@ export function SellerManagement({))}</SelectNative>- {selectedSellerIndex ? (+ {selectedSellerId ? (<div className="flex items-center gap-2"><CustomTooltiptrigger={@@ -355,6 +368,7 @@ export function SellerManagement({handleSellerEdit={handleSellerEdit}initialData={editingSeller}isEditMode={isEditMode}+ formValues={formValues}/>{/* Delete alert seller dialog */}diff --git a/src/components/ui/input-helper-message.tsx b/src/components/ui/input-helper-message.tsxindex 6176527..dde7475 100644--- a/src/components/ui/input-helper-message.tsx+++ b/src/components/ui/input-helper-message.tsx@@ -1,8 +1,10 @@-export const InputHelperMessage = ({+import { memo } from "react";++export const InputHelperMessage = memo(function InputHelperMessage({children,}: {children: React.ReactNode;-}) => {+}) {return (<pclassName="mt-1 text-balance text-xs text-zinc-700/90"@@ -12,4 +14,4 @@ export const InputHelperMessage = ({{children}</p>);-};+});diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsxindex 4302513..806ecd0 100644--- a/src/components/ui/input.tsx+++ b/src/components/ui/input.tsx@@ -1,25 +1,27 @@import { cn } from "@/lib/utils";import * as React from "react";-const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(- ({ className, type, ...props }, ref) => {- return (- <input- type={type}- autoComplete="off"- className={cn(- "h-8 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow placeholder:text-slate-500/70 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50 dark:placeholder:text-slate-400/70 dark:focus-visible:border-slate-300 dark:focus-visible:ring-slate-300/20",- type === "search" &&- "[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none",- type === "file" &&- "p-0 pr-3 italic text-slate-500/70 file:me-3 file:h-full file:border-0 file:border-r file:border-solid file:border-slate-200 file:bg-transparent file:px-3 file:text-sm file:font-medium file:not-italic file:text-slate-950 dark:text-slate-400/70 dark:file:border-slate-800 dark:file:text-slate-50",- className- )}- ref={ref}- {...props}- />- );- }+const Input = React.memo(+ React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(+ ({ className, type, ...props }, ref) => {+ return (+ <input+ type={type}+ autoComplete="off"+ className={cn(+ "h-8 w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-slate-950 shadow-sm shadow-black/5 transition-shadow placeholder:text-slate-500/70 focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-50 dark:placeholder:text-slate-400/70 dark:focus-visible:border-slate-300 dark:focus-visible:ring-slate-300/20",+ type === "search" &&+ "[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none",+ type === "file" &&+ "p-0 pr-3 italic text-slate-500/70 file:me-3 file:h-full file:border-0 file:border-r file:border-solid file:border-slate-200 file:bg-transparent file:px-3 file:text-sm file:font-medium file:not-italic file:text-slate-950 dark:text-slate-400/70 dark:file:border-slate-800 dark:file:text-slate-50",+ className+ )}+ ref={ref}+ {...props}+ />+ );+ }+ ));Input.displayName = "Input";diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsxindex 051be5a..fedbaaf 100644--- a/src/components/ui/label.tsx+++ b/src/components/ui/label.tsx@@ -4,19 +4,21 @@ import * as React from "react";import { cn } from "@/lib/utils";-const Label = React.forwardRef<- HTMLLabelElement,- React.LabelHTMLAttributes<HTMLLabelElement>->(({ className, ...props }, ref) => (- <label- ref={ref}- className={cn(- "block text-balance text-xs font-medium text-gray-900 peer-disabled:cursor-not-allowed peer-disabled:opacity-70 dark:text-slate-50",- className- )}- {...props}- />-));+const Label = React.memo(+ React.forwardRef<+ HTMLLabelElement,+ React.LabelHTMLAttributes<HTMLLabelElement>+ >(({ className, ...props }, ref) => (+ <label+ ref={ref}+ className={cn(+ "block text-balance text-xs font-medium text-gray-900 peer-disabled:cursor-not-allowed peer-disabled:opacity-70 dark:text-slate-50",+ className+ )}+ {...props}+ />+ ))+);Label.displayName = "Label";export { Label };diff --git a/src/components/ui/money-input.tsx b/src/components/ui/money-input.tsxindex efbe5f8..25063e4 100644--- a/src/components/ui/money-input.tsx+++ b/src/components/ui/money-input.tsx@@ -10,76 +10,80 @@ export const CURRENCY_SYMBOLS = {[SUPPORTED_CURRENCIES[3]]: "zł",} as const satisfies Record<InvoiceData["currency"], string>;-const MoneyInput = React.forwardRef<- HTMLInputElement,- React.ComponentProps<"input"> & { currency: InvoiceData["currency"] }->(({ currency, ...props }, ref) => {- const shownCurrencyText = currency || SUPPORTED_CURRENCIES[0];- const currencySymbol = CURRENCY_SYMBOLS[shownCurrencyText] || null;+const MoneyInput = React.memo(+ React.forwardRef<+ HTMLInputElement,+ React.ComponentProps<"input"> & { currency: InvoiceData["currency"] }+ >(({ currency, ...props }, ref) => {+ const shownCurrencyText = currency || SUPPORTED_CURRENCIES[0];+ const currencySymbol = CURRENCY_SYMBOLS[shownCurrencyText] || null;- return (- <div>- <div className="relative flex rounded-lg shadow-sm shadow-black/5">- {currencySymbol ? (- <span className="pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 text-sm">- {currencySymbol}+ return (+ <div>+ <div className="relative flex rounded-lg shadow-sm shadow-black/5">+ {currencySymbol ? (+ <span className="pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 text-sm">+ {currencySymbol}+ </span>+ ) : null}+ <Input+ {...props}+ ref={ref}+ className={cn(+ "-me-px rounded-e-none ps-6 shadow-none",+ currencySymbol ? "ps-6" : "ps-3",+ props.className+ )}+ placeholder="0.00"+ />+ <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>- ) : null}- <Input- {...props}- ref={ref}- className={cn(- "-me-px rounded-e-none ps-6 shadow-none",- currencySymbol ? "ps-6" : "ps-3",- props.className- )}- placeholder="0.00"- />- <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></div>- </div>- );-});+ );+ })+);MoneyInput.displayName = "MoneyInput";-const ReadOnlyMoneyInput = React.forwardRef<- HTMLInputElement,- React.ComponentProps<"input"> & { currency: InvoiceData["currency"] }->(({ currency, ...props }, ref) => {- const shownCurrencyText = currency || SUPPORTED_CURRENCIES[0];- const currencySymbol = CURRENCY_SYMBOLS[shownCurrencyText] || null;+const ReadOnlyMoneyInput = React.memo(+ React.forwardRef<+ HTMLInputElement,+ React.ComponentProps<"input"> & { currency: InvoiceData["currency"] }+ >(({ currency, ...props }, ref) => {+ const shownCurrencyText = currency || SUPPORTED_CURRENCIES[0];+ const currencySymbol = CURRENCY_SYMBOLS[shownCurrencyText] || null;- return (- <div>- <div className="relative flex rounded-lg shadow-sm shadow-black/5">- {currencySymbol ? (- <span className="pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 text-sm">- {currencySymbol}+ return (+ <div>+ <div className="relative flex rounded-lg shadow-sm shadow-black/5">+ {currencySymbol ? (+ <span className="pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 text-sm">+ {currencySymbol}+ </span>+ ) : null}+ <Input+ {...props}+ ref={ref}+ className={cn(+ "-me-px block w-full cursor-not-allowed rounded-md rounded-e-none border border-gray-300 bg-gray-100 px-3 py-2 ps-6",+ currencySymbol ? "ps-6" : "ps-3",+ "focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50",+ props.className+ )}+ placeholder="0.00"+ type="text"+ 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 text-slate-950 shadow-sm shadow-black/5 transition-shadow">+ {shownCurrencyText}</span>- ) : null}- <Input- {...props}- ref={ref}- className={cn(- "-me-px block w-full cursor-not-allowed rounded-md rounded-e-none border border-gray-300 bg-gray-100 px-3 py-2 ps-6",- currencySymbol ? "ps-6" : "ps-3",- "focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50",- props.className- )}- placeholder="0.00"- type="text"- 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 text-slate-950 shadow-sm shadow-black/5 transition-shadow">- {shownCurrencyText}- </span>+ </div></div>- </div>- );-});+ );+ })+);ReadOnlyMoneyInput.displayName = "ReadOnlyMoneyInput";export { MoneyInput, ReadOnlyMoneyInput };diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsxindex 5babdc7..c850c1c 100644--- a/src/components/ui/switch.tsx+++ b/src/components/ui/switch.tsx@@ -8,25 +8,27 @@ import { cn } from "@/lib/utils";/*** https://originui.com/checks-radios-switches*/-const Switch = React.forwardRef<- React.ElementRef<typeof SwitchPrimitives.Root>,- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>->(({ className, ...props }, ref) => (- <SwitchPrimitives.Root- className={cn(- "focus-visible:outline-ring/70 peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-slate-900 data-[state=unchecked]:bg-slate-200 dark:data-[state=checked]:bg-slate-50 dark:data-[state=unchecked]:bg-slate-800",- className- )}- {...props}- ref={ref}- >- <SwitchPrimitives.Thumb+const Switch = React.memo(+ React.forwardRef<+ React.ElementRef<typeof SwitchPrimitives.Root>,+ React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>+ >(({ className, ...props }, ref) => (+ <SwitchPrimitives.RootclassName={cn(- "pointer-events-none block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-300 [transition-timing-function:cubic-bezier(0.16,1,0.3,1)] data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 dark:bg-slate-950 rtl:data-[state=checked]:-translate-x-4"+ "focus-visible:outline-ring/70 peer inline-flex h-6 w-10 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent outline-offset-2 transition-colors focus-visible:outline focus-visible:outline-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-slate-900 data-[state=unchecked]:bg-slate-200 dark:data-[state=checked]:bg-slate-50 dark:data-[state=unchecked]:bg-slate-800",+ className)}- />- </SwitchPrimitives.Root>-));+ {...props}+ ref={ref}+ >+ <SwitchPrimitives.Thumb+ className={cn(+ "pointer-events-none block size-5 rounded-full bg-white shadow-sm shadow-black/5 ring-0 transition-transform duration-300 [transition-timing-function:cubic-bezier(0.16,1,0.3,1)] data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0 dark:bg-slate-950 rtl:data-[state=checked]:-translate-x-4"+ )}+ />+ </SwitchPrimitives.Root>+ ))+);Switch.displayName = SwitchPrimitives.Root.displayName;export { Switch };diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsxindex cb7b50c..fa276d6 100644--- a/src/components/ui/tooltip.tsx+++ b/src/components/ui/tooltip.tsx@@ -5,55 +5,86 @@ import * as React from "react";import { cn } from "@/lib/utils";-const TooltipProvider = TooltipPrimitive.Provider;+const TooltipProvider = React.memo(TooltipPrimitive.Provider);-const Tooltip = TooltipPrimitive.Root;+// Add Provider wrapper for app-wide usage+function TooltipProviderWrapper({ children }: { children: React.ReactNode }) {+ return <TooltipProvider delayDuration={0}>{children}</TooltipProvider>;+}-const TooltipTrigger = TooltipPrimitive.Trigger;+const Tooltip = React.memo(TooltipPrimitive.Root);-const TooltipContent = React.forwardRef<- React.ElementRef<typeof TooltipPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> & {- showArrow?: boolean;- }->(({ className, sideOffset = 4, showArrow = false, ...props }, ref) => (- <TooltipPrimitive.Portal>- <TooltipPrimitive.Content- ref={ref}- sideOffset={sideOffset}- className={cn(- "relative z-50 max-w-[280px] rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm text-slate-950 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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}- >- {props.children}- {showArrow && (- <TooltipPrimitive.Arrow className="my-px border-slate-200 fill-white drop-shadow-[0_1px_0_hsl(var(--border))]" />- )}- </TooltipPrimitive.Content>- </TooltipPrimitive.Portal>-));+const TooltipTrigger = React.memo(TooltipPrimitive.Trigger);++const TooltipContent = React.memo(+ React.forwardRef<+ React.ElementRef<typeof TooltipPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> & {+ showArrow?: boolean;+ }+ >(({ className, sideOffset = 4, showArrow = false, ...props }, ref) => (+ <TooltipPrimitive.Portal>+ <TooltipPrimitive.Content+ ref={ref}+ sideOffset={sideOffset}+ className={cn(+ "relative z-50 max-w-[280px] rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm text-slate-950 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-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}+ >+ {props.children}+ {showArrow && (+ <TooltipPrimitive.Arrow className="my-px border-slate-200 fill-white drop-shadow-[0_1px_0_hsl(var(--border))]" />+ )}+ </TooltipPrimitive.Content>+ </TooltipPrimitive.Portal>+ ))+);TooltipContent.displayName = TooltipPrimitive.Content.displayName;-const CustomTooltip = ({- trigger,- content,- className,-}: {+interface CustomTooltipProps {trigger: React.ReactNode;content: React.ReactNode;className?: string;-}) => {- return (- <Tooltip>- <TooltipTrigger asChild>{trigger}</TooltipTrigger>- <TooltipContent className={cn("px-2 py-1 text-xs", className)}>- {content}- </TooltipContent>- </Tooltip>- );-};+ side?: "top" | "right" | "bottom" | "left";+ align?: "start" | "center" | "end";+ delayDuration?: number;+ showArrow?: boolean;+}++const CustomTooltip = React.memo(+ ({+ trigger,+ content,+ className,+ side = "top",+ align = "center",+ delayDuration = 300,+ showArrow = false,+ }: CustomTooltipProps) => {+ // Memoize both trigger and content+ const memoizedTrigger = React.useMemo(() => trigger, [trigger]);+ const memoizedContent = React.useMemo(() => content, [content]);++ return (+ <Tooltip delayDuration={delayDuration}>+ <TooltipTrigger asChild>{memoizedTrigger}</TooltipTrigger>+ {memoizedContent ? (+ <TooltipContent+ side={side}+ align={align}+ className={cn("px-2 py-1 text-xs", className)}+ showArrow={showArrow}+ >+ {memoizedContent}+ </TooltipContent>+ ) : null}+ </Tooltip>+ );+ }+);+CustomTooltip.displayName = "CustomTooltip";export {Tooltip,@@ -61,4 +92,5 @@ export {TooltipProvider,TooltipTrigger,CustomTooltip,+ TooltipProviderWrapper,};