erpnext-queue-client 2.4.3 → 2.4.4

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 (39) hide show
  1. package/dist/client.js +87 -105
  2. package/dist/constants.js +1 -0
  3. package/dist/dataConverter.js +4 -13
  4. package/dist/erpnext/decryptFromErpNext.server.js +1 -1
  5. package/dist/erpnext/decryptFromErpNext.server.test.js +2 -11
  6. package/dist/erpnext/doctypeResourceRequest.js +44 -37
  7. package/dist/erpnext/doctypeSubmittableResourceRequest.js +19 -33
  8. package/dist/erpnext/doctypes/address.js +40 -41
  9. package/dist/erpnext/doctypes/consolidatedCustomsInvoice.js +18 -20
  10. package/dist/erpnext/doctypes/contact.js +30 -30
  11. package/dist/erpnext/doctypes/deliveryNote.js +13 -12
  12. package/dist/erpnext/doctypes/item.d.ts +10 -10
  13. package/dist/erpnext/doctypes/item.js +64 -63
  14. package/dist/erpnext/doctypes/paymentEntry.js +42 -43
  15. package/dist/erpnext/doctypes/productBundle.js +15 -17
  16. package/dist/erpnext/doctypes/purchaseInvoice.js +45 -49
  17. package/dist/erpnext/doctypes/purchaseReceipt.js +41 -43
  18. package/dist/erpnext/doctypes/salesInvoice.js +42 -43
  19. package/dist/erpnext/doctypes/servicecase.js +103 -114
  20. package/dist/erpnext/doctypes/shipment.js +30 -35
  21. package/dist/erpnext/doctypes/stock.js +94 -109
  22. package/dist/erpnext/doctypes/tags.js +58 -77
  23. package/dist/erpnext/erpnextRequestWrapper.js +83 -80
  24. package/dist/erpnext/fileRequests.js +28 -29
  25. package/dist/erpnext/methodRequest.js +37 -43
  26. package/dist/erpnext/model/DocTypeHelpers.js +2 -3
  27. package/dist/erpnext/model/Item.d.ts +6 -6
  28. package/dist/erpnext/model/Item.js +1 -1
  29. package/dist/erpnext/model/StockEntry.d.ts +63 -21
  30. package/dist/erpnext/model/StockEntry.js +22 -21
  31. package/dist/erpnext/reports.js +81 -89
  32. package/dist/erpnext/resourceRequest.js +142 -150
  33. package/dist/index.js +43 -3
  34. package/dist/index.test.js +69 -83
  35. package/dist/utils/fernet.server.js +24 -4
  36. package/dist/utils/request.js +59 -72
  37. package/dist/utils/zodContextOptionals.js +5 -3
  38. package/dist/utils/zodUtils.js +2 -2
  39. package/package.json +1 -1
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StockEntry = void 0;
4
4
  // convert from types to zod schema
5
5
  const zod_1 = require("zod");
6
+ const zodContextOptionals_1 = require("../../utils/zodContextOptionals");
6
7
  const StockEntryItem = zod_1.z
