gemcap-be-common 1.2.91 → 1.2.93

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.
Files changed (33) hide show
  1. package/db/collaterals.db.d.ts +12 -1
  2. package/db/collaterals.db.js +101 -1
  3. package/db/collaterals.db.ts +110 -5
  4. package/db/groups.db.d.ts +45 -0
  5. package/db/groups.db.js +22 -0
  6. package/db/groups.db.ts +20 -0
  7. package/models/CustomerGroup.model.d.ts +29 -0
  8. package/models/CustomerGroup.model.js +25 -0
  9. package/models/CustomerGroup.model.ts +31 -0
  10. package/models/QueryResult.model.d.ts +3 -0
  11. package/models/QueryResult.model.js +18 -4
  12. package/models/QueryResult.model.ts +19 -4
  13. package/package.json +1 -1
  14. package/queries/inventory/extension.js +2 -2
  15. package/queries/inventory/extension.ts +1 -1
  16. package/queries/inventory/inconsistent-data.js +2 -2
  17. package/queries/inventory/inconsistent-data.ts +1 -1
  18. package/queries/inventory/movement.js +2 -2
  19. package/queries/inventory/movement.ts +1 -1
  20. package/queries/inventory/turn.js +2 -2
  21. package/queries/inventory/turn.ts +1 -1
  22. package/queries/inventory/unit-cost-difference.js +2 -2
  23. package/queries/inventory/unit-cost-difference.ts +1 -1
  24. package/queries/receivable/ar-turn.d.ts +3 -0
  25. package/queries/receivable/ar-turn.js +117 -0
  26. package/queries/receivable/ar-turn.ts +120 -0
  27. package/queries/receivable/grouped-receivables.d.ts +5 -0
  28. package/queries/receivable/grouped-receivables.js +76 -0
  29. package/queries/receivable/grouped-receivables.ts +85 -0
  30. package/tsconfig.tsbuildinfo +1 -1
  31. /package/db/{inventories.d.ts → inventories.db.d.ts} +0 -0
  32. /package/db/{inventories.js → inventories.db.js} +0 -0
  33. /package/db/{inventories.ts → inventories.db.ts} +0 -0
@@ -4,7 +4,7 @@ exports.getUnitCostDifferenceHeader = exports.getInvoiceMovement = exports.getIn
4
4
  const excel_helper_1 = require("../../helpers/excel.helper");
5
5
  const BBCDate_model_1 = require("../../models/BBCDate.model");
6
6
  const collaterals_db_1 = require("../../db/collaterals.db");
7
- const inventories_1 = require("../../db/inventories");
7
+ const inventories_db_1 = require("../../db/inventories.db");
8
8
  const collaterals_enum_1 = require("../../enums/collaterals.enum");
