File size: 5,888 Bytes
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
0159174
0330133
 
0159174
 
 
 
 
 
0330133
0159174
0330133
0159174
0330133
0159174
0330133
 
 
 
 
0159174
0330133
 
 
0159174
0330133
0159174
 
 
 
 
 
 
 
 
0330133
0159174
 
0330133
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
0159174
 
 
 
 
 
 
0330133
 
 
 
0159174
 
 
 
 
 
 
0330133
0159174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0330133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0159174
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import Service from "../models/ServiceModel.js";
import Product from "../models/ProductModel.js";

/**

 * Validate and process invoice items (products + services)

 */
export const validateInvoiceItems = async (items, tenantId, branchId) => {
   if (!Array.isArray(items) || items.length === 0) {
      throw new Error("ูŠุฌุจ ุฅุถุงูุฉ ุตู†ู ูˆุงุญุฏ ุนู„ู‰ ุงู„ุฃู‚ู„");
   }

   const processedItems = [];
   let hasServices = false;

   for (const item of items) {
      if (!item.name || !item.price || !item.quantity) {
         throw new Error("ูƒู„ ุตู†ู ูŠุฌุจ ุฃู† ูŠุญุชูˆูŠ ุนู„ู‰ ุงุณู… ูˆุณุนุฑ ูˆูƒู…ูŠุฉ");
      }

      if (item.type === "service" && item.serviceId) {
         const service = await Service.findOne({
            _id: item.serviceId,
            tenant: tenantId,
            isDeleted: false,
         });
         if (!service) throw new Error(`ุงู„ุฎุฏู…ุฉ ุบูŠุฑ ู…ูˆุฌูˆุฏุฉ: ${item.name}`);
         hasServices = true;
         processedItems.push({ ...item, type: "service", serviceId: item.serviceId });

      } else if (item.type === "product" && item.productId) {
         const product = await Product.findOne({
            _id: item.productId,
            tenant: tenantId,
            branch: branchId,
         });
         if (!product) throw new Error(`ุงู„ู…ู†ุชุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ: ${item.name}`);
         if (product.stock < Number(item.quantity)) {
            throw new Error(`ุงู„ู…ุฎุฒูˆู† ุบูŠุฑ ูƒุงูู ู„ู„ุตู†ู ${item.name}. ุงู„ู…ุชุงุญ: ${product.stock}`);
         }
         processedItems.push({ ...item, type: "product", productId: item.productId });

      } else if (item.type === "catalog" && item.catalogItemId) {   // โœ… new branch
         const catalogItem = await CatalogItem.findOne({
            _id: item.catalogItemId,
            tenant: tenantId,
            isActive: true,
         });
         if (!catalogItem) throw new Error(`ุนู†ุตุฑ ุงู„ูƒุชุงู„ูˆุฌ ุบูŠุฑ ู…ูˆุฌูˆุฏ: ${item.name}`);
         processedItems.push({ ...item, type: "catalog", catalogItemId: item.catalogItemId });

      } else {
         throw new Error(`ู†ูˆุน ุงู„ุตู†ู ุบูŠุฑ ุตุญูŠุญ ุฃูˆ ู…ุนุฑู ู…ูู‚ูˆุฏ: ${item.name}`);
      }
   }

   return { processedItems, hasServices };
};

/**

 * Apply items to invoice and update stock for products

 */
export const applyInvoiceItemsAndStock = async (invoice, items, tenantId, branchId) => {
   let serviceRevenue = 0;
   let productRevenue = 0;
   let catalogRevenue = 0;   // โœ… add catalog tracking

   for (const item of items) {
      const quantity = Number(item.quantity || 1);
      const price = Number(item.price || 0);
      const total = quantity * price;

      const invoiceItem = {
         name: item.name,
         quantity,
         price,
         total,
         type: item.type || "product",
         date: new Date(),
      };

      if (item.type === "service" && item.serviceId) {
         invoiceItem.serviceId = item.serviceId;
         serviceRevenue += total;

      } else if (item.type === "product" && item.productId) {
         invoiceItem.productId = item.productId;
         productRevenue += total;
         await Product.findOneAndUpdate(
            { _id: item.productId, tenant: tenantId, branch: branchId },
            { $inc: { stock: -quantity } }
         );

      } else if (item.type === "catalog" && item.catalogItemId) {   // โœ… new branch
         invoiceItem.catalogItemId = item.catalogItemId;
         catalogRevenue += total;
      }

      invoice.items.push(invoiceItem);
   }

   invoice.serviceRevenue = serviceRevenue;
   invoice.productRevenue = productRevenue;
   invoice.catalogRevenue = catalogRevenue;   // โœ… now tracked
   invoice.hasServices = serviceRevenue > 0;
};

/**

 * Create income records for different revenue types

 */
export const createIncomeRecords = async ({

   tenantId,

   branchId,

   invoice,

   customer,

   userId,

   date = new Date(),

}) => {
   const incomeRecords = [];

   if (invoice.serviceRevenue > 0) {
      incomeRecords.push({
         tenant: tenantId,
         branch: branchId,
         title: `Service income - ${invoice.invoiceNumber}`,
         category: "service_income",
         amount: invoice.serviceRevenue,
         paymentMethod: "cash",
         notes: `Service revenue from invoice ${invoice.invoiceNumber}`,
         sourceType: "invoice_payment",
         relatedInvoice: invoice._id,
         relatedCustomer: customer?._id || null,
         date,
         createdBy: userId || null,
      });
   }

   if (invoice.productRevenue > 0) {
      incomeRecords.push({
         tenant: tenantId,
         branch: branchId,
         title: `Product sales - ${invoice.invoiceNumber}`,
         category: customer?.isWalkIn ? "walk_in_sale" : "invoice_payment",
         amount: invoice.productRevenue,
         paymentMethod: "cash",
         notes: `Product revenue from invoice ${invoice.invoiceNumber}`,
         sourceType: "invoice_payment",
         relatedInvoice: invoice._id,
         relatedCustomer: customer?._id || null,
         date,
         createdBy: userId || null,
      });
   }
   if (invoice.catalogRevenue > 0) {   
      incomeRecords.push({
         tenant: tenantId,
         branch: branchId,
         title: `Catalog sales - ${invoice.invoiceNumber}`,
         category: "catalog_sale",
         amount: invoice.catalogRevenue,
         paymentMethod: "cash",
         notes: `Catalog revenue from invoice ${invoice.invoiceNumber}`,
         sourceType: "invoice_payment",
         relatedInvoice: invoice._id,
         relatedCustomer: customer?._id || null,
         date,
         createdBy: userId || null,
      });
   }

   return incomeRecords;
};