7
8
  .object({
8
9
  t_warehouse: zod_1.z.string().optional(),
@@ -16,27 +17,27 @@ const StockEntryItem = zod_1.z
16
17
  exports.StockEntry = zod_1.z
17
18
  .object({
18
19
  external_name: zod_1.z.string().optional(),
19
- naming_series: zod_1.z.string(),
20
+ naming_series: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
20
21
  stock_entry_type: zod_1.z.string(),
21
22
  outgoing_stock_entry: zod_1.z.string().optional(),
22
- purpose: zod_1.z.string(),
23
- add_to_transit: zod_1.z.number(),
23
+ purpose: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
24
+ add_to_transit: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
24
25
  work_order: zod_1.z.string().optional(),
25
26
  purchase_order: zod_1.z.string().optional(),
26
27
  delivery_note_no: zod_1.z.string().optional(),
27
28
  sales_invoice_no: zod_1.z.string().optional(),
28
29
  pick_list: zod_1.z.string().optional(),
29
30
  purchase_receipt_no: zod_1.z.string().optional(),
30
- company: zod_1.z.string(),
31
- posting_date: zod_1.z.string(),
32
- posting_time: zod_1.z.string(),
33
- set_posting_time: zod_1.z.number(),
34
- inspection_required: zod_1.z.number(),
35
- from_bom: zod_1.z.number(),
36
- apply_putaway_rule: zod_1.z.number(),
31
+ company: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
32
+ posting_date: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
33
+ posting_time: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
34
+ set_posting_time: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
35
+ inspection_required: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
36
+ from_bom: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
37
+ apply_putaway_rule: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
37
38
  bom_no: zod_1.z.string().optional(),
38
- fg_completed_qty: zod_1.z.number(),
39
- use_multi_level_bom: zod_1.z.number(),
39
+ fg_completed_qty: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
40
+ use_multi_level_bom: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
40
41
  from_warehouse: zod_1.z.string().optional(),
41
42
  source_warehouse_address: zod_1.z.string().optional(),
42
43
  source_address_display: zod_1.z.string().optional(),
@@ -44,10 +45,10 @@ exports.StockEntry = zod_1.z
44
45
  target_warehouse_address: zod_1.z.string().optional(),
45
46
  target_address_display: zod_1.z.string().optional(),
46
47
  scan_barcode: zod_1.z.string().optional(),
47
- total_outgoing_value: zod_1.z.number(),
48
- total_incoming_value: zod_1.z.number(),
49
- value_difference: zod_1.z.number(),
50
- total_additional_costs: zod_1.z.number(),
48
+ total_outgoing_value: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
49
+ total_incoming_value: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
50
+ value_difference: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
51
+ total_additional_costs: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
51
52
  supplier: zod_1.z.string().optional(),
52
53
  supplier_name: zod_1.z.string().optional(),
53
54
  supplier_address: zod_1.z.string().optional(),
@@ -55,15 +56,15 @@ exports.StockEntry = zod_1.z
55
56
  project: zod_1.z.string().optional(),
56
57
  select_print_heading: zod_1.z.string().optional(),
57
58
  letter_head: zod_1.z.string().optional(),
58
- is_opening: zod_1.z.string(),
59
+ is_opening: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.string()),
59
60
  remarks: zod_1.z.string().optional(),
60
- per_transferred: zod_1.z.number(),
61
- total_amount: zod_1.z.number(),
61
+ per_transferred: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
62
+ total_amount: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
62
63
  job_card: zod_1.z.string().optional(),
63
64
  amended_from: zod_1.z.string().optional(),
64
65
  credit_note: zod_1.z.string().optional(),
65
- is_return: zod_1.z.number(),
66
+ is_return: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.number()),
66
67
  items: zod_1.z.array(StockEntryItem),
67
- additional_costs: zod_1.z.array(zod_1.z.string()),
68
+ additional_costs: (0, zodContextOptionals_1.optionalForInput)(zod_1.z.array(zod_1.z.string())),
68
69
  })
69
70
  .describe("Stock Entry");
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.ERPNextReports = void 0;
13
4
  const zod_1 = require("zod");
@@ -17,98 +8,99 @@ const lodash_1 = require("lodash");
17
8
  const utils_1 = require("../utils/utils");
18
9
  const resourceRequest_1 = require("./resourceRequest");
