Index: src/sections/invoice/invoice-new-edit-form.tsx
===================================================================
--- src/sections/invoice/invoice-new-edit-form.tsx	(revision dc3406b4adcd188a5b90d471779b2da7665882cc)
+++ src/sections/invoice/invoice-new-edit-form.tsx	(revision 5d6f37a75130aab7d9a67b5b430603eff2c0ca6e)
@@ -11,5 +11,5 @@
 import { useRouter } from 'src/routes/hooks';
 // types
-import { CreateInvoice, Invoice } from 'src/schemas';
+import { Invoice } from 'mvpmasters-shared';
 // hooks
 import { useBoolean } from 'src/hooks/use-boolean';
@@ -20,13 +20,19 @@
 import uploadToFirebaseStorage from 'src/utils/upload-to-firebase-storage';
 import { pdf } from '@react-pdf/renderer';
-import { useGetTenant } from 'src/api/tenant';
-import { collections, generateId, updateDocument } from 'src/lib/firestore';
+import { useGetSettings } from 'src/api/settings';
+import {
+  collections,
+  documents,
+  firestoreBatch,
+  generateId,
+  updateDocument,
+} from 'src/lib/firestore';
 import { useGetServices } from 'src/api/service';
 import { mutate } from 'swr';
+import { Timestamp } from 'firebase/firestore';
 import InvoiceNewEditStatusDate from './invoice-new-edit-status-date';
 import InvoiceNewEditAddress from './invoice-new-edit-address';
 import InvoiceNewEditDetails from './invoice-new-edit-details';
 import InvoicePDF from './invoice-pdf';
-import { createInvoice, updateInvoice } from 'src/api/invoice';
 
 // ----------------------------------------------------------------------
@@ -52,13 +58,4 @@
 ];
 
-interface InvoiceItem {
-  service: string | null;
-  title: string;
-  price: number;
-  total: number;
-  quantity: number;
-  description: string;
-}
-
 export default function InvoiceNewEditForm({ isCopy, currentInvoice }: Props) {
   const router = useRouter();
@@ -72,7 +69,5 @@
     description: Yup.string().required('Description is required'),
     service: Yup.string().nullable(),
-    quantity: Yup.number()
-      .required('Quantity is required')
-      .min(0.5, 'Quantity must be at least 0.5'),
+    quantity: Yup.number().required('Quantity is required').min(0.5, 'Quantity must be at least 1'),
     price: Yup.number().required('Price is required').min(0, 'Price must be at least 0'),
     total: Yup.number().required('Total is required').min(0, 'Total must be at least 0'),
@@ -81,5 +76,5 @@
   const NewInvoiceSchema = Yup.object().shape({
     invoiceNumber: Yup.string().nullable().required('Invoice number is required'),
-    issueDate: Yup.mixed<any>().nullable().required('Create date is required'),
+    createDate: Yup.mixed<any>().nullable().required('Create date is required'),
     dueDate: Yup.mixed<any>()
       .required('Due date is required')
@@ -87,5 +82,5 @@
         'date-min',
         'Due date must be later than create date',
-        (value, { parent }) => value.getTime() > parent.issueDate.getTime()
+        (value, { parent }) => value.getTime() > parent.createDate.getTime()
       ),
     invoiceFrom: Yup.mixed<any>().nullable().required('Invoice from is required'),
@@ -96,5 +91,5 @@
       .required('Quantity type is required'),
     month: Yup.string().oneOf(monthNames).required('Month is required'),
-    status: Yup.string().oneOf(['draft', 'processing', 'pending', 'overdue', 'paid']).required(),
+    status: Yup.string().required(),
     totalAmount: Yup.number().required(),
     // not required
@@ -108,6 +103,5 @@
 
   const { services: invoiceServices } = useGetServices();
-  console.log('invoiceServices', invoiceServices);
-  const { settings: tenant, settingsEmpty, settingsLoading } = useGetTenant();
+  const { settings, settingsEmpty, settingsLoading } = useGetSettings();
 
   const defaultValues = useMemo(
@@ -116,9 +110,7 @@
         !isCopy && currentInvoice?.invoiceNumber
           ? currentInvoice?.invoiceNumber
-          : incrementInvoiceNumber(tenant?.lastInvoiceNumber),
-      issueDate: currentInvoice?.issueDate ? new Date(currentInvoice.issueDate) : new Date(),
-      dueDate: currentInvoice?.dueDate
-        ? new Date(currentInvoice.dueDate)
-        : new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
+          : incrementInvoiceNumber(settings?.invoice?.lastInvoiceNumber),
+      createDate: currentInvoice?.createDate?.toDate() || new Date(),
+      dueDate: currentInvoice?.dueDate?.toDate() || null,
       invoiceFrom: currentInvoice?.invoiceFrom || null,
       invoiceTo: currentInvoice?.invoiceTo || null,
@@ -146,5 +138,5 @@
       totalAmount: currentInvoice?.totalAmount || 0,
     }),
-    [currentInvoice, isCopy, tenant]
+    [currentInvoice, isCopy, settings]
   );
 
