my-typescript-library-rahul52us 3.0.9 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import express from 'express';
2
2
  import { authenticateJWT } from '../controllers/auth.controller';
3
- import { createPendingApprovalService, deleteAllDocumentsService, deleteSingleDocumentService, findOneAndDeleteDocument, getAllDocumentService, getcountDocumentsByLevelAndStatusService, getcountDocumentsWorkflowService, saveAsDraftService, sendMailService, updateDocumentService, updateStatusService, uploadAddtionalDocumentsService, withdrawalApprovalService } from '../services/document/document.services';
3
+ import { createPendingApprovalService, deleteAllDocumentsService, deleteSingleDocumentService, findOneAndDeleteDocument, getAllDocumentService, getcountDocumentsByLevelAndStatusService, getcountDocumentsWorkflowService, getDownloadExcelService, saveAsDraftService, sendMailService, updateDocumentService, updateStatusService, uploadAddtionalDocumentsService, withdrawalApprovalService } from '../services/document/document.services';
4
4
 
5
5
 
6
6
  const Document = express.Router();
@@ -31,5 +31,6 @@ Document.put('/update/status',authenticateJWT,updateStatusService)
31
31
 
32
32
  Document.post("/sendMail",authenticateJWT, sendMailService);
33
33
 
34
+ Document.post("/downloadExcel", authenticateJWT, getDownloadExcelService);
34
35
 
35
36
  export default Document;