19
10
  class ERPNextReports extends methodRequest_1.ERPNextMethodRequest {
11
+ resourceRequest;
20
12
  constructor(temporalClient) {
21
13
  super(temporalClient);
22
14
  this.resourceRequest = new resourceRequest_1.ERPNextResourceRequest(temporalClient);
23
15
  }
24
- enqueueReport(reportName, body) {
25
- return __awaiter(this, void 0, void 0, function* () {
26
- const result = yield this.request({
27
- methodName: "frappe.core.doctype.prepared_report.prepared_report.make_prepared_report",
28
- requestMethod: "POST",
29
- body: Object.assign({ report_name: reportName }, body),
30
- responseValidationModel: Report_1.EnqueueReportResponse,
31
- });
32
- return result;
16
+ async enqueueReport(reportName, body) {
17
+ const result = await this.request({
18
+ methodName: "frappe.core.doctype.prepared_report.prepared_report.make_prepared_report",
19
+ requestMethod: "POST",
20
+ body: {
21
+ report_name: reportName,
22
+ ...body,
23
+ },
24
+ responseValidationModel: Report_1.EnqueueReportResponse,
33
25
  });
26
+ return result;
34
27
  }
35
- isPreparedReport(reportName) {
36
- return __awaiter(this, void 0, void 0, function* () {
37
- const result = yield this.resourceRequest.getList({
38
- resourceName: "Report",
39
- fields: ["prepared_report"],
40
- filters: [["name", "=", reportName]],
41
- limit: 1,
42
- resourceModel: Report_1.PendingPreparedReport,
43
- });
44
- if (!result[0])
45
- throw new Error(`Report ${reportName} not found`);
46
- return result[0].prepared_report;
28
+ async isPreparedReport(reportName) {
29
+ const result = await this.resourceRequest.getList({
30
+ resourceName: "Report",
31
+ fields: ["prepared_report"],
32
+ filters: [["name", "=", reportName]],
33
+ limit: 1,
34
+ resourceModel: Report_1.PendingPreparedReport,
47
35
  });
36
+ if (!result[0])
37
+ throw new Error(`Report ${reportName} not found`);
38
+ return result[0].prepared_report;
48
39
  }
49
- getReport(reportName, body, reportRowModel) {
50
- return __awaiter(this, void 0, void 0, function* () {
51
- if (yield this.isPreparedReport(reportName)) {
52
- return this.enqueueAndGetReport(reportName, body, reportRowModel);
53
- }
54
- else {
55
- const responseValidationModel = (0, Report_1.Report)(reportRowModel !== null && reportRowModel !== void 0 ? reportRowModel : zod_1.z.any());
56
- const reportResponse = yield this.request({
57
- methodName: `frappe.desk.query_report.run`,
58
- body: Object.assign({ report_name: reportName }, body),
59
- requestMethod: "POST",
60
- responseValidationModel,
61
- });
62
- return reportResponse === null || reportResponse === void 0 ? void 0 : reportResponse.result.filter((r) => !(0, lodash_1.isArray)(r));
63
- }
64
- });
40
+ async getReport(reportName, body, reportRowModel) {
41
+ if (await this.isPreparedReport(reportName)) {
42
+ return this.enqueueAndGetReport(reportName, body, reportRowModel);
43
+ }
44
+ else {
45
+ const responseValidationModel = (0, Report_1.Report)(reportRowModel ?? zod_1.z.any());
46
+ const reportResponse = await this.request({
47
+ methodName: `frappe.desk.query_report.run`,
48
+ body: {
49
+ report_name: reportName,
50
+ ...body,
51
+ },
52
+ requestMethod: "POST",
53
+ responseValidationModel,
54
+ });
55
+ return reportResponse?.result.filter((r) => !(0, lodash_1.isArray)(r));
56
+ }
65
57
  }
66
- getEnqueuedReport(reportName, body, enqueuedReportName, reportRowModel) {
67
- return __awaiter(this, void 0, void 0, function* () {
68
- var _a;
69
- for (let i = 0; i < 100; i++) {
70
- const responseValidationModel = (0, Report_1.Report)(reportRowModel !== null && reportRowModel !== void 0 ? reportRowModel : zod_1.z.any());
71
- const reportResponse = yield this.request({
72
- methodName: `frappe.desk.query_report.run`,
73
- body: Object.assign({ report_name: reportName }, body),
74
- requestMethod: "POST",
75
- responseValidationModel: zod_1.z.any().describe("Any"),
76
- });
77
- // Casting to correct type since Typescript is not able to infer the type correctly.
78
- // Type safety is ensured by zod
79
- if ((reportResponse === null || reportResponse === void 0 ? void 0 : reportResponse.result) &&
80
- ((_a = reportResponse === null || reportResponse === void 0 ? void 0 : reportResponse.doc) === null || _a === void 0 ? void 0 : _a.name) === enqueuedReportName) {
81
- const validatedReponse = responseValidationModel.parse(reportResponse);
82
- return validatedReponse.result.filter((r) => !(0, lodash_1.isArray)(r));
83
- }
84
- yield (0, utils_1.timeout)(1000);
58
+ async getEnqueuedReport(reportName, body, enqueuedReportName, reportRowModel) {
59
+ for (let i = 0; i < 100; i++) {
60
+ const responseValidationModel = (0, Report_1.Report)(reportRowModel ?? zod_1.z.any());
61
+ const reportResponse = await this.request({
62
+ methodName: `frappe.desk.query_report.run`,
63
+ body: {
64
+ report_name: reportName,
65
+ ...body,
66
+ },
67
+ requestMethod: "POST",
68
+ responseValidationModel: zod_1.z.any().describe("Any"),
69
+ });
70
+ // Casting to correct type since Typescript is not able to infer the type correctly.
71
+ // Type safety is ensured by zod
72
+ if (reportResponse?.result &&
73
+ reportResponse?.doc?.name === enqueuedReportName) {
74
+ const validatedReponse = responseValidationModel.parse(reportResponse);
75
+ return validatedReponse.result.filter((r) => !(0, lodash_1.isArray)(r));
85
76
  }
86
- throw new Error(`Failed to get report ${reportName} with body ${JSON.stringify(body)}`);
87
- });
77
+ await (0, utils_1.timeout)(1000);
78
+ }
79
+ throw new Error(`Failed to get report ${reportName} with body ${JSON.stringify(body)}`);
88
80
  }
89
- enqueueAndGetReport(reportName, body, reportRowModel) {
90
- return __awaiter(this, void 0, void 0, function* () {
91
- var _a;
92
- const result = yield this.enqueueReport(reportName, body);
93
- const { name } = result;
94
- for (let i = 0; i < 100; i++) {
95
- const responseValidationModel = (0, Report_1.Report)(reportRowModel !== null && reportRowModel !== void 0 ? reportRowModel : zod_1.z.any());
96
- const reportResponse = yield this.request({
97
- methodName: `frappe.desk.query_report.run`,
98
- body: Object.assign({ report_name: reportName }, body),
99
- requestMethod: "POST",
100
- responseValidationModel: zod_1.z.any().describe("Any"),
101
- });
102
- // Casting to correct type since Typescript is not able to infer the type correctly.
103
- // Type safety is ensured by zod
104
- if ((reportResponse === null || reportResponse === void 0 ? void 0 : reportResponse.result) && ((_a = reportResponse === null || reportResponse === void 0 ? void 0 : reportResponse.doc) === null || _a === void 0 ? void 0 : _a.name) === name) {
105
- const validatedReponse = responseValidationModel.parse(reportResponse);
106
- return validatedReponse.result.filter((r) => !(0, lodash_1.isArray)(r));
107
- }
108
- yield (0, utils_1.timeout)(1000);
81
+ async enqueueAndGetReport(reportName, body, reportRowModel) {
82
+ const result = await this.enqueueReport(reportName, body);
83
+ const { name } = result;
84
+ for (let i = 0; i < 100; i++) {
85
+ const responseValidationModel = (0, Report_1.Report)(reportRowModel ?? zod_1.z.any());
86
+ const reportResponse = await this.request({
87
+ methodName: `frappe.desk.query_report.run`,
88
+ body: {
89
+ report_name: reportName,
90
+ ...body,
91
+ },
92
+ requestMethod: "POST",
93
+ responseValidationModel: zod_1.z.any().describe("Any"),
94
+ });
95
+ // Casting to correct type since Typescript is not able to infer the type correctly.
96
+ // Type safety is ensured by zod
97
+ if (reportResponse?.result && reportResponse?.doc?.name === name) {
98
+ const validatedReponse = responseValidationModel.parse(reportResponse);
99
+ return validatedReponse.result.filter((r) => !(0, lodash_1.isArray)(r));
109
100
  }
110
- throw new Error(`Failed to get report ${reportName} with body ${JSON.stringify(body)}`);
111
- });
101
+ await (0, utils_1.timeout)(1000);
102
+ }
103
+ throw new Error(`Failed to get report ${reportName} with body ${JSON.stringify(body)}`);
112
104
  }
113
105
  }
114
106
  exports.ERPNextReports = ERPNextReports;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.ERPNextResourceRequest = void 0;
13
4
  const zod_1 = require("zod");
@@ -18,158 +9,159 @@ const DocTypeHelpers_1 = require("./model/DocTypeHelpers");
18
9
  const ERPNextResponse_1 = require("./model/ERPNextResponse");
19
10
  const zodContextOptionals_1 = require("../utils/zodContextOptionals");
20
11
  class ERPNextResourceRequest {
12
+ temporalClient;
21
13
  constructor(temporalClient) {
22
- this.getParams = (fields, filters, asDict, params) => {
23
- const fieldsParams = fields
24
- ? { fields: `[${fields.map((fi) => `"${fi}"`).join(",")}]` }
25
- : {};
26
- const filtersParams = filters
27
- ? {
28
- filters: `[${filters
29
- .map((f) => `[${f.map((fi) => typeof fi === "string" ? `"${fi}"` : `["${fi.join('","')}"]`)}]`)
30
- .join(",")}]`,
31
- }
32
- : {};
33
- const asDictParams = asDict === false ? { as_dict: "False" } : {};
34
- const allParams = Object.assign(Object.assign(Object.assign(Object.assign({}, fieldsParams), filtersParams), asDictParams), params);
35
- return allParams;
36
- };
37
14
  this.temporalClient = temporalClient;
38
15
  }
39
- getList(_a) {
40
- return __awaiter(this, arguments, void 0, function* ({ resourceName, fields, filters, resourceModel, skip, limit, priority = 5, asDict, params, }) {
41
- if (resourceModel && !resourceModel.description)
42
- throw new Error("Resource model must have a description");
43
- const erpNextFields = (fields === null || fields === void 0 ? void 0 : fields.length)
44
- ? fields
45
- : ["name"]; // default field is name
46
- const schema = asDict === false
47
- ? zod_1.z
48
- .object({
49
- data: zod_1.z.array(zod_1.z.array(zod_1.z.string())),
50
- })
51
- .describe(`${(resourceModel === null || resourceModel === void 0 ? void 0 : resourceModel.description)
52
- ? (resourceModel === null || resourceModel === void 0 ? void 0 : resourceModel.description) + " "
53
- : ""}List with fields ${JSON.stringify(erpNextFields)} as dict = false`)
54
- : resourceModel
55
- ? (fields === null || fields === void 0 ? void 0 : fields[0]) === "*"
56
- ? zod_1.z
57
- .object({ data: zod_1.z.array((0, DocTypeHelpers_1.DocModelListEntry)(resourceModel)) })
58
- .describe(`${resourceName} List with all fields`)
59
- : zod_1.z
60
- .object({
61
- data: zod_1.z.array((0, zodUtils_1.pickFromSchema)((0, DocTypeHelpers_1.DocModelListEntry)(resourceModel), erpNextFields.filter((f) => f !== "*") // filter out * when other fields are present
62
- )),
63
- })
64
- .describe(`${resourceModel.description} List with fields ${JSON.stringify(erpNextFields.filter((f) => f !== "*"))}`)
65
- : zod_1.z.any().describe("Any response");
66
- const defaultPaginationSize = 500;
67
- let loopLimit = defaultPaginationSize;
68
- let loopSkip = 0;
69
- let results = [];
70
- let currentResult = [];
71
- // when skip or limit are defined, don't loop automatically.
72
- const autoPaginate = skip || limit ? false : true;
73
- if (autoPaginate)
74
- logger_1.lg.info("AUTO PAGINATE");
75
- do {
76
- // use limit & skip whenever it is directly provided. In other cases use loopLimit & loopSkip to remove pagination
77
- const paramsString = (0, utils_1.paramsToString)(Object.assign(Object.assign(Object.assign({}, this.getParams(erpNextFields, filters, asDict, params)), (limit === undefined && !autoPaginate
16
+ getParams = (fields, filters, asDict, params) => {
17
+ const fieldsParams = fields
18
+ ? { fields: `[${fields.map((fi) => `"${fi}"`).join(",")}]` }
19
+ : {};
20
+ const filtersParams = filters
21
+ ? {
22
+ filters: `[${filters
23
+ .map((f) => `[${f.map((fi) => typeof fi === "string" ? `"${fi}"` : `["${fi.join('","')}"]`)}]`)
24
+ .join(",")}]`,
25
+ }
26
+ : {};
27
+ const asDictParams = asDict === false ? { as_dict: "False" } : {};
28
+ const allParams = {
29
+ ...fieldsParams,
30
+ ...filtersParams,
31
+ ...asDictParams,
32
+ ...params,
33
+ };
34
+ return allParams;
35
+ };
36
+ async getList({ resourceName, fields, filters, resourceModel, skip, limit, priority = 5, asDict, params, }) {
37
+ if (resourceModel && !resourceModel.description)
38
+ throw new Error("Resource model must have a description");
39
+ const erpNextFields = fields?.length
40
+ ? fields
41
+ : ["name"]; // default field is name
42
+ const schema = asDict === false
43
+ ? zod_1.z
44
+ .object({
45
+ data: zod_1.z.array(zod_1.z.array(zod_1.z.string())),
46
+ })
47
+ .describe(`${resourceModel?.description
48
+ ? resourceModel?.description + " "
49
+ : ""}List with fields ${JSON.stringify(erpNextFields)} as dict = false`)
50
+ : resourceModel
51
+ ? fields?.[0] === "*"
52
+ ? zod_1.z
53
+ .object({ data: zod_1.z.array((0, DocTypeHelpers_1.DocModelListEntry)(resourceModel)) })
54
+ .describe(`${resourceName} List with all fields`)
55
+ : zod_1.z
56
+ .object({
57
+ data: zod_1.z.array((0, zodUtils_1.pickFromSchema)((0, DocTypeHelpers_1.DocModelListEntry)(resourceModel), erpNextFields.filter((f) => f !== "*") // filter out * when other fields are present
58
+ )),
59
+ })
60
+ .describe(`${resourceModel.description} List with fields ${JSON.stringify(erpNextFields.filter((f) => f !== "*"))}`)
61
+ : zod_1.z.any().describe("Any response");
62
+ const defaultPaginationSize = 500;
63
+ let loopLimit = defaultPaginationSize;
64
+ let loopSkip = 0;
65
+ let results = [];
66
+ let currentResult = [];
67
+ // when skip or limit are defined, don't loop automatically.
68
+ const autoPaginate = skip || limit ? false : true;
69
+ if (autoPaginate)
70
+ logger_1.lg.info("AUTO PAGINATE");
71
+ do {
72
+ // use limit & skip whenever it is directly provided. In other cases use loopLimit & loopSkip to remove pagination
73
+ const paramsString = (0, utils_1.paramsToString)({
74
+ ...this.getParams(erpNextFields, filters, asDict, params),
75
+ ...(limit === undefined && !autoPaginate
78
76
  ? {}
79
- : { limit: String(limit !== null && limit !== void 0 ? limit : loopLimit) })), (skip === undefined && !autoPaginate
77
+ : { limit: String(limit ?? loopLimit) }),
78
+ ...(skip === undefined && !autoPaginate
80
79
  ? {}
81
- : { limit_start: String(skip !== null && skip !== void 0 ? skip : loopSkip) })));
82
- const result = yield this.temporalClient.executeERPNextRequestWorkflow(`GET-${resourceName.toLowerCase()}-List`, {
83
- requestMethod: "GET",
84
- resourceName,
85
- responseValidationModel: schema,
86
- params: paramsString,
87
- }, "erpnext", priority);
88
- currentResult = result.data;
89
- results = [...results, ...currentResult];
90
- loopSkip = loopSkip + loopLimit;
91
- } while (autoPaginate && currentResult.length);
92
- return results;
93
- });
94
- }
95
- getById(_a) {
96
- return __awaiter(this, arguments, void 0, function* ({ resourceName, resourceId, resourceModel, priority = 5, }) {
97
- if (resourceModel && !resourceModel.description)
98
- throw new Error("Resource model must have a description");
99
- if (!resourceId)
100
- throw new Error("Resource id is required");
101
- const result = yield this.temporalClient
102
- .executeERPNextRequestWorkflow(`GET-${resourceName}-${resourceId}`, {
103
- requestMethod: "GET",
104
- resourceName,
105
- resourceId,
106
- responseValidationModel: resourceModel
107
- ? zod_1.z
108
- .object({ data: (0, DocTypeHelpers_1.DocModel)(resourceModel) })
109
- .describe(resourceName + " Response")
110
- : undefined,
111
- }, "erpnext", priority)
112
- .catch((err) => {
113
- if (err.message.includes("Error 404")) {
114
- logger_1.lg.error(`Resource ${resourceName} with id ${resourceId} not found`);
115
- return;
116
- }
117
- throw err;
80
+ : { limit_start: String(skip ?? loopSkip) }),
118
81
  });
119
- return result === null || result === void 0 ? void 0 : result.data;
120
- });
121
- }
122
- updateById(_a) {
123
- return __awaiter(this, arguments, void 0, function* ({ resourceName, resourceId, inputValidationModel, resourceModel, body, priority = 5, }) {
124
- // accept partial input while enforcing allowed keys
125
- const partialInputValidationModel = inputValidationModel && inputValidationModel instanceof zod_1.ZodObject
126
- ? inputValidationModel.partial().strict()
127
- : inputValidationModel;
128
- const result = yield this.temporalClient.executeERPNextRequestWorkflow(`PUT-${resourceName}-${resourceId}`, {
129
- requestMethod: "PUT",
130
- resourceId,
82
+ const result = await this.temporalClient.executeERPNextRequestWorkflow(`GET-${resourceName.toLowerCase()}-List`, {
83
+ requestMethod: "GET",
131
84
  resourceName,
132
- inputValidationModel: partialInputValidationModel,
133
- responseValidationModel: resourceModel
134
- ? zod_1.z.object({ data: (0, DocTypeHelpers_1.DocModel)(resourceModel) }).describe(resourceName)
135
- : undefined,
136
- body,
85
+ responseValidationModel: schema,
86
+ params: paramsString,
137
87
  }, "erpnext", priority);
138
- return result.data;
139
- });
88
+ currentResult = result.data;
89
+ results = [...results, ...currentResult];
90
+ loopSkip = loopSkip + loopLimit;
91
+ } while (autoPaginate && currentResult.length);
92
+ return results;
140
93
  }
141
- create(_a) {
142
- return __awaiter(this, arguments, void 0, function* ({ resourceName, inputValidationModel, resourceModel, body, params, priority = 5, }) {
143
- if (resourceModel && !resourceModel.description)
144
- throw new Error("Resource model must have a description");
145
- const result = yield this.temporalClient.executeERPNextRequestWorkflow(`POST-${resourceName}`, {
146
- requestMethod: "POST",
147
- resourceName,
148
- inputValidationModel: inputValidationModel !== null && inputValidationModel !== void 0 ? inputValidationModel : (resourceModel ? (0, zodContextOptionals_1.ResourceInput)(resourceModel) : undefined),
149
- responseValidationModel: resourceModel
150
- ? zod_1.z
151
- .object({
152
- data: (0, DocTypeHelpers_1.DocModel)(resourceModel),
153
- })
154
- .describe(resourceModel.description)
155
- : undefined,
156
- params: (0, utils_1.paramsToString)(params),
157
- body,
158
- }, "erpnext", priority);
159
- return result.data;
94
+ async getById({ resourceName, resourceId, resourceModel, priority = 5, }) {
95
+ if (resourceModel && !resourceModel.description)
96
+ throw new Error("Resource model must have a description");
97
+ if (!resourceId)
98
+ throw new Error("Resource id is required");
99
+ const result = await this.temporalClient
100
+ .executeERPNextRequestWorkflow(`GET-${resourceName}-${resourceId}`, {
101
+ requestMethod: "GET",
102
+ resourceName,
103
+ resourceId,
104
+ responseValidationModel: resourceModel
105
+ ? zod_1.z
106
+ .object({ data: (0, DocTypeHelpers_1.DocModel)(resourceModel) })
107
+ .describe(resourceName + " Response")
108
+ : undefined,
109
+ }, "erpnext", priority)
110
+ .catch((err) => {
111
+ if (err.message.includes("Error 404")) {
112
+ logger_1.lg.error(`Resource ${resourceName} with id ${resourceId} not found`);
113
+ return;
114
+ }
115
+ throw err;
160
116
  });
117
+ return result?.data;
161
118
  }
162
- deleteById(_a) {
163
- return __awaiter(this, arguments, void 0, function* ({ resourceName, resourceId, resourceModel, priority = 5, }) {
164
- if (resourceModel && !resourceModel.description)
165
- throw new Error("Resource model must have a description");
166
- return yield this.temporalClient.executeERPNextRequestWorkflow(`DELETE-${resourceName}`, {
167
- requestMethod: "DELETE",
168
- resourceName,
169
- resourceId,
170
- responseValidationModel: ERPNextResponse_1.DeleteResponseModel,
171
- }, "erpnext", priority);
172
- });
119
+ async updateById({ resourceName, resourceId, inputValidationModel, resourceModel, body, priority = 5, }) {
120
+ // accept partial input while enforcing allowed keys
121
+ const partialInputValidationModel = inputValidationModel && inputValidationModel instanceof zod_1.ZodObject
122
+ ? inputValidationModel.partial().strict()
123
+ : inputValidationModel;
124
+ const result = await this.temporalClient.executeERPNextRequestWorkflow(`PUT-${resourceName}-${resourceId}`, {
125
+ requestMethod: "PUT",
126
+ resourceId,
127
+ resourceName,
128
+ inputValidationModel: partialInputValidationModel,
129
+ responseValidationModel: resourceModel
130
+ ? zod_1.z.object({ data: (0, DocTypeHelpers_1.DocModel)(resourceModel) }).describe(resourceName)
131
+ : undefined,
132
+ body,
133
+ }, "erpnext", priority);
134
+ return result.data;
135
+ }
136
+ async create({ resourceName, inputValidationModel, resourceModel, body, params, priority = 5, }) {
137
+ if (resourceModel && !resourceModel.description)
138
+ throw new Error("Resource model must have a description");
139
+ const result = await this.temporalClient.executeERPNextRequestWorkflow(`POST-${resourceName}`, {
140
+ requestMethod: "POST",
141
+ resourceName,
142
+ inputValidationModel: inputValidationModel ??
143
+ (resourceModel ? (0, zodContextOptionals_1.ResourceInput)(resourceModel) : undefined),
144
+ responseValidationModel: resourceModel
145
+ ? zod_1.z
146
+ .object({
147
+ data: (0, DocTypeHelpers_1.DocModel)(resourceModel),
148
+ })
149
+ .describe(resourceModel.description)
150
+ : undefined,
151
+ params: (0, utils_1.paramsToString)(params),
152
+ body,
153
+ }, "erpnext", priority);
154
+ return result.data;
155
+ }
156
+ async deleteById({ resourceName, resourceId, resourceModel, priority = 5, }) {
157
+ if (resourceModel && !resourceModel.description)
158
+ throw new Error("Resource model must have a description");
159
+ return await this.temporalClient.executeERPNextRequestWorkflow(`DELETE-${resourceName}`, {
160
+ requestMethod: "DELETE",
161
+ resourceName,
162
+ resourceId,
163
+ responseValidationModel: ERPNextResponse_1.DeleteResponseModel,
164
+ }, "erpnext", priority);
173
165
  }
174
166
  }
175
167
  exports.ERPNextResourceRequest = ERPNextResourceRequest;