@@ -172,16 +164,6 @@
 
     try {
+      // generate collection id
       const id = generateId(collections.invoice);
-
-      // Ensure dates are valid Date objects
-      const issueDate = data.issueDate instanceof Date ? data.issueDate : new Date(data.issueDate);
-      const dueDate = data.dueDate instanceof Date ? data.dueDate : new Date(data.dueDate);
-
-      const currentTime = new Date();
-      issueDate.setHours(
-        currentTime.getHours(),
-        currentTime.getMinutes(),
-        currentTime.getSeconds()
-      );
 
       // attach serivce details
@@ -191,16 +173,21 @@
       }));
 
+      const currentTime = new Date();
+      const createDateWithCurrentTime = new Date(data.createDate); // This creates a date object using the date from data.createDate
+      // Set the time of createDateWithCurrentTime to the current hour, minutes, and seconds
+      createDateWithCurrentTime.setHours(
+        currentTime.getHours(),
+        currentTime.getMinutes(),
+        currentTime.getSeconds()
+      );
+
       // transform data
-      const writeData: CreateInvoice = {
+      const writeData = {
         ...data,
-        invoiceNumber: incrementInvoiceNumber(tenant?.lastInvoiceNumber),
+        invoiceNumber: incrementInvoiceNumber(settings?.invoice.lastInvoiceNumber),
         status: 'draft',
-        issueDate,
-        dueDate,
-        items: items.filter((item) => item.service !== null) as CreateInvoice['items'],
-        subTotal: data.totalAmount - (data.taxes || 0) - (data.discount || 0),
-        month: data.month as Invoice['month'],
-        invoiceFrom: data.invoiceFrom!,
-        invoiceTo: data.invoiceTo!,
+        createDate: Timestamp.fromDate(createDateWithCurrentTime),
+        dueDate: Timestamp.fromDate(new Date(data.dueDate)),
+        items,
       };
 
@@ -208,25 +195,23 @@
       const invoicePdf = <InvoicePDF invoice={writeData as Invoice} currentStatus="pending" />;
       const blob: Blob = await pdf(invoicePdf).toBlob();
-      const storagePath: string = `invoices/${writeData.invoiceTo.name}-${writeData.invoiceNumber}.pdf`;
+      const storagePath: string = `invoices/${writeData.invoiceTo.name}/${id}-${writeData.invoiceNumber}.pdf`;
       await uploadToFirebaseStorage(blob, storagePath);
 
       // write to DB
-      // await firestoreBatch([
-      //   {
-      //     docPath: `${collections.invoice}/${id}`,
-      //     type: 'set',
-      //     data: {
-      //       ...writeData,
-      //       pdfRef: storagePath,
-      //     },
-      //   },
-      //   {
-      //     docPath: `${collections.settings}/${documents.settingsInvoice}`,
-      //     type: 'set',
-      //     data: { lastInvoiceNumber: writeData.invoiceNumber },
-      //   },
-      // ]);
-
-      await createInvoice({ ...writeData, pdfRef: storagePath });
+      await firestoreBatch([
+        {
+          docPath: `${collections.invoice}/${id}`,
+          type: 'set',
+          data: {
+            ...writeData,
+            pdfRef: storagePath,
+          },
+        },
+        {
+          docPath: `${collections.settings}/${documents.settingsInvoice}`,
+          type: 'set',
+          data: { lastInvoiceNumber: writeData.invoiceNumber },
+        },
+      ]);
 
       loadingSave.onFalse();
@@ -244,9 +229,4 @@
     try {
       if (currentInvoice) {
-        // Ensure dates are valid Date objects
-        const issueDate =
-          data.issueDate instanceof Date ? data.issueDate : new Date(data.issueDate);
-        const dueDate = data.dueDate instanceof Date ? data.dueDate : new Date(data.dueDate);
-
         // attach serivce details
         const items = data.items.map((item) => ({
@@ -258,9 +238,7 @@
         const writeData = {
           ...data,
-          issueDate,
-          dueDate,
+          createDate: Timestamp.fromDate(new Date(data.createDate)),
+          dueDate: Timestamp.fromDate(new Date(data.dueDate)),
           items,
-          invoiceFrom: data.invoiceFrom!,
-          invoiceTo: data.invoiceTo!,
         };
 
@@ -268,50 +246,18 @@
         const invoicePdf = <InvoicePDF invoice={writeData as Invoice} currentStatus="pending" />;
         const blob: Blob = await pdf(invoicePdf).toBlob();
-        const storagePath: string = `invoices/${data.invoiceTo.name}-${data.invoiceNumber}.pdf`;
+        const storagePath: string = `invoices/${data.invoiceTo.name}/${currentInvoice.id}-${data.invoiceNumber}.pdf`;
         await uploadToFirebaseStorage(blob, storagePath);
 
         // update DB
-        // await updateDocument(collections.invoice, currentInvoice.id, {
-        //   ...writeData,
-        //   pdfRef: storagePath,
-        // });
-
-        await updateInvoice(currentInvoice.id, {
+        await updateDocument(collections.invoice, currentInvoice.id, {
           ...writeData,
           pdfRef: storagePath,
-          status: data.status as 'draft' | 'processing' | 'pending' | 'overdue' | 'paid',
-          month: data.month as
-            | 'January'
-            | 'February'
-            | 'March'
-            | 'April'
-            | 'May'
-            | 'June'
-            | 'July'
-            | 'August'
-            | 'September'
-            | 'October'
-            | 'November'
-            | 'December',
-          items: items.filter((item) => item.service !== null) as {
-            service: { id: string; month: number; name: string; sprint: number; hour: number };
-            title: string;
-            price: number;
-            total: number;
-            quantity: number;
-            description: string;
-          }[],
         });
 
         // mutate current data
-        // mutate([collections.invoice, currentInvoice.id]);
+        mutate([collections.invoice, currentInvoice.id]);
       } else {
         // generate collection id
         const id = generateId(collections.invoice);
-
-        // Ensure dates are valid Date objects
-        const issueDate =
-          data.issueDate instanceof Date ? data.issueDate : new Date(data.issueDate);
-        const dueDate = data.dueDate instanceof Date ? data.dueDate : new Date(data.dueDate);
 
         // attach serivce details
@@ -324,9 +270,7 @@
         const writeData = {
           ...data,
-          issueDate,
-          dueDate,
+          createDate: Timestamp.fromDate(new Date(data.createDate)),
+          dueDate: Timestamp.fromDate(new Date(data.dueDate)),
           items,
-          invoiceFrom: data.invoiceFrom!,
-          invoiceTo: data.invoiceTo!,
         };
 
@@ -334,24 +278,23 @@
         const invoicePdf = <InvoicePDF invoice={writeData as Invoice} currentStatus="pending" />;
         const blob: Blob = await pdf(invoicePdf).toBlob();
-        const storagePath: string = `invoices/${data.invoiceTo.name}-${data.invoiceNumber}.pdf`;
+        const storagePath: string = `invoices/${data.invoiceTo.name}/${id}-${data.invoiceNumber}.pdf`;
         await uploadToFirebaseStorage(blob, storagePath);
 
         // write to DB
-        // await firestoreBatch([
-        //   {
-        //     docPath: `${collections.invoice}/${id}`,
-        //     type: 'set',
-        //     data: {
-        //       ...writeData,
-        //       pdfRef: storagePath,
-        //     },
-        //   },
-        //   {
-        //     docPath: `${collections.settings}/${documents.settingsInvoice}`,
-        //     type: 'set',
-        //     data: { lastInvoiceNumber: writeData.invoiceNumber },
-        //   },
-        // ]);
-        await createInvoice({ ...writeData, pdfRef: storagePath });
+        await firestoreBatch([
+          {
+            docPath: `${collections.invoice}/${id}`,
+            type: 'set',
+            data: {
+              ...writeData,
+              pdfRef: storagePath,
+            },
+          },
+          {
+            docPath: `${collections.settings}/${documents.settingsInvoice}`,
+            type: 'set',
+            data: { lastInvoiceNumber: writeData.invoiceNumber },
+          },
+        ]);
 
         reset();
@@ -371,5 +314,5 @@
     <FormProvider methods={methods}>
       <Card>
-        {!!tenant && <InvoiceNewEditAddress />}
+        {settings?.company && <InvoiceNewEditAddress />}
 
         <InvoiceNewEditStatusDate isCopy={isCopy} />
