narinder1231's picture
improve error logging and error messages
d747060
import { logger } from '../../utils/logger';
import Invoice from '../../models/invoice';
import InvoiceDetail from '../../models/invoicedetail';
import { createBill, uploadBill, uploadBillToOwnerPortal } from './propertyware.service';
import { formatDate } from '../../utils/dataUtils';
import ErrorLog from '../../models/errorLog';
import { createAuditLog } from '../../controllers/auditLog.controller';
import { updateInvoiceData } from '../../controllers/invoice/invoice.controller';
import axios from 'axios';
import FormData from 'form-data';
interface ErrorResponse {
response: {
data: {
userMessage: string;
errorCode: string;
errors?: Array<{ key: string; message: string }>;
}
}
}
export const syncInvoicesService = async (): Promise<string> => {
try {
const invoices = await Invoice.findAll({
where: { status: 'Approved' },
include: [{ model: InvoiceDetail }]
});
if (invoices.length === 0) {
return "No invoice to sync";
}
const syncPromises = invoices.map(async (invoice) => {
const bill = {
billDate: formatDate(invoice.invoice_date),
billSplits: invoice.InvoiceDetails.map(detail => ({
amount: detail.amount as number,
glAccountID: detail.pw_gl_account_id,
portfolioID: detail.pw_portfolio_id,
buildingID: detail.pw_building_id,
comments: detail.description,
paid: false,
unitID: detail.pw_unit_id
})),
dueDate: invoice.due_date ? formatDate(invoice.due_date) : null,
vendorID: invoice.pw_vendor_id?.toString(),
comments: invoice.description,
refNo: invoice.reference_number,
terms: invoice.term,
workOrderID: invoice.pw_work_order_id,
};
try {
const response = await createBill(bill);
// Add audit log for Update Invoice
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}`
};
await createAuditLog(auditLogData);
try {
// upload invoice file to propertyware
if (invoice.filename) {
try {
const { data } = await axios.get(invoice.pdf_url as string, {
responseType: 'arraybuffer'
});
const fileBuffer = Buffer.from(data);
const formData = new FormData();
formData.append('file', fileBuffer, {
filename: invoice.filename
});
const billDocumentResponse = await uploadBill(response.id, formData);
await uploadBillToOwnerPortal(billDocumentResponse.id, invoice.filename);
} catch (error) {
logger.error("Invoice file upload failed: ");
logger.error(error);
}
}
} catch (error) {
logger.error("Invoice file upload failed: ");
logger.error(error);
}
// Update Invoice status
await updateInvoiceData(invoice.id as number, { status: 'Sync success' }, 1);
logger.info(`Bill for invoice ${bill.refNo} synced successfully`);
} catch (error) {
let errorMessage = `Error syncing bill for invoice ${bill.refNo}.`;
const errorobj = (error as ErrorResponse);
const errordata = errorobj.response.data;
if (errordata) {
if (errordata.errors && Array.isArray(errordata.errors)) {
errorMessage += ` Errors: ${errordata.errors.map(e => `${e.key}: ${e.message}`).join(', ')}`;
} else {
errorMessage += ` ${errordata.userMessage}`;
}
logger.error(errorMessage);
logger.error(error);
// Add entry to error log
const errorLogData = {
invoice_id: invoice.id as number,
error_type: 'PW Sync Failed',
error_details: errorMessage
};
await ErrorLog.create(errorLogData);
} else if (error instanceof Error) {
logger.error(`Error syncing bill for invoice ${bill.refNo}: ${error.message}`);
logger.error(error);
// Add entry to error log
const errorLogData = {
invoice_id: invoice.id as number,
error_type: 'PW Sync Failed',
error_details: `Error syncing bill for invoice ${bill.refNo}. ${error.message}`
};
await ErrorLog.create(errorLogData);
} else {
logger.error(`Unknown error syncing bill for invoice ${bill.refNo}`);
logger.error(error);
// Add entry to error log
const errorLogData = {
invoice_id: invoice.id as number,
error_type: 'PW Sync Failed',
error_details: `Unknown error syncing bill for invoice ${bill.refNo}`
};
await ErrorLog.create(errorLogData);
}
await updateInvoiceData(invoice.id as number, { status: 'Sync Failed' }, 1);
}
});
await Promise.all(syncPromises);
return "Invoice data sync process completed successfully";
} catch (error) {
logger.error('Error while syncing invoices to propertyware:');
logger.error(error);
throw new Error('Error while syncing invoices to propertyware');
}
};