@@ -9,6 +9,7 @@ import {
9
9
  getDashChartdata,
10
10
  getDocument,
11
11
  getDocumentCountByLevelAndStatus,
12
+ getDownloadExcelDocument,
12
13
  getPendingApproval,
13
14
  getPendingDash,
14
15
  saveAsDraftDocument,
@@ -42,6 +43,7 @@ import { formatHtmlEditedValues } from "./utils/constant";
42
43
  import dotenv from "dotenv";
43
44
  import DocumentSchema from "../../repository/schemas/document.schema";
44
45
  import { getallUsersWorkFlow } from "../../repository/workflow.repository";
46
+ import { exportInvoicesWithApprovals } from "./utils/function";
45
47
  dotenv.config();
46
48
  interface UserRequest extends Request {
47
49
  user?: {
@@ -1734,3 +1736,106 @@ export async function sendMailService(
1734
1736
  .json({ status: "error", message: "Error sending mail" });
1735
1737
  }
1736
1738
  }
1739
+
1740
+
1741
+ export async function getDownloadExcelFunction(req: any) {
1742
+ try {
1743
+ // let { company, _id, level, defaultWorkflow } = req.user;
1744
+ let { defaultWorkflow } = req.user;
1745
+
1746
+ const _id = req.body._id
1747
+ ? new mongoose.Types.ObjectId(req.body._id)
1748
+ : req.user._id;
1749
+ const level = req.body.level || req.user.level;
1750
+ const company = req.body?.company as string;
1751
+ const status = req.body?.status as string;
1752
+ let value = (req.body?.value as string) || "";
1753
+ let sort = (req.body?.sort as string) || "-1";
1754
+ let limit = (req.body?.limit as string) || null;
1755
+ let page = (req.body?.page as string) || "1";
1756
+ let exchangeType = (req.body.exchangeType as string) || null;
1757
+ let billType = (req?.body?.billType as string) || null;
1758
+ let manual = (req?.body?.manual as string) || null;
1759
+ const dateTo = (req?.body?.dateTo as string) || null;
1760
+ const dateFrom = (req?.body?.dateFrom as string) || null;
1761
+ let searchField = (req?.body?.searchField as string) || null;
1762
+ let dateFilterKey = (req.body.dateFilterKey as string) || "created_At";
1763
+ let sortByKey = (req?.body?.sortByKey as string) || "created_At";
1764
+ let { totalLevel } = await getWorkflowLevelService(
1765
+ req.body.activeWorkflow || defaultWorkflow
1766
+ );
1767
+
1768
+ const { status: statusCode, data } = await getSingleWorkFlowService(
1769
+ req,
1770
+ req.body.activeWorkflow || req.user.defaultWorkflow
1771
+ );
1772
+ let files: any = [];
1773
+ if (statusCode === "success") {
1774
+ if (Array.isArray(data.values.table)) {
1775
+ let filterTable = data.values.table.filter(
1776
+ (item: any) => item.isActive === true
1777
+ );
1778
+ if (filterTable.length) {
1779
+ files = filterTable[0].columnName
1780
+ ?.filter((dt: any) => dt.isFile)
1781
+ .map((fl: any) => fl.key);
1782
+ }
1783
+ }
1784
+ }
1785
+
1786
+ const differentiateFirstLevel = data?.values?.differentiateFirstLevel;
1787
+
1788
+ const documents = await getDownloadExcelDocument(
1789
+ Number(totalLevel),
1790
+ req?.body?.activeWorkflow || defaultWorkflow,
1791
+ value,
1792
+ status,
1793
+ company,
1794
+ _id,
1795
+ differentiateFirstLevel,
1796
+ level,
1797
+ sort,
1798
+ limit,
1799
+ page,
1800
+ req.body.searchFilters || [],
1801
+ billType,
1802
+ manual,
1803
+ dateFrom,
1804
+ dateTo,
1805
+ (searchField = "partnerName"),
1806
+ dateFilterKey,
1807
+ sortByKey,
1808
+ files
1809
+ );
1810
+
1811
+ let base64 = await exportInvoicesWithApprovals(documents?.data || []);
1812
+
1813
+ return {
1814
+ status: "success",
1815
+ statusCode: 200,
1816
+ documents: documents,
1817
+ base64: base64,
1818
+ };
1819
+ } catch (error) {
1820
+ return { status: "error", statusCode: 400, message: error?.message };
1821
+ }
1822
+ }
1823
+
1824
+ export async function getDownloadExcelService(req: Request, res: Response): Promise<void> {
1825
+ try {
1826
+ const { status, statusCode, base64 } = await getDownloadExcelFunction({
1827
+ body: req.body,
1828
+ user: (req as any).user,
1829
+ });
1830
+
1831
+ res.status(statusCode || 200).json({
1832
+ status,
1833
+ base64,
1834
+ });
1835
+ } catch (error: any) {
1836
+ res.status(500).json({
1837
+ status: "error",
1838
+ message: error?.message || "Something went wrong",
1839
+ });
1840
+ }
1841
+ }
@@ -0,0 +1,65 @@
1
+ import ExcelJS from 'exceljs';
2
+
3
+ export async function exportInvoicesWithApprovals(invoices: any): Promise<string> {
4
+ const workbook = new ExcelJS.Workbook();
5
+ workbook.creator = 'Invoice System';
6
+ workbook.created = new Date();
7
+
8
+ // --------------------------------------------------------------
9
+ // 1. INVOICES SHEET – all originalValues + a few top-level fields
10
+ // --------------------------------------------------------------
11
+ const invoiceWs = workbook.addWorksheet('Invoices');
12
+
13
+ const invoiceRows = invoices.map((inv: any) => ({
14
+ documentId: inv.documentId || '',
15
+ created_At: inv.created_At || '',
16
+ overall_status: inv.status || '',
17
+ ...(inv.originalValues || {}),
18
+ }));
19
+
20
+ if (invoiceRows.length) {
21
+ const invHeaders = Object.keys(invoiceRows[0]);
22
+ invoiceWs.addRow(invHeaders).font = { bold: true };
23
+ invoiceRows.forEach((r: any) => invoiceWs.addRow(invHeaders.map((h: string) => r[h] ?? '')));
24
+ invoiceWs.columns.forEach(c => c.width = 20);
25
+ }
26
+
27
+ // --------------------------------------------------------------
28
+ // 2. APPROVALS SHEET – **only documentId** as foreign key
29
+ // --------------------------------------------------------------
30
+ const approvalWs = workbook.addWorksheet('Approvals');
31
+
32
+ const approvalRows: any[] = [];
33
+ invoices.forEach((inv: any) => {
34
+ const docId = inv.documentId || '';
35
+ (inv.approval || []).forEach((appr: any, idx: number) => {
36
+ const user = appr.user || {};
37
+ approvalRows.push({
38
+ documentId: docId, // <-- ONLY link
39
+ approval_step: idx + 1,
40
+ approver_name: user.username || '',
41
+ approver_role: user.role || '',
42
+ approver_level: appr.level || '',
43
+ approval_status: appr.status || '',
44
+ comment: appr.comment || '',
45
+ approved_at: appr.createdAt || '',
46
+ approval_type: appr.type || '',
47
+ });
48
+ });
49
+ });
50
+
51
+ if (approvalRows.length) {
52
+ const apprHeaders = Object.keys(approvalRows[0]);
53
+ approvalWs.addRow(apprHeaders).font = { bold: true };
54
+ approvalRows.forEach((r: any) => approvalWs.addRow(apprHeaders.map((h: string) => r[h] ?? '')));
55
+ approvalWs.columns.forEach(c => c.width = 22);
56
+ } else {
57
+ approvalWs.addRow(['No approvals found']).font = { italic: true };
58
+ }
59
+
60
+ // --------------------------------------------------------------
61
+ // 3. RETURN BASE64
62
+ // --------------------------------------------------------------
63
+ const buffer : any = await workbook.xlsx.writeBuffer();
64
+ return `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,${buffer.toString('base64')}`;
65
+ }