9
9
  const getInvoiceMovementFull = async (params) => {
10
10
  const { reportAdditions, reportRemoved } = await (0, exports.getInvoiceMovement)(params);
@@ -21,7 +21,7 @@ const getInvoiceMovement = async (params) => {
21
21
  if (currentBbcDate) {
22
22
  const previousDocuments = await (0, collaterals_db_1.getPreviousCollateralDocument)(currentBbcDate.borrowerId.toString(), currentBbcDate.bbcDate, collaterals_enum_1.ECollaterals.INVENTORY, 1);
23
23
  if (previousDocuments.length > 0) {
24
- return (0, inventories_1.getInventoryMovement)(borrowerId.toString(), previousDocuments[0].bbcDate.toString(), currentBbcDate.bbcDate.toString());
24
+ return (0, inventories_db_1.getInventoryMovement)(borrowerId.toString(), previousDocuments[0].bbcDate.toString(), currentBbcDate.bbcDate.toString());
25
25
  }
26
26
  }
27
27
  return { reportAdditions: [], reportRemoved: [] };
@@ -2,7 +2,7 @@ import { TQueryParams } from '../../models/QueryResult.model';
2
2
  import { addHeaderToData } from '../../helpers/excel.helper';
3
3
  import { BBCDateModel } from '../../models/BBCDate.model';
4
4
  import { getPreviousCollateralDocument } from '../../db/collaterals.db';
5
- import { getInventoryMovement } from '../../db/inventories';
5
+ import { getInventoryMovement } from '../../db/inventories.db';
6
6
  import { ECollaterals } from '../../enums/collaterals.enum';
7
7
 
8
8
  export const getInvoiceMovementFull = async (params: TQueryParams) => {
@@ -10,8 +10,8 @@ const bbcDates_db_1 = require("../../db/bbcDates.db");
10
10
  const bbcSheets_db_1 = require("../../db/bbcSheets.db");
11
11
  const collaterals_enum_1 = require("../../enums/collaterals.enum");
12
12
  const collaterals_db_1 = require("../../db/collaterals.db");
13
- const inventories_1 = require("../../db/inventories");
14
13
  const excel_helper_1 = require("../../helpers/excel.helper");
14
+ const inventories_db_1 = require("../../db/inventories.db");
15
15
  const getInventoryTurnFull = async (params) => {
16
16
  const { tableByUnit, tableByValue } = await (0, exports.getInventoryTurn)(params);
17
17
  const headerByUnit = getInventoryTurnHeader('byUnit');
@@ -26,7 +26,7 @@ const getInventoryTurn = async (params) => {
26
26
  const bbcDates = await (0, bbcDates_db_1.getBBCDatesForPeriod)(borrowerId.toString(), new Date(startDate), new Date(endDate));
27
27
  const bbcIds = bbcDates.map((bbc) => bbc._id.toString());
28
28
  const bbcSheets = await (0, bbcSheets_db_1.getBBCSheetsByType)(bbcIds, collaterals_enum_1.ECollaterals.INVENTORY);
29
- const skuGroup = (await (0, inventories_1.getAllUniqSKUInRangeNew)(bbcSheets.map((bbcSheet) => bbcSheet._id.toString()))).pop();
29
+ const skuGroup = (await (0, inventories_db_1.getAllUniqSKUInRangeNew)(bbcSheets.map((bbcSheet) => bbcSheet._id.toString()))).pop();
30
30
  const BBCs = await (0, collaterals_db_1.getCollateralDocsByBBC)(bbcIds, collaterals_enum_1.ECollaterals.INVENTORY);
31
31
  return getDifference(skuGroup ? skuGroup.skus.sort() : [], BBCs);
32
32
  };
@@ -5,11 +5,11 @@ import { getBBCDatesForPeriod } from '../../db/bbcDates.db';
5
5
  import { getBBCSheetsByType } from '../../db/bbcSheets.db';
6
6
  import { ECollaterals } from '../../enums/collaterals.enum';
7
7
  import { getCollateralDocsByBBC } from '../../db/collaterals.db';
8
- import { getAllUniqSKUInRangeNew } from '../../db/inventories';
9
8
  import { IInventoryItem } from '../../models/InventoryItem.model';
10
9
  import { IBBCDateDoc } from '../../models/BBCDate.model';
11
10
  import { TQueryParams } from '../../models/QueryResult.model';
12
11
  import { addHeaderToData } from '../../helpers/excel.helper';
12
+ import { getAllUniqSKUInRangeNew } from '../../db/inventories.db';
13
13
 
14
14
  interface IGroupedCollaterals extends IBBCDateDoc {
15
15
  items: IInventoryItem[];
@@ -8,8 +8,8 @@ const mongoose_1 = __importDefault(require("mongoose"));
8
8
  const decimal_js_1 = __importDefault(require("decimal.js"));
9
9
  const collaterals_db_1 = require("../../db/collaterals.db");
10
10
  const collaterals_enum_1 = require("../../enums/collaterals.enum");
11
- const inventories_1 = require("../../db/inventories");
12
11
  const excel_helper_1 = require("../../helpers/excel.helper");
12
+ const inventories_db_1 = require("../../db/inventories.db");
13
13
  const getUnitCostDifferenceFull = async (params) => {
14
14
  const data = await (0, exports.getUnitCostDifference)(params);
15
15
  const header = getUnitCostDifferenceHeader();
@@ -20,7 +20,7 @@ const getUnitCostDifference = async (params) => {
20
20
  const { borrowerId } = params;
21
21
  const bbcGroups = await (0, collaterals_db_1.findCollateralsWithSheets)(borrowerId.toString(), [collaterals_enum_1.ECollaterals.INVENTORY]);
22
22
  const sheetIds = bbcGroups.reduce((acc, bbcGroup) => [...acc, ...bbcGroup.sheets.map((sheet) => new mongoose_1.default.Types.ObjectId(sheet._id))], []);
23
- const data = await (0, inventories_1.getSKUUnitCostForAllDates)(sheetIds);
23
+ const data = await (0, inventories_db_1.getSKUUnitCostForAllDates)(sheetIds);
24
24
  const mappedData = data.map((i) => {
25
25
  const difference = new decimal_js_1.default(i.currentCost).sub(i.minCost.minCost).toDP(4).toNumber();
26
26
  return {
@@ -3,9 +3,9 @@ import Decimal from 'decimal.js';
3
3
 
4
4
  import { findCollateralsWithSheets } from '../../db/collaterals.db';
5
5
  import { ECollaterals } from '../../enums/collaterals.enum';
6
- import { getSKUUnitCostForAllDates } from '../../db/inventories';
7
6
  import { TQueryParams } from '../../models/QueryResult.model';
8
7
  import { addHeaderToData } from '../../helpers/excel.helper';
8
+ import { getSKUUnitCostForAllDates } from '../../db/inventories.db';
9
9
 
10
10
  export const getUnitCostDifferenceFull = async (params: TQueryParams) => {
11
11
  const data = await getUnitCostDifference(params);
@@ -0,0 +1,3 @@
1
+ import { TQueryParams } from '../../models/QueryResult.model';
2
+ export declare const getARTurnFull: (params: TQueryParams) => Promise<{}[]>;
3
+ export declare const getARTurn: (params: TQueryParams) => Promise<any[]>;
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getARTurn = exports.getARTurnFull = void 0;
7
+ const decimal_js_1 = __importDefault(require("decimal.js"));
8
+ const dayjs_1 = __importDefault(require("dayjs"));
9
+ const BBCDate_model_1 = require("../../models/BBCDate.model");
10
+ const bbcSheets_db_1 = require("../../db/bbcSheets.db");
11
+ const collaterals_enum_1 = require("../../enums/collaterals.enum");
12
+ const receivables_db_1 = require("../../db/receivables.db");
13
+ const collaterals_db_1 = require("../../db/collaterals.db");
14
+ const excel_helper_1 = require("../../helpers/excel.helper");
15
+ const ReceivableItem_model_1 = require("../../models/ReceivableItem.model");
16
+ const getARTurnFull = async (params) => {
17
+ const data = await (0, exports.getARTurn)(params);
18
+ const header = getARTurnHeader();
19
+ return (0, excel_helper_1.addHeaderToData)(header, data);
20
+ };
21
+ exports.getARTurnFull = getARTurnFull;
22
+ const getInvoices = async (bbcSheetIds) => {
23
+ return ReceivableItem_model_1.ReceivableItemModel.aggregate([
24
+ {
25
+ $match: {
26
+ $and: [
27
+ { 'bbcSheetId': { $in: bbcSheetIds } },
28
+ ],
29
+ },
30
+ },
31
+ ...collaterals_db_1.COLLATERALS_LOOKUP,
32
+ ]);
33
+ };
34
+ const getARTurn = async (params) => {
35
+ const { borrowerId, bbcDateId, extraParams } = params;
36
+ const { daysFilter } = extraParams;
37
+ const currentBbcDate = await BBCDate_model_1.BBCDateModel.findById(bbcDateId).lean();
38
+ if (!currentBbcDate) {
39
+ return [];
40
+ }
41
+ const rangeStart = (0, dayjs_1.default)(new Date(currentBbcDate.bbcDate)).subtract(daysFilter, 'day').toDate();
42
+ const rangeEnd = new Date(currentBbcDate.bbcDate);
43
+ const allInventoryBbcDates = await (0, bbcSheets_db_1.getUniqueDatesForPeriod)(borrowerId.toString(), collaterals_enum_1.ECollaterals.RECEIVABLE, new Date(rangeStart), new Date(rangeEnd));
44
+ const sheetIds = allInventoryBbcDates.reduce((acc, bbc) => [...acc, ...bbc.ids], []);
45
+ const uniqInvoices = (await (0, receivables_db_1.getUniqInvoices)(sheetIds)).pop();
46
+ if (!uniqInvoices) {
47
+ return [];
48
+ }
49
+ const bbcIds = allInventoryBbcDates.map((bbc) => bbc._id.toString());
50
+ const allInvoicesNew = await (0, collaterals_db_1.getCollateralDocsByBBC)(bbcIds, collaterals_enum_1.ECollaterals.RECEIVABLE);
51
+ const mappedUniqInvoices = uniqInvoices.uniqueValues.map((value) => {
52
+ const [customerTitle, invoiceNumber] = value.split(receivables_db_1.CUSTOMER_NUMBER_SEPARATOR);
53
+ return { customerTitle, invoiceNumber };
54
+ });
55
+ const lastInvoiceNew = allInvoicesNew[allInvoicesNew.length - 1];
56
+ if (!lastInvoiceNew) {
57
+ return [];
58
+ }
59
+ const workedInvoice = [];
60
+ mappedUniqInvoices.forEach((uniqInvoice) => {
61
+ const foundInvoice = lastInvoiceNew.items
62
+ .find((invoice) => invoice.customerTitle === uniqInvoice.customerTitle && invoice.invoiceNumber === uniqInvoice.invoiceNumber);
63
+ if (!foundInvoice) {
64
+ workedInvoice.push(uniqInvoice);
65
+ }
66
+ });
67
+ workedInvoice.sort((invoice1, invoice2) => invoice1.invoiceNumber - invoice2.invoiceNumber);
68
+ const lastInvoices = [];
69
+ const allInvoices = await getInvoices(sheetIds);
70
+ workedInvoice.forEach((invoice) => {
71
+ const testFirstInvoices = allInvoices
72
+ .filter((i) => i.customerTitle === invoice.customerTitle && i.invoiceNumber === invoice.invoiceNumber)
73
+ .sort((invoice1, invoice2) => new Date(invoice1.bbcDate).valueOf() - new Date(invoice2.bbcDate).valueOf());
74
+ const firstInvoice = testFirstInvoices.length > 0 ? testFirstInvoices[0] : null;
75
+ const lastInvoice = testFirstInvoices.length > 0 ? testFirstInvoices[testFirstInvoices.length - 1] : null;
76
+ const lastIndex = allInventoryBbcDates.findIndex((i) => i._id.toString() === lastInvoice.bbc._id.toString());
77
+ const dateRemoved = new Date(allInventoryBbcDates[lastIndex + 1].bbcDate);
78
+ const numberOfDays = (0, dayjs_1.default)(dateRemoved).diff((0, dayjs_1.default)(new Date(firstInvoice.invoiceDate)), 'day');
79
+ lastInvoices.push({
80
+ invoiceNumber: firstInvoice.invoiceNumber,
81
+ dateIssued: firstInvoice.invoiceDate,
82
+ dateRemoved,
83
+ numberOfDays,
84
+ valueRemoved: firstInvoice.invoiceAmount,
85
+ customer: firstInvoice.customerTitle,
86
+ totalValue: numberOfDays * firstInvoice.invoiceAmount,
87
+ });
88
+ });
89
+ const groupedInvoices = lastInvoices.reduce((acc, invoice) => {
90
+ acc[invoice.customer] = acc[invoice.customer] || [];
91
+ acc[invoice.customer].push(invoice);
92
+ return acc;
93
+ }, {});
94
+ return Object.entries(groupedInvoices).reduce((acc, [customer, invoices]) => {
95
+ const invoiceTotalDays = invoices.reduce((totalAverage, invoice) => new decimal_js_1.default(totalAverage).add(invoice.numberOfDays).toNumber(), 0);
96
+ const averageNumberDays = new decimal_js_1.default(invoiceTotalDays).div(invoices.length).toDP(2).toNumber();
97
+ const invoiceTotalValue = invoices.reduce((totalAverage, invoice) => new decimal_js_1.default(totalAverage).add(invoice.totalValue).toNumber(), 0);
98
+ const invoiceTotalRemoved = invoices.reduce((totalAverage, invoice) => new decimal_js_1.default(totalAverage).add(invoice.valueRemoved).toNumber(), 0);
99
+ const weightedAveragedDays = invoiceTotalRemoved === 0
100
+ ? 0
101
+ : new decimal_js_1.default(invoiceTotalValue).div(invoiceTotalRemoved).toDP(2).toNumber();
102
+ const data = {
103
+ customer,
104
+ averageNumberDays,
105
+ weightedAveragedDays,
106
+ };
107
+ return [...acc, data];
108
+ }, []);
109
+ };
110
+ exports.getARTurn = getARTurn;
111
+ const getARTurnHeader = () => {
112
+ return {
113
+ customer: 'Customer',
114
+ averageNumberDays: 'Average Number of Days to clear invoice',
115
+ weightedAveragedDays: 'Weighted Averaged Days (by Value)',
116
+ };
117
+ };
@@ -0,0 +1,120 @@
1
+ import Decimal from 'decimal.js';
2
+ import dayjs from 'dayjs';
3
+ import mongoose from 'mongoose';
4
+
5
+ import { BBCDateModel } from '../../models/BBCDate.model';
6
+ import { getUniqueDatesForPeriod } from '../../db/bbcSheets.db';
7
+ import { ECollaterals } from '../../enums/collaterals.enum';
8
+ import { CUSTOMER_NUMBER_SEPARATOR, getUniqInvoices } from '../../db/receivables.db';
9
+ import { COLLATERALS_LOOKUP, getCollateralDocsByBBC } from '../../db/collaterals.db';
10
+ import { TQueryParams } from '../../models/QueryResult.model';
11
+ import { addHeaderToData } from '../../helpers/excel.helper';
12
+ import { ReceivableItemModel } from '../../models/ReceivableItem.model';
13
+
14
+ export const getARTurnFull = async (params: TQueryParams) => {
15
+ const data = await getARTurn(params);
16
+ const header = getARTurnHeader();
17
+ return addHeaderToData(header, data);
18
+ };
19
+
20
+ const getInvoices = async (bbcSheetIds: mongoose.Types.ObjectId[]) => {
21
+ return ReceivableItemModel.aggregate([
22
+ {
23
+ $match: {
24
+ $and: [
25
+ { 'bbcSheetId': { $in: bbcSheetIds } },
26
+ ],
27
+ },
28
+ },
29
+ ...COLLATERALS_LOOKUP,
30
+ ]);
31
+ };
32
+
33
+ export const getARTurn = async (params: TQueryParams) => {
34
+ const { borrowerId, bbcDateId, extraParams } = params;
35
+ const { daysFilter } = <{ daysFilter: number }>extraParams;
36
+ const currentBbcDate = await BBCDateModel.findById(bbcDateId).lean();
37
+ if (!currentBbcDate) {
38
+ return [];
39
+ }
40
+ const rangeStart = dayjs(new Date(currentBbcDate.bbcDate)).subtract(daysFilter, 'day').toDate();
41
+ const rangeEnd = new Date(currentBbcDate.bbcDate);
42
+ const allInventoryBbcDates = await getUniqueDatesForPeriod(borrowerId.toString(), ECollaterals.RECEIVABLE, new Date(rangeStart), new Date(rangeEnd));
43
+ const sheetIds = allInventoryBbcDates.reduce((acc, bbc) => [...acc, ...bbc.ids], []);
44
+ const uniqInvoices = (await getUniqInvoices(sheetIds)).pop();
45
+ if (!uniqInvoices) {
46
+ return [];
47
+ }
48
+ const bbcIds = allInventoryBbcDates.map((bbc) => bbc._id.toString());
49
+ const allInvoicesNew = await getCollateralDocsByBBC(bbcIds, ECollaterals.RECEIVABLE);
50
+ const mappedUniqInvoices = uniqInvoices.uniqueValues.map((value) => {
51
+ const [customerTitle, invoiceNumber] = value.split(CUSTOMER_NUMBER_SEPARATOR);
52
+ return { customerTitle, invoiceNumber };
53
+ });
54
+ const lastInvoiceNew = allInvoicesNew[allInvoicesNew.length - 1];
55
+ if (!lastInvoiceNew) {
56
+ return [];
57
+ }
58
+ const workedInvoice = [];
59
+ mappedUniqInvoices.forEach((uniqInvoice) => {
60
+ const foundInvoice = lastInvoiceNew.items
61
+ .find((invoice) => invoice.customerTitle === uniqInvoice.customerTitle && invoice.invoiceNumber === uniqInvoice.invoiceNumber);
62
+ if (!foundInvoice) {
63
+ workedInvoice.push(uniqInvoice);
64
+ }
65
+ });
66
+ workedInvoice.sort((invoice1, invoice2) => invoice1.invoiceNumber - invoice2.invoiceNumber);
67
+ const lastInvoices = [];
68
+
69
+ const allInvoices = await getInvoices(sheetIds);
70
+
71
+ workedInvoice.forEach((invoice) => {
72
+ const testFirstInvoices = allInvoices
73
+ .filter((i) => i.customerTitle === invoice.customerTitle && i.invoiceNumber === invoice.invoiceNumber)
74
+ .sort((invoice1, invoice2) => new Date(invoice1.bbcDate).valueOf() - new Date(invoice2.bbcDate).valueOf());
75
+ const firstInvoice = testFirstInvoices.length > 0 ? testFirstInvoices[0] : null;
76
+ const lastInvoice = testFirstInvoices.length > 0 ? testFirstInvoices[testFirstInvoices.length - 1] : null;
77
+ const lastIndex = allInventoryBbcDates.findIndex((i) => i._id.toString() === lastInvoice.bbc._id.toString());
78
+ const dateRemoved = new Date(allInventoryBbcDates[lastIndex + 1].bbcDate);
79
+ const numberOfDays = dayjs(dateRemoved).diff(dayjs(new Date(firstInvoice.invoiceDate)), 'day');
80
+ lastInvoices.push({
81
+ invoiceNumber: firstInvoice.invoiceNumber,
82
+ dateIssued: firstInvoice.invoiceDate,
83
+ dateRemoved,
84
+ numberOfDays,
85
+ valueRemoved: firstInvoice.invoiceAmount,
86
+ customer: firstInvoice.customerTitle,
87
+ totalValue: numberOfDays * firstInvoice.invoiceAmount,
88
+ });
89
+ });
90
+
91
+ const groupedInvoices = lastInvoices.reduce((acc, invoice) => {
92
+ acc[invoice.customer] = acc[invoice.customer] || [];
93
+ acc[invoice.customer].push(invoice);
94
+ return acc;
95
+ }, {});
96
+
97
+ return Object.entries(groupedInvoices).reduce((acc, [customer, invoices]: [string, any[]]) => {
98
+ const invoiceTotalDays = invoices.reduce((totalAverage, invoice) => new Decimal(totalAverage).add(invoice.numberOfDays).toNumber(), 0);
99
+ const averageNumberDays = new Decimal(invoiceTotalDays).div(invoices.length).toDP(2).toNumber();
100
+ const invoiceTotalValue = invoices.reduce((totalAverage, invoice) => new Decimal(totalAverage).add(invoice.totalValue).toNumber(), 0);
101
+ const invoiceTotalRemoved = invoices.reduce((totalAverage, invoice) => new Decimal(totalAverage).add(invoice.valueRemoved).toNumber(), 0);
102
+ const weightedAveragedDays = invoiceTotalRemoved === 0
103
+ ? 0
104
+ : new Decimal(invoiceTotalValue).div(invoiceTotalRemoved).toDP(2).toNumber();
105
+ const data = {
106
+ customer,
107
+ averageNumberDays,
108
+ weightedAveragedDays,
109
+ };
110
+ return [...acc, data];
111
+ }, []);
112
+ };
113
+
114
+ const getARTurnHeader = () => {
115
+ return {
116
+ customer: 'Customer',
117
+ averageNumberDays: 'Average Number of Days to clear invoice',
118
+ weightedAveragedDays: 'Weighted Averaged Days (by Value)',
119
+ };
120
+ };
@@ -0,0 +1,5 @@
1
+ import { TQueryParams } from '../../models/QueryResult.model';
2
+ export declare const getGroupedReceivablesFull: (params: TQueryParams) => Promise<{}[]>;
3
+ export declare const getGroupedReceivables: (params: TQueryParams) => Promise<{
4
+ [x: string]: any[];
5
+ }[]>;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getGroupedReceivables = exports.getGroupedReceivablesFull = void 0;
7
+ const dayjs_1 = __importDefault(require("dayjs"));
8
+ const excel_helper_1 = require("../../helpers/excel.helper");
9
+ const collaterals_db_1 = require("../../db/collaterals.db");
10
+ const collaterals_enum_1 = require("../../enums/collaterals.enum");
11
+ const mongoose_1 = __importDefault(require("mongoose"));
12
+ const column_desciptions_helper_1 = require("../../helpers/column-desciptions.helper");
13
+ const BBCDate_model_1 = require("../../models/BBCDate.model");
14
+ const partially_paid_restated_1 = require("./partially-paid-restated");
15
+ const getGroupedReceivablesFull = async (params) => {
16
+ const data = await (0, exports.getGroupedReceivables)(params);
17
+ const header = getGroupedReceivablesHeader();
18
+ return (0, excel_helper_1.addHeaderToData)(header, data);
19
+ };
20
+ exports.getGroupedReceivablesFull = getGroupedReceivablesFull;
21
+ const getGroupedReceivables = async (params) => {
22
+ const { borrowerId, bbcDateId, extraParams } = params;
23
+ console.log(extraParams.someParam);
24
+ const { calculateDueDate } = extraParams;
25
+ const sheets = await (0, collaterals_db_1.findCollateralSheets)(bbcDateId.toString(), collaterals_enum_1.ECollaterals.RECEIVABLE);
26
+ return await Promise.all(sheets.map(async (sheet) => {
27
+ const data = await (0, collaterals_db_1.findCollaterals)(sheet._id.toString(), false);
28
+ const customerTitleIndex = column_desciptions_helper_1.COLLATERALS[collaterals_enum_1.ECollaterals.RECEIVABLE].findIndex((column) => column.db_title === 'customerTitle');
29
+ const columnsShort = column_desciptions_helper_1.COLLATERALS[collaterals_enum_1.ECollaterals.RECEIVABLE]
30
+ .map((c) => ({ db_title: c.db_title, title: c.title }))
31
+ .filter((c) => c.db_title !== 'bbcDate');
32
+ columnsShort.splice(customerTitleIndex, 0, { db_title: 'customerGroup', title: 'Customer group' });
33
+ columnsShort.push({ db_title: 'partiallyPaid', title: 'Partially paid' });
34
+ const columnDB = columnsShort.map((c) => c.db_title);
35
+ const bbcDate = await BBCDate_model_1.BBCDateModel.findById(bbcDateId).lean();
36
+ const startDate = (0, dayjs_1.default)(new Date(bbcDate.bbcDate)).subtract(180, 'day').toDate();
37
+ const endDate = new Date(bbcDate.bbcDate);
38
+ const { partiallyPaidInvoices } = await (0, partially_paid_restated_1.getPartialPaid)({ borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId), startDate, endDate });
39
+ const dataWithPartiallyPaid = data.map((invoice) => {
40
+ let partiallyPaid = false;
41
+ const foundInvoice = partiallyPaidInvoices.find((pInvoice) => {
42
+ return (pInvoice.invoiceNumber === invoice.invoiceNumber) && (pInvoice.customer === invoice.customerTitle);
43
+ });
44
+ if (foundInvoice) {
45
+ partiallyPaid = foundInvoice.difference > 0;
46
+ }
47
+ if ((invoice.originalAmount !== 0) && (invoice.originalAmount !== invoice.invoiceAmount)) {
48
+ partiallyPaid = true;
49
+ }
50
+ return {
51
+ ...invoice,
52
+ partiallyPaid,
53
+ dueDate: calculateDueDate ? (0, dayjs_1.default)(invoice.invoiceDate).utcOffset(0).add(90, 'days').toDate() : invoice.dueDate,
54
+ };
55
+ });
56
+ const shortData = (0, collaterals_db_1.excludeNoDataColumns)(dataWithPartiallyPaid, columnDB);
57
+ const dataWithGroups = await (0, collaterals_db_1.addCustomerGroups)(shortData, borrowerId.toString());
58
+ return { [sheet.sheetName]: dataWithGroups };
59
+ }));
60
+ };
61
+ exports.getGroupedReceivables = getGroupedReceivables;
62
+ const getGroupedReceivablesHeader = () => {
63
+ return {
64
+ sheetName: 'Sheet name',
65
+ invoiceNumber: 'Invoice number',
66
+ invoiceDate: 'Invoice date',
67
+ customerTitle: 'Customer title',
68
+ customerGroup: 'Customer group',
69
+ invoiceAmount: 'Invoice amount',
70
+ dueDate: 'Due date',
71
+ invoiceDetail1: 'Invoice detail 1',
72
+ invoiceDetail2: 'Invoice detail 2',
73
+ invoiceDetail3: 'Invoice detail 3',
74
+ partiallyPaid: 'Partially paid',
75
+ };
76
+ };
@@ -0,0 +1,85 @@
1
+ import dayjs from 'dayjs';
2
+
3
+ import { TQueryParams } from '../../models/QueryResult.model';
4
+ import { addHeaderToData } from '../../helpers/excel.helper';
5
+ import {
6
+ addCustomerGroups,
7
+ excludeNoDataColumns,
8
+ findCollaterals,
9
+ findCollateralSheets,
10
+ } from '../../db/collaterals.db';
11
+ import { ECollaterals } from '../../enums/collaterals.enum';
12
+ import mongoose from 'mongoose';
13
+ import { COLLATERALS } from '../../helpers/column-desciptions.helper';
14
+ import { BBCDateModel } from '../../models/BBCDate.model';
15
+ import { getPartialPaid } from './partially-paid-restated';
16
+
17
+ export const getGroupedReceivablesFull = async (params: TQueryParams) => {
18
+ const data = await getGroupedReceivables(params);
19
+ const header = getGroupedReceivablesHeader();
20
+ return addHeaderToData(header, data);
21
+ };
22
+
23
+ export const getGroupedReceivables = async (params: TQueryParams) => {
24
+ const { borrowerId, bbcDateId, extraParams } = params;
25
+ console.log(extraParams.someParam);
26
+ const { calculateDueDate } = <{ calculateDueDate: boolean }>extraParams;
27
+ const sheets = await findCollateralSheets(bbcDateId.toString(), ECollaterals.RECEIVABLE);
28
+
29
+ return await Promise.all(sheets.map(async (sheet) => {
30
+ const data: any[] = await findCollaterals(sheet._id.toString(), false);
31
+ const customerTitleIndex = COLLATERALS[ECollaterals.RECEIVABLE].findIndex((column) => column.db_title === 'customerTitle');
32
+
33
+ const columnsShort = COLLATERALS[ECollaterals.RECEIVABLE]
34
+ .map((c) => ({ db_title: c.db_title, title: c.title }))
35
+ .filter((c) => c.db_title !== 'bbcDate');
36
+ columnsShort.splice(customerTitleIndex, 0, { db_title: 'customerGroup', title: 'Customer group' });
37
+ columnsShort.push({ db_title: 'partiallyPaid', title: 'Partially paid' });
38
+
39
+ const columnDB = columnsShort.map((c) => c.db_title);
40
+
41
+ const bbcDate = await BBCDateModel.findById(bbcDateId).lean();
42
+ const startDate = dayjs(new Date(bbcDate.bbcDate)).subtract(180, 'day').toDate();
43
+ const endDate = new Date(bbcDate.bbcDate);
44
+
45
+ const { partiallyPaidInvoices } = await getPartialPaid({ borrowerId: new mongoose.Types.ObjectId(borrowerId), startDate, endDate });
46
+
47
+ const dataWithPartiallyPaid = data.map((invoice) => {
48
+ let partiallyPaid = false;
49
+ const foundInvoice = partiallyPaidInvoices.find((pInvoice) => {
50
+ return (pInvoice.invoiceNumber === invoice.invoiceNumber) && (pInvoice.customer === invoice.customerTitle);
51
+ });
52
+ if (foundInvoice) {
53
+ partiallyPaid = foundInvoice.difference > 0;
54
+ }
55
+ if ((invoice.originalAmount !== 0) && (invoice.originalAmount !== invoice.invoiceAmount)) {
56
+ partiallyPaid = true;
57
+ }
58
+ return {
59
+ ...invoice,
60
+ partiallyPaid,
61
+ dueDate: calculateDueDate ? dayjs(invoice.invoiceDate).utcOffset(0).add(90, 'days').toDate() : invoice.dueDate,
62
+ };
63
+ });
64
+
65
+ const shortData = excludeNoDataColumns(dataWithPartiallyPaid, columnDB);
66
+ const dataWithGroups = await addCustomerGroups(shortData, borrowerId.toString());
67
+ return { [sheet.sheetName]: dataWithGroups };
68
+ }));
69
+ };
70
+
71
+ const getGroupedReceivablesHeader = () => {
72
+ return {
73
+ sheetName: 'Sheet name',
74
+ invoiceNumber: 'Invoice number',
75
+ invoiceDate: 'Invoice date',
76
+ customerTitle: 'Customer title',
77
+ customerGroup: 'Customer group',
78
+ invoiceAmount: 'Invoice amount',
79
+ dueDate: 'Due date',
80
+ invoiceDetail1: 'Invoice detail 1',
81
+ invoiceDetail2: 'Invoice detail 2',
82
+ invoiceDetail3: 'Invoice detail 3',
83
+ partiallyPaid: 'Partially paid',
84
+ };
85
+ };