Index: src/app/api/invoices/[id]/route.ts
===================================================================
--- src/app/api/invoices/[id]/route.ts	(revision dc3406b4adcd188a5b90d471779b2da7665882cc)
+++ src/app/api/invoices/[id]/route.ts	(revision 5d6f37a75130aab7d9a67b5b430603eff2c0ca6e)
@@ -1,16 +1,10 @@
 import { NextRequest, NextResponse } from 'next/server';
-import { invoiceSchema, updateInvoiceSchema } from 'src/schemas';
+import { invoiceSchema } from 'mvpmasters-shared';
 import prisma from 'src/lib/prisma';
 import { authenticateRequest } from 'src/lib/auth-middleware';
-import { Prisma } from '@prisma/client';
 
-export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
+export async function PATCH(request: NextRequest, { params }: { params: { id: string } }) {
   try {
-    // Validate ID format
-    if (!params.id || !/^[0-9a-fA-F-]+$/.test(params.id)) {
-      return NextResponse.json({ error: 'Invalid invoice ID format' }, { status: 400 });
-    }
-
-    // Authenticate request
+    // Authenticate the request
     const authResult = await authenticateRequest(request);
     if (authResult instanceof NextResponse) {
@@ -19,181 +13,32 @@
     const { userId } = authResult;
 
-    // Fetch invoice with user check
-    const invoice = await prisma.invoice.findFirst({
-      where: {
-        id: params.id,
-        // invoiceFromId: userId,
+    const body = await request.json();
+    const validatedData = invoiceSchema.partial().parse(body);
+
+    const invoice = await prisma.invoice.update({
+      where: { id: params.id, userId },
+      data: {
+        ...validatedData,
+        items: validatedData.items
+          ? {
+              deleteMany: {},
+              create: validatedData.items,
+            }
+          : undefined,
       },
       include: {
+        items: {
+          include: {
+            service: true,
+          },
+        },
         invoiceFrom: true,
         invoiceTo: true,
-        items: true,
       },
     });
 
-    if (!invoice) {
-      return NextResponse.json({ error: 'Invoice not found or access denied' }, { status: 404 });
-    }
-
     return NextResponse.json(invoice);
   } catch (error) {
-    console.error('Error fetching invoice:', error);
-
-    if (error instanceof Prisma.PrismaClientKnownRequestError) {
-      return NextResponse.json({ error: 'Database error occurred' }, { status: 500 });
-    }
-
-    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
+    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
   }
 }
-
-export async function PATCH(request: NextRequest, { params }: { params: { id: string } }) {
-  try {
-    // Validate ID format
-    if (!params.id || !/^[0-9a-fA-F-]+$/.test(params.id)) {
-      return NextResponse.json({ error: 'Invalid invoice ID format' }, { status: 400 });
-    }
-
-    // Authenticate request
-    const authResult = await authenticateRequest(request);
-    if (authResult instanceof NextResponse) {
-      return authResult;
-    }
-    const { userId } = authResult;
-
-    // Parse and validate request body
-    const body = await request.json();
-
-    const validation = updateInvoiceSchema.partial().safeParse(body);
-
-    if (!validation.success) {
-      return NextResponse.json(
-        { error: 'Invalid invoice data', details: validation.error.format() },
-        { status: 400 }
-      );
-    }
-
-    // Verify invoice exists and belongs to user
-    const existingInvoice = await prisma.invoice.findFirst({
-      where: {
-        id: params.id,
-        // invoiceFromId: userId,
-      },
-    });
-
-    if (!existingInvoice) {
-      return NextResponse.json({ error: 'Invoice not found or access denied' }, { status: 404 });
-    }
-
-    // Update invoice and related data
-    const updatedInvoice = await prisma.$transaction(async (tx) => {
-      // Conditionally delete and recreate items only if they are provided
-      if (validation.data.items) {
-        await tx.lineItem.deleteMany({
-          where: { invoiceId: params.id },
-        });
-      }
-
-      // Update the invoice and create new items if provided
-      return tx.invoice.update({
-        where: { id: params.id },
-        data: {
-          invoiceNumber: validation.data.invoiceNumber,
-          issueDate: validation.data.issueDate,
-          dueDate: validation.data.dueDate,
-          status: validation.data.status,
-          currency: validation.data.currency,
-          quantityType: validation.data.quantityType,
-          subTotal: validation.data.subTotal,
-          month: validation.data.month,
-          totalAmount: validation.data.totalAmount,
-          discount: validation.data.discount,
-          taxes: validation.data.taxes,
-          pdfRef: validation.data.pdfRef,
-          invoiceTo: {
-            update: validation.data.invoiceTo,
-          },
-          items: validation.data.items
-            ? {
-                create: validation.data.items.map((item) => ({
-                  ...item,
-                  service: {
-                    connect: { id: item.service.id },
-                  },
-                })),
-              }
-            : undefined,
-        },
-        include: {
-          invoiceFrom: true,
-          invoiceTo: true,
-          items: true,
-        },
-      });
-    });
-
-    return NextResponse.json(updatedInvoice);
-  } catch (error) {
-    console.error('Error updating invoice:', error);
-
-    if (error instanceof Prisma.PrismaClientKnownRequestError) {
-      return NextResponse.json({ error: 'Database error occurred' }, { status: 500 });
-    }
-
-    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
-  }
-}
-
-export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
-  try {
-    // Validate ID format
-    if (!params.id || !/^[0-9a-fA-F-]+$/.test(params.id)) {
-      return NextResponse.json({ error: 'Invalid invoice ID format' }, { status: 400 });
-    }
-
-    // Authenticate request
-    const authResult = await authenticateRequest(request);
-    if (authResult instanceof NextResponse) {
-      return authResult;
-    }
-    const { userId } = authResult;
-    console.log('userId', userId);
-
-    // Verify invoice exists and belongs to user
-    const existingInvoice = await prisma.invoice.findFirst({
-      where: {
-        id: params.id,
-      },
-    });
-
-    if (!existingInvoice) {
-      return NextResponse.json({ error: 'Invoice not found or access denied' }, { status: 404 });
-    }
-
-    // Delete invoice and related items in a transaction
-    await prisma.$transaction(async (tx) => {
-      // Delete related items first
-      await tx.lineItem.deleteMany({
-        where: { invoiceId: params.id },
-      });
-
-      // Delete the invoice
-      await tx.invoice.delete({
-        where: { id: params.id },
-      });
-    });
-
-    return NextResponse.json({ message: 'Invoice deleted successfully' }, { status: 200 });
-  } catch (error) {
-    console.error('Error deleting invoice:', error);
-
-    if (error instanceof Prisma.PrismaClientKnownRequestError) {
-      if (error.code === 'P2025') {
-        return NextResponse.json({ error: 'Invoice not found' }, { status: 404 });
-      }
-      return NextResponse.json({ error: 'Database error occurred' }, { status: 500 });
-    }
-
-    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
-  }
-}
Index: src/app/api/invoices/route.ts
===================================================================
--- src/app/api/invoices/route.ts	(revision dc3406b4adcd188a5b90d471779b2da7665882cc)
+++ src/app/api/invoices/route.ts	(revision 5d6f37a75130aab7d9a67b5b430603eff2c0ca6e)
@@ -1,7 +1,6 @@
 import { NextRequest, NextResponse } from 'next/server';
-import { createInvoiceSchema, invoiceSchema, invoiceTableFiltersSchema } from 'src/schemas';
+import { invoiceSchema, invoiceTableFiltersSchema } from 'mvpmasters-shared';
 import prisma from 'src/lib/prisma';
 import { auth } from 'src/lib/firebase-admin';
-import { InvoiceStatus } from '@prisma/client';
 
 // Helper function to get userId from Authorization header
@@ -24,7 +23,7 @@
   try {
     const userId = await getUserId(request);
-    // if (!userId) {
-    //   return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
-    // }
+    if (!userId) {
+      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+    }
 
     const searchParams = request.nextUrl.searchParams;
@@ -42,10 +41,9 @@
     const invoices = await prisma.invoice.findMany({
       where: {
-        status: validatedFilters.status
-          ? { equals: validatedFilters.status as InvoiceStatus }
-          : undefined,
-        issueDate: {
-          ...(validatedFilters.startDate && { gte: validatedFilters.startDate }),
-          ...(validatedFilters.endDate && { lte: validatedFilters.endDate }),
+        userId,
+        status: validatedFilters.status ? { equals: validatedFilters.status } : undefined,
+        createDate: {
+          gte: validatedFilters.startDate,
+          lte: validatedFilters.endDate,
         },
         items:
@@ -74,57 +72,17 @@
   try {
     const userId = await getUserId(request);
-    // if (!userId) {
-    //   return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
-    // }
+    if (!userId) {
+      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+    }
 
     const body = await request.json();
-    const validatedData = createInvoiceSchema.parse(body);
-
-    const tenant = await prisma.tenant.findUnique({
-      where: { id: validatedData.invoiceFrom.id },
-    });
-
-    const toCustomer = await prisma.client.findUnique({
-      where: { id: validatedData.invoiceTo.id },
-    });
-
-    if (!tenant || !toCustomer) {
-      return NextResponse.json({ error: 'Invoice sender or recipient not found' }, { status: 404 });
-    }
-
-    // Update lastInvoiceNumber in tenant
-    const updatedTenant = await prisma.tenant.update({
-      where: { id: tenant.id },
-      data: {
-        lastInvoiceNumber: validatedData.invoiceNumber,
-      },
-    });
+    const validatedData = invoiceSchema.parse(body);
 
     const invoice = await prisma.invoice.create({
       data: {
-        dueDate: validatedData.dueDate,
-        status: validatedData.status,
-        currency: validatedData.currency,
-        quantityType: validatedData.quantityType,
-        subTotal: validatedData.subTotal,
-        issueDate: validatedData.issueDate,
-        month: validatedData.month,
-        discount: validatedData.discount,
-        taxes: validatedData.taxes,
-        totalAmount: validatedData.totalAmount,
-        invoiceNumber: validatedData.invoiceNumber,
-        invoiceFromId: tenant.id,
-        invoiceToId: toCustomer.id,
+        ...validatedData,
+        userId,
         items: {
-          create: validatedData.items.map((item) => ({
-            title: item.title,
-            price: item.price,
-            total: item.total,
-            quantity: item.quantity,
-            description: item.description,
-            service: {
-              connect: { id: item.service.id },
-            },
-          })),
+          create: validatedData.items,
         },
       },
@@ -142,5 +100,4 @@
     return NextResponse.json(invoice, { status: 201 });
   } catch (error) {
-    console.error(error);
     return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
   }
Index: src/app/api/invoices/totals/route.ts
===================================================================
--- src/app/api/invoices/totals/route.ts	(revision dc3406b4adcd188a5b90d471779b2da7665882cc)
+++ 	(revision )
@@ -1,71 +1,0 @@
-import { NextRequest, NextResponse } from 'next/server';
-import prisma from 'src/lib/prisma';
-import { authenticateRequest } from 'src/lib/auth-middleware';
-
-type InvoiceStatus = 'processing' | 'paid' | 'pending' | 'overdue' | 'draft';
-type CurrencyTotals = { EUR: number; USD: number };
-type Results = Record<InvoiceStatus | 'total', CurrencyTotals>;
-
-export async function GET(request: NextRequest) {
-  try {
-    // Authenticate the request
-    const authResult = await authenticateRequest(request);
-
-    if (!authResult || authResult instanceof NextResponse) {
-      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
-    }
-
-    const { userId, tenantId } = authResult;
-
-    const searchParams = request.nextUrl.searchParams;
-    const startDate = searchParams.get('startDate')
-      ? new Date(searchParams.get('issueDate')!)
-      : null;
-
-    if (!startDate) {
-      return NextResponse.json({ error: 'Start date is required' }, { status: 400 });
-    }
-
-    // Calculate totals using raw SQL
-    const totals = await prisma.$queryRaw`
-      SELECT 
-        status,
-        currency,
-        SUM("total_amount") as total
-      FROM "Invoice"
-      WHERE "issue_date" >= ${startDate}
-        AND "tenant_id" = ${tenantId}
-      GROUP BY status, currency
-    `;
-
-    // Format the response
-    const results: Results = {
-      total: { EUR: 0, USD: 0 },
-      processing: { EUR: 0, USD: 0 },
-      paid: { EUR: 0, USD: 0 },
-      pending: { EUR: 0, USD: 0 },
-      overdue: { EUR: 0, USD: 0 },
-      draft: { EUR: 0, USD: 0 },
-    };
-
-    // Process the results - adjusted for raw SQL response format
-    for (const row of totals as {
-      status: string;
-      currency: 'EUR' | 'USD';
-      total: string | number;
-    }[]) {
-      const { status, currency, total } = row;
-      const statusKey = status.toLowerCase() as InvoiceStatus;
-      if (statusKey in results && (currency === 'EUR' || currency === 'USD')) {
-        const amount = Number(total) || 0;
-        results[statusKey][currency] = amount;
-        results.total[currency] += amount;
-      }
-    }
-
-    return NextResponse.json(results);
-  } catch (error) {
-    console.error('Error calculating totals:', error);
-    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
-  }
-}
