Bansari Akhani commited on
Commit
464e8df
·
1 Parent(s): 662175b

improvise erro handling of PW response

Browse files
src/controllers/propertyware/bills.controller.ts CHANGED
@@ -4,24 +4,32 @@ import Invoice from '../../models/invoice';
4
  import InvoiceDetail from '../../models/invoicedetail';
5
  import { createBill } from '../../shared/services/propertyware.service';
6
  import { formatDate } from '../../utils/dataUtils';
7
- import ErrorLog from './../../models/errorLog';
8
  import { createAuditLog } from '../auditLog.controller';
9
 
10
- export const syncInvoices = async (req: Request, res: Response) => {
 
 
 
 
 
 
 
 
 
 
11
  try {
12
  const invoices = await Invoice.findAll({
13
  where: { status: 'approved' },
14
- include: [
15
- { model: InvoiceDetail }
16
- ]
17
  });
18
 
19
- if (invoices.length == 0) {
20
  res.end("No invoice to sync");
 
21
  }
22
 
23
- // Map the invoices to the bill request format
24
- invoices.forEach(async (invoice) => {
25
  const bill = {
26
  billDate: formatDate(invoice.invoice_date),
27
  billSplits: invoice.InvoiceDetails.map(detail => ({
@@ -33,7 +41,7 @@ export const syncInvoices = async (req: Request, res: Response) => {
33
  paid: false,
34
  unitID: detail.pw_unit_id
35
  })),
36
- dueDate: invoice.due_date ? formatDate(invoice.due_date) : null,
37
  vendorID: invoice.pw_vendor_id?.toString(),
38
  billNumber: invoice.invoice_number,
39
  comments: invoice.description,
@@ -41,32 +49,76 @@ export const syncInvoices = async (req: Request, res: Response) => {
41
  terms: invoice.term,
42
  workOrderID: invoice.pw_work_order_id,
43
  };
 
44
  try {
45
  const response = await createBill(bill);
46
 
47
- // add audit log for Update Invoice
48
- const auditLogData = { invoice_id: invoice.id as number, action_by: 1, action: 'Invoice sync to PW', details: `Bill for invoice ${bill.refNo} synced successfully. PW invoice id : ${response.id}`};
49
- createAuditLog(auditLogData);
 
 
 
 
 
50
 
51
- // Update Invoide status
52
- await invoice.update({status:'Sync success'});
53
 
54
  logger.info(`Bill for invoice ${bill.refNo} synced successfully`);
55
  } catch (error) {
56
- if (error instanceof Error ){
57
- await invoice.update({status:'Sync failed'})
 
 
 
 
 
 
 
 
 
 
58
 
59
- logger.error(`Error syncing bill for invoice ${bill.refNo}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- // add entry to error log
62
- const errorLogData = { invoice_id: invoice.id as number, error_type: 'PW Sync Failed', error_details: `Error syncing bill for invoice ${bill.refNo}. ${error.message}`};
 
 
 
 
 
 
 
 
 
 
63
  await ErrorLog.create(errorLogData);
64
  }
65
- logger.error(error);
66
  }
67
  });
68
 
69
-
70
 
71
  res.end("Invoice data synced successfully");
72
  } catch (error) {
 
4
  import InvoiceDetail from '../../models/invoicedetail';
5
  import { createBill } from '../../shared/services/propertyware.service';
6
  import { formatDate } from '../../utils/dataUtils';
7
+ import ErrorLog from '../../models/errorLog';
8
  import { createAuditLog } from '../auditLog.controller';
9
 
10
+ interface ErrorResponse {
11
+ response: {
12
+ data: {
13
+ userMessage: string;
14
+ errorCode: string;
15
+ errors?: Array<{ key: string; message: string }>;
16
+ }
17
+ }
18
+ }
19
+
20
+ export const syncInvoices = async (req: Request, res: Response): Promise<void> => {
21
  try {
22
  const invoices = await Invoice.findAll({
23
  where: { status: 'approved' },
24
+ include: [{ model: InvoiceDetail }]
 
 
25
  });
26
 
27
+ if (invoices.length === 0) {
28
  res.end("No invoice to sync");
29
+ return;
30
  }
31
 
32
+ const syncPromises = invoices.map(async (invoice) => {
 
33
  const bill = {
34
  billDate: formatDate(invoice.invoice_date),
35
  billSplits: invoice.InvoiceDetails.map(detail => ({
 
41
  paid: false,
42
  unitID: detail.pw_unit_id
43
  })),
44
+ dueDate: invoice.due_date ? formatDate(invoice.due_date) : null,
45
  vendorID: invoice.pw_vendor_id?.toString(),
46
  billNumber: invoice.invoice_number,
47
  comments: invoice.description,
 
49
  terms: invoice.term,
50
  workOrderID: invoice.pw_work_order_id,
51
  };
52
+
53
  try {
54
  const response = await createBill(bill);
55
 
56
+ // Add audit log for Update Invoice
57
+ const auditLogData = {
58
+ invoice_id: invoice.id as number,
59
+ action_by: 1,
60
+ action: 'Invoice sync to PW',
61
+ details: `Bill for invoice ${bill.refNo} synced successfully. PW invoice id: ${response.id}`
62
+ };
63
+ await createAuditLog(auditLogData);
64
 
65
+ // Update Invoice status
66
+ await invoice.update({ status: 'Sync success' });
67
 
68
  logger.info(`Bill for invoice ${bill.refNo} synced successfully`);
69
  } catch (error) {
70
+ let errorMessage = `Error syncing bill for invoice ${bill.refNo}.`;
71
+
72
+ const errorobj = (error as ErrorResponse);
73
+
74
+ const errordata = errorobj.response.data;
75
+
76
+ if (errordata) {
77
+ if (errordata.errors && Array.isArray(errordata.errors)) {
78
+ errorMessage += ` Errors: ${errordata.errors.map(e => `${e.key}: ${e.message}`).join(', ')}`;
79
+ } else {
80
+ errorMessage += ` ${errordata.userMessage}`;
81
+ }
82
 
83
+ logger.error(errorMessage);
84
+
85
+ // Add entry to error log
86
+ const errorLogData = {
87
+ invoice_id: invoice.id as number,
88
+ error_type: 'PW Sync Failed',
89
+ error_details: errorMessage
90
+ };
91
+ await ErrorLog.create(errorLogData);
92
+ } else if (error instanceof Error) {
93
+
94
+ logger.error(`Error syncing bill for invoice ${bill.refNo}: ${error.message}`);
95
+
96
+ // Add entry to error log
97
+ const errorLogData = {
98
+ invoice_id: invoice.id as number,
99
+ error_type: 'PW Sync Failed',
100
+ error_details: `Error syncing bill for invoice ${bill.refNo}. ${error.message}`
101
+ };
102
 
103
+ await ErrorLog.create(errorLogData);
104
+ } else {
105
+
106
+ logger.error(`Unknown error syncing bill for invoice ${bill.refNo}`);
107
+ logger.error(error);
108
+
109
+ // Add entry to error log
110
+ const errorLogData = {
111
+ invoice_id: invoice.id as number,
112
+ error_type: 'PW Sync Failed',
113
+ error_details: `Unknown error syncing bill for invoice ${bill.refNo}`
114
+ };
115
  await ErrorLog.create(errorLogData);
116
  }
117
+ await invoice.update({ status: 'Sync failed' });
118
  }
119
  });
120
 
121
+ await Promise.all(syncPromises);
122
 
123
  res.end("Invoice data synced successfully");
124
  } catch (error) {