@keshavsoft/tallyextract 1.1.2 → 1.2.3

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 (63) hide show
  1. package/index.js +1 -1
  2. package/package.json +1 -1
  3. package/src/v3/api/Import/ledgers.json +17 -0
  4. package/src/v3/api/PrepareDataObject/ForInventory/entryFile.js +24 -0
  5. package/src/v3/api/PrepareDataObject/ForInventory/prepareInventory.js +85 -0
  6. package/src/v3/api/PrepareDataObject/ForLedger/entryFile.js +46 -0
  7. package/src/v3/api/PrepareDataObject/ForLedger/prepareLedger.js +24 -0
  8. package/src/v3/api/PrepareDataObject/entryFile.js +20 -0
  9. package/src/v3/api/PrepareDataObject/prepareClientData.js +56 -0
  10. package/src/v3/api/PrepareDataObject/prepareTallyJson/entryFile.js +25 -0
  11. package/src/v3/api/importVoucher.js +14 -0
  12. package/src/v3/api/index.js +5 -0
  13. package/src/{v1 → v3}/api/ledger.js +1 -1
  14. package/src/v3/api/utils/validateInput.js +36 -0
  15. package/src/v3/core/impotToTally.js +14 -0
  16. package/src/v1/Import/ledgers.json +0 -8
  17. package/src/v1/api/index.js +0 -3
  18. package/src/v1/config/getSchema.js +0 -20
  19. package/src/v1/engine/index.js +0 -5
  20. package/src/v1/engine/mutate/delete/deleteBase.js +0 -26
  21. package/src/v1/engine/mutate/delete/deleteWithChecks.js +0 -14
  22. package/src/v1/engine/mutate/index.js +0 -7
  23. package/src/v1/engine/mutate/insert/insertAsIs.js +0 -7
  24. package/src/v1/engine/mutate/insert/insertBase.js +0 -19
  25. package/src/v1/engine/mutate/insert/insertFlat.js +0 -24
  26. package/src/v1/engine/mutate/insert/insertGenPk copy.js +0 -39
  27. package/src/v1/engine/mutate/insert/insertGenPk.js +0 -41
  28. package/src/v1/engine/mutate/insert/insertWithChecks.js +0 -52
  29. package/src/v1/engine/mutate/update/updateBase.js +0 -26
  30. package/src/v1/engine/mutate/update/updateWithChecks.js +0 -18
  31. package/src/v1/engine/query/aggregate/count.js +0 -13
  32. package/src/v1/engine/query/aggregate/index.js +0 -1
  33. package/src/v1/engine/query/filterByColumns.js +0 -18
  34. package/src/v1/engine/query/filterByPk.js +0 -18
  35. package/src/v1/engine/query/findAll.js +0 -14
  36. package/src/v1/engine/query/findByPk.js +0 -18
  37. package/src/v1/engine/query/index.js +0 -8
  38. package/src/v1/helpers/buildMutate.js +0 -28
  39. package/src/v1/helpers/buildQuery.js +0 -27
  40. package/src/v1/helpers/file/read.js +0 -7
  41. package/src/v1/helpers/file/write.js +0 -5
  42. package/src/v1/helpers/pkHelper.js +0 -19
  43. package/src/v1/helpers/validate.js +0 -27
  44. package/src/v1/helpers/validateHelper.js +0 -27
  45. package/src/v1/helpers/validators/default.js +0 -5
  46. package/src/v1/helpers/validators/enum.js +0 -7
  47. package/src/v1/helpers/validators/length.js +0 -11
  48. package/src/v1/helpers/validators/minMax.js +0 -11
  49. package/src/v1/helpers/validators/pattern.js +0 -8
  50. package/src/v1/helpers/validators/required.js +0 -5
  51. package/src/v1/helpers/validators/type.js +0 -15
  52. package/src/v1/helpers/validators/unique.js +0 -8
  53. package/src/v1/schema/schema.json +0 -133
  54. /package/src/{v1 → v3/api}/Import/Templates/inventory.json +0 -0
  55. /package/src/{v1 → v3/api}/Import/Templates/ledgers.json +0 -0
  56. /package/src/{v1 → v3/api}/Import/Templates/main.json +0 -0
  57. /package/src/{v1 → v3/api}/Import/Templates/template.json +0 -0
  58. /package/src/{v1 → v3/api}/Import/staticVariables.json +0 -0
  59. /package/src/{v1 → v3}/api/stockItems.js +0 -0
  60. /package/src/{v1 → v3}/cli.js +0 -0
  61. /package/src/{v1 → v3}/core/sendToTally.js +0 -0
  62. /package/src/{v1 → v3}/index.js +0 -0
  63. /package/src/{v1 → v3}/utils/readJson.js +0 -0
package/index.js CHANGED
@@ -1 +1 @@
1
- export * from "./src/v1/index.js";
1
+ export * from "./src/v3/index.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keshavsoft/tallyextract",
3
- "version": "1.1.2",
3
+ "version": "1.2.3",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -0,0 +1,17 @@
1
+ {
2
+ "static_variables": [
3
+ {
4
+ "name": "svExportFormat",
5
+ "value": "jsonex"
6
+ },
7
+ {
8
+ "name": "svCurrentCompany",
9
+ "value": "Mani9"
10
+ }
11
+ ],
12
+ "fetch_List": [
13
+ "Name",
14
+ "Parent",
15
+ "Closing Balance"
16
+ ]
17
+ }
@@ -0,0 +1,24 @@
1
+ import path from "path";
2
+ import { fileURLToPath } from "url";
3
+ import { startFunc as prepareInventory } from "./prepareInventory.js";
4
+ // --------------------------------------------------
5
+
6
+ // Creates inventory entries array from items.json
7
+ const startFunc = ({ inItemsJsonAsArray }) => {
8
+ let LocalArray = [];
9
+ const LocalInItemsJsonAsArray = inItemsJsonAsArray;
10
+
11
+ return LocalInItemsJsonAsArray.map(element => {
12
+ return prepareInventory({
13
+ inItemName: element.ItemName,
14
+ inTaxPer: element.TaxPer,
15
+ inUom: element.Uom,
16
+ inRate: element.Rate,
17
+ inQty: element.Qty
18
+ });
19
+ });
20
+
21
+ return CommonFileDataAsJson;
22
+ };
23
+
24
+ export { startFunc };
@@ -0,0 +1,85 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ import { fileURLToPath } from "url";
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ const filePath = path.join(__dirname, "../../Import/Templates/inventory.json");
10
+
11
+ // Prepares single inventory entry
12
+ const startFunc = ({ inItemName, inTaxPer, inUom, inRate, inQty }) => {
13
+ // const filePath = path.join("./Import/Templates", "inventory.json");
14
+ let template = fs.readFileSync(filePath, "utf8");
15
+
16
+ let data = JSON.parse(template);
17
+
18
+ const LocalItemName = inItemName;
19
+ const LocalUom = inUom;
20
+ const LocalQty = inQty;
21
+ const LocalRate = inRate;
22
+
23
+ const LocalRateWithTax = LocalRate * (1 + (inTaxPer / 100));
24
+ const LocalAmount = LocalRate * LocalQty;
25
+
26
+ data.hsnitemsource = LocalItemName;
27
+ data.gstitemsource = LocalItemName;
28
+ data.stockitemname = LocalItemName;
29
+
30
+ data.mrprate = `${LocalRateWithTax}.00/${LocalUom}`;
31
+ data.inclvatrate = `${LocalRateWithTax}.00/${LocalUom}`;
32
+
33
+
34
+ // --------------------------------------------------
35
+ // Quantity & Amount
36
+ // --------------------------------------------------
37
+
38
+ data.amount = `${LocalAmount}.00`;
39
+ data.rate = `${LocalRate}.00/${LocalUom}`;
40
+ data.actualqty = `${LocalQty}.00 ${LocalUom}`;
41
+ data.billedqty = `${LocalQty}.00 ${LocalUom}`;
42
+
43
+
44
+ // --------------------------------------------------
45
+ // Batch Allocation
46
+ // --------------------------------------------------
47
+
48
+ data.batchallocations[0].amount = LocalRate * LocalQty;
49
+ data.batchallocations[0].actualqty = `${LocalQty}.00 ${LocalUom}`;
50
+ data.batchallocations[0].billedqty = `${LocalQty}.00 ${LocalUom}`;
51
+
52
+
53
+ // --------------------------------------------------
54
+ // Accounting Allocation
55
+ // --------------------------------------------------
56
+
57
+ data.accountingallocations[0].classrate = `${LocalRate}.00`;
58
+ data.accountingallocations[0].amount = `${LocalAmount}.00`;
59
+
60
+ updateRateDetails(data.ratedetails, inTaxPer);
61
+
62
+ return data;
63
+ };
64
+
65
+ // Update GST ratedetails safely
66
+ const updateRateDetails = (ratedetails, taxPer) => {
67
+ const half = (taxPer / 2).toFixed(2);
68
+ const full = Number(taxPer).toFixed(2);
69
+
70
+ ratedetails.forEach(row => {
71
+ switch (row.gstratedutyhead) {
72
+ case "CGST":
73
+ row.gstrate = half;
74
+ break;
75
+ case "SGST/UTGST":
76
+ row.gstrate = half;
77
+ break;
78
+ case "IGST":
79
+ row.gstrate = full;
80
+ break;
81
+ }
82
+ });
83
+ };
84
+
85
+ export { startFunc };
@@ -0,0 +1,46 @@
1
+ import path from "path";
2
+ import { fileURLToPath } from "url";
3
+ import { startFunc as prepareLedger } from "./prepareLedger.js";
4
+
5
+ // Creates ledger entries for voucher
6
+ const startFunc = ({ inItemsJsonAsArray, inLedgerDetails }) => {
7
+ let LocalArray = [];
8
+
9
+ const LocalInItemsJsonAsArray = inItemsJsonAsArray;
10
+
11
+ const LocalAmount = LocalInItemsJsonAsArray.map(element => {
12
+ return element.Rate * element.Qty * (1 + (element.TaxPer / 100));
13
+ });
14
+
15
+ const LocalOnlyAmount = LocalInItemsJsonAsArray.map(element => {
16
+ return element.Rate * element.Qty;
17
+ });
18
+
19
+ const amountSum = LocalAmount.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
20
+ const onlyAmountSum = LocalOnlyAmount.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
21
+
22
+ const LocalLedgerEntry = prepareLedger({
23
+ inLedgerName: inLedgerDetails.LedgerName,
24
+ inAmount: `-${amountSum}.00`
25
+ });
26
+
27
+ LocalArray.push(LocalLedgerEntry);
28
+
29
+ const LocalCGST = prepareLedger({
30
+ inLedgerName: "CGST Output",
31
+ inAmount: `${(amountSum - onlyAmountSum) / 2}.00`
32
+ });
33
+
34
+ LocalArray.push(LocalCGST);
35
+
36
+ const LocalSGST = prepareLedger({
37
+ inLedgerName: "SGST Output",
38
+ inAmount: `${(amountSum - onlyAmountSum) / 2}.00`
39
+ });
40
+
41
+ LocalArray.push(LocalSGST);
42
+
43
+ return LocalArray;
44
+ };
45
+
46
+ export { startFunc };
@@ -0,0 +1,24 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ import { fileURLToPath } from "url";
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ const filePath = path.join(__dirname, "../../Import/Templates/ledgers.json");
10
+
11
+ // Prepares single ledger entry
12
+ const startFunc = ({ inLedgerName, inAmount }) => {
13
+ // const filePath = path.join("./Import/Templates", "ledgers.json");
14
+ let template = fs.readFileSync(filePath, "utf8");
15
+
16
+ let data = JSON.parse(template);
17
+
18
+ data.ledgername = inLedgerName;
19
+ data.amount = inAmount;
20
+
21
+ return data;
22
+ };
23
+
24
+ export { startFunc };
@@ -0,0 +1,20 @@
1
+ import { startFunc as prepareClientData } from "./prepareClientData.js";
2
+ import { startFunc as prepareTallyJson } from "./prepareTallyJson/entryFile.js";
3
+
4
+ const startFunc = ({ inClientData }) => {
5
+ try {
6
+ let data = prepareTallyJson();
7
+
8
+ const fromClientData = prepareClientData({
9
+ inTallyJson: data,
10
+ inClientData
11
+ });
12
+
13
+ return fromClientData;
14
+ } catch (err) {
15
+ console.error("Import Failed");
16
+ console.log(err.response?.data || err.message);
17
+ };
18
+ };
19
+
20
+ export { startFunc };
@@ -0,0 +1,56 @@
1
+ import { startFunc as ForLedger } from "./ForLedger/entryFile.js";
2
+ import { startFunc as ForInventory } from "./ForInventory/entryFile.js";
3
+
4
+ const startFunc = ({ inTallyJson, inClientData }) => {
5
+ try {
6
+ let data = inTallyJson;
7
+
8
+ const LocalClientData = inClientData;
9
+
10
+ const LocalInventoryItem = ForInventory({ inItemsJsonAsArray: LocalClientData.allinventoryentries });
11
+
12
+ const LocalLedgerItem = ForLedger({
13
+ inItemsJsonAsArray: LocalClientData.allinventoryentries,
14
+ inLedgerDetails: LocalClientData.customerDetails
15
+ });
16
+
17
+ changeCustomerDetails({
18
+ inLedgerName: LocalClientData.customerDetails.LedgerName,
19
+ inData: data
20
+ });
21
+
22
+ changeVoucherDate({
23
+ inData: data,
24
+ inDate: LocalClientData.customerDetails.InvoiceDate
25
+ });
26
+
27
+ data.tallymessage[0].allinventoryentries = LocalInventoryItem;
28
+ data.tallymessage[0].ledgerentries = LocalLedgerItem;
29
+
30
+ return data;
31
+ } catch (err) {
32
+ console.error("Import Failed");
33
+ console.log(err.response?.data || err.message);
34
+ };
35
+ };
36
+
37
+ const changeCustomerDetails = ({ inLedgerName, inData }) => {
38
+ const CommonLedgerName = inLedgerName;
39
+
40
+ inData.tallymessage[0].partyname = CommonLedgerName;
41
+ inData.tallymessage[0].basicbuyername = CommonLedgerName;
42
+ inData.tallymessage[0].partyledgername = CommonLedgerName;
43
+ inData.tallymessage[0].consigneemailingname = CommonLedgerName;
44
+ inData.tallymessage[0].partymailingname = CommonLedgerName;
45
+ inData.tallymessage[0].basicbasepartyname = CommonLedgerName;
46
+ };
47
+
48
+ const changeVoucherDate = ({ inData, inDate }) => {
49
+ const localDate = inDate;
50
+
51
+ inData.tallymessage[0].date = localDate;
52
+ inData.tallymessage[0].vchstatusdate = localDate;
53
+ inData.tallymessage[0].effectivedate = localDate;
54
+ };
55
+
56
+ export { startFunc };
@@ -0,0 +1,25 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ import { fileURLToPath } from "url";
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ const filePath = path.join(__dirname, "../../Import/Templates/template.json");
10
+
11
+ const startFunc = () => {
12
+ try {
13
+ // const filePath = path.join("../../Import/Templates", "template.json");
14
+ let template = fs.readFileSync(filePath, "utf8");
15
+
16
+ let data = JSON.parse(template);
17
+
18
+ return data;
19
+ } catch (err) {
20
+ console.error("Import Failed");
21
+ console.log(err.response?.data || err.message);
22
+ };
23
+ };
24
+
25
+ export { startFunc };
@@ -0,0 +1,14 @@
1
+ import { sendToTally } from "../core/impotToTally.js";
2
+ import { startFunc as PrepareDataObject } from "../api/PrepareDataObject/entryFile.js";
3
+
4
+ import { validateImportVoucherInput } from "./utils/validateInput.js";
5
+
6
+ const importVoucher = async (inClientData) => {
7
+ validateImportVoucherInput(inClientData); // 🔥 early fail
8
+
9
+ const bodyToSend = PrepareDataObject({ inClientData });
10
+
11
+ return await sendToTally(bodyToSend);
12
+ };
13
+
14
+ export { importVoucher };
@@ -0,0 +1,5 @@
1
+ // src/v1/api/index.js
2
+ export { ledger } from "./ledger.js";
3
+ export { stockItems } from "./stockitems.js";
4
+
5
+ export { importVoucher } from "./importVoucher.js";
@@ -2,5 +2,5 @@
2
2
  import { sendToTally } from "../core/sendToTally.js";
3
3
 
4
4
  export function ledger() {
5
- return sendToTally("KeshavStockItems");
5
+ return sendToTally("KeshavLedgers");
6
6
  };
@@ -0,0 +1,36 @@
1
+ // utils/validateInput.js
2
+ const validateImportVoucherInput = (data) => {
3
+ if (!data || typeof data !== "object") {
4
+ throw new Error("Input must be an object");
5
+ }
6
+
7
+ // 🔹 allinventoryentries
8
+ if (!Array.isArray(data.allinventoryentries)) {
9
+ throw new Error("allinventoryentries must be an array");
10
+ }
11
+
12
+ if (data.allinventoryentries.length === 0) {
13
+ throw new Error("allinventoryentries cannot be empty");
14
+ }
15
+
16
+ // optional: validate one item structure
17
+ const item = data.allinventoryentries[0];
18
+ if (!item.ItemName || !item.Qty) {
19
+ throw new Error("Invalid inventory item structure");
20
+ }
21
+
22
+ // 🔹 customerDetails
23
+ if (!data.customerDetails || typeof data.customerDetails !== "object") {
24
+ throw new Error("customerDetails must be an object");
25
+ }
26
+
27
+ if (!data.customerDetails.LedgerName) {
28
+ throw new Error("LedgerName is required in customerDetails");
29
+ }
30
+
31
+ if (!data.customerDetails.InvoiceDate) {
32
+ throw new Error("InvoiceDate is required in customerDetails");
33
+ }
34
+ };
35
+
36
+ export { validateImportVoucherInput };
@@ -0,0 +1,14 @@
1
+ export async function sendToTally(data, url = "http://localhost:9000") {
2
+ const res = await fetch(url, {
3
+ method: "POST",
4
+ headers: {
5
+ "Content-Type": "application/json",
6
+ "TallyRequest": "Import",
7
+ "Type": "Data",
8
+ "Id": "Vouchers"
9
+ },
10
+ body: JSON.stringify(data)
11
+ });
12
+
13
+ return res.json();
14
+ };
@@ -1,8 +0,0 @@
1
- {
2
- "static_variables": [
3
- {
4
- "name": "svExportFormat",
5
- "value": "jsonex"
6
- }
7
- ]
8
- }
@@ -1,3 +0,0 @@
1
- // src/v1/api/index.js
2
- export { ledger } from "./ledger.js";
3
- export { stockItems } from "./stockitems.js";
@@ -1,20 +0,0 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import { getConfig } from "../../core/configStore.js";
4
-
5
- export const getSchema = (table) => {
6
- const config = getConfig();
7
-
8
- const schemaPath = path.join(config.SchemaPath, `${table}.json`);
9
-
10
- if (!fs.existsSync(schemaPath)) {
11
- throw new Error(`Schema not found for table "${table}" at ${schemaPath}`);
12
- }
13
-
14
- try {
15
- const schema = fs.readFileSync(schemaPath, "utf-8");
16
- return JSON.parse(schema);
17
- } catch (err) {
18
- throw new Error(`Invalid schema JSON for "${table}": ${err.message}`);
19
- };
20
- };
@@ -1,5 +0,0 @@
1
- export * as query from "./query/index.js";
2
- export * as mutate from "./mutate/index.js";
3
- export * as remove from "./remove/index.js";
4
- export * as filter from "./filter/index.js";
5
- export * as aggregate from "./aggregate/index.js";
@@ -1,26 +0,0 @@
1
- import { getConfig } from "../../../../core/configStore.js";
2
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
3
- import { readData } from "../../../helpers/file/read.js";
4
- import { writeData } from "../../../helpers/file/write.js";
5
-
6
- const deleteBase = ({ table, pk }) => {
7
- const config = getConfig();
8
- const path = buildDataPath(config, table);
9
-
10
- const data = readData(path);
11
-
12
- const index = data.findIndex(r => r.pk === pk);
13
-
14
- if (index === -1) {
15
- throw new Error(`Record with pk ${pk} not found`);
16
- }
17
-
18
- const deleted = data[index];
19
- data.splice(index, 1);
20
-
21
- writeData(path, data);
22
-
23
- return deleted;
24
- };
25
-
26
- export default deleteBase;
@@ -1,14 +0,0 @@
1
- import deleteBase from "./deleteBase.js";
2
- import { getSchema } from "../../../config/getSchema.js";
3
-
4
- const deleteWithChecks = ({ table, pk }) => {
5
- const schema = getSchema(table);
6
-
7
- if (!pk) {
8
- throw new Error("pk is required");
9
- }
10
-
11
- return deleteBase({ table, pk });
12
- };
13
-
14
- export default deleteWithChecks;
@@ -1,7 +0,0 @@
1
- export { default as insertAsIs } from "./insert/insertAsIs.js";
2
- export { default as insertFlat } from "./insert/insertFlat.js";
3
- export { default as insertGenPk } from "./insert/insertGenPk.js";
4
- export { default as insertWithChecks } from "./insert/insertWithChecks.js";
5
-
6
- export { default as deleteWithChecks } from "./delete/deleteWithChecks.js";
7
- export { default as updateWithChecks } from "./update/updateWithChecks.js";
@@ -1,7 +0,0 @@
1
- import insertBase from "./insertBase.js";
2
-
3
- const insertAsIs = ({ table, record }) => {
4
- return insertBase({ table, record });
5
- };
6
-
7
- export default insertAsIs;
@@ -1,19 +0,0 @@
1
- import { getConfig } from "../../../../core/configStore.js";
2
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
3
- import { readData } from "../../../helpers/file/read.js";
4
- import { writeData } from "../../../helpers/file/write.js";
5
-
6
- const insertBase = ({ table, record }) => {
7
- const config = getConfig();
8
- const path = buildDataPath(config, table);
9
-
10
- const data = readData(path);
11
-
12
- data.push(record);
13
-
14
- writeData(path, data);
15
-
16
- return record;
17
- };
18
-
19
- export default insertBase;
@@ -1,24 +0,0 @@
1
- import insertBase from "./insertBase.js";
2
-
3
- const isPlainObject = (val) =>
4
- typeof val === "object" && val !== null && !Array.isArray(val);
5
-
6
- const isPrimitive = (val) =>
7
- val === null ||
8
- ["string", "number", "boolean"].includes(typeof val);
9
-
10
- const insertFlat = ({ table, record }) => {
11
- if (!isPlainObject(record)) {
12
- throw new Error("must be object");
13
- }
14
-
15
- for (const key in record) {
16
- if (!isPrimitive(record[key])) {
17
- throw new Error(`invalid value for ${key}`);
18
- }
19
- }
20
-
21
- return insertBase({ table, record }); // 🔥 reuse
22
- };
23
-
24
- export default insertFlat;
@@ -1,39 +0,0 @@
1
- import insertBase from "./insertBase.js";
2
-
3
- import { getConfig } from "../../../../core/configStore.js";
4
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
5
- import { readData } from "../../../helpers/file/read.js";
6
-
7
- import { getSchema } from "../../../config/getSchema.js";
8
- import { getPrimaryKey, attachPrimaryKey } from "../../../helpers/pkHelper.js";
9
-
10
- const insertGenPk = ({ table, record }) => {
11
- let schema;
12
- try {
13
- schema = getSchema(table);
14
- } catch (err) {
15
- console.error(err.message);
16
- return; // or throw based on your design
17
- };
18
-
19
- // const schema = getSchema(table);
20
- const pk = getPrimaryKey(schema.columns);
21
-
22
- // ✅ if pk already exists, skip generation
23
- if (record[pk] !== undefined) {
24
- return insertBase({ table, record });
25
- }
26
-
27
- const config = getConfig();
28
- const path = buildDataPath(config, table);
29
- const data = readData(path);
30
-
31
- const newRecord = attachPrimaryKey(record, pk, data);
32
-
33
- return insertBase({
34
- table,
35
- record: newRecord
36
- });
37
- };
38
-
39
- export default insertGenPk;
@@ -1,41 +0,0 @@
1
- import insertBase from "./insertBase.js";
2
- import { getConfig } from "../../../../core/configStore.js";
3
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
4
- import { readData } from "../../../helpers/file/read.js";
5
- import { getSchema } from "../../../config/getSchema.js";
6
- import { getPrimaryKey, attachPrimaryKey } from "../../../helpers/pkHelper.js";
7
-
8
- const validateInput = ({ table, record }) => {
9
- if (!table) throw new Error("table is required");
10
- if (!record || typeof record !== "object") throw new Error("record must be object");
11
- };
12
-
13
- const safeGetSchema = (table) => {
14
- const schema = getSchema(table);
15
- if (!schema?.columns) throw new Error(`Invalid schema for "${table}"`);
16
- return schema;
17
- };
18
-
19
- const getData = (table) => {
20
- const config = getConfig();
21
- const path = buildDataPath(config, table);
22
- return readData(path);
23
- };
24
-
25
- const insertGenPk = ({ table, record }) => {
26
- validateInput({ table, record });
27
-
28
- const schema = safeGetSchema(table);
29
- const pk = getPrimaryKey(schema.columns);
30
-
31
- if (record[pk] !== undefined) {
32
- return insertBase({ table, record });
33
- }
34
-
35
- const data = getData(table);
36
- const newRecord = attachPrimaryKey(record, pk, data);
37
-
38
- return insertBase({ table, record: newRecord });
39
- };
40
-
41
- export default insertGenPk;
@@ -1,52 +0,0 @@
1
- import insertBase from "./insertBase.js";
2
- import validate from "../../../helpers/validate.js";
3
-
4
- import { getSchema } from "../../../config/getSchema.js";
5
- import { getPrimaryKey, attachPrimaryKey } from "../../../helpers/pkHelper.js";
6
-
7
- import { getConfig } from "../../../../core/configStore.js";
8
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
9
- import { readData } from "../../../helpers/file/read.js";
10
-
11
- const insertWithChecks1 = ({ table, record }) => {
12
- const schema = getSchema(table);
13
-
14
- // 🔥 PK handling
15
- const pk = getPrimaryKey(schema.columns);
16
-
17
- if (record[pk] === undefined) {
18
- const config = getConfig();
19
- const path = buildDataPath(config, table);
20
- const data = readData(path);
21
-
22
- record = attachPrimaryKey(record, pk, data);
23
- }
24
-
25
- // 🔥 validate AFTER pk
26
- validate(schema, record);
27
-
28
- return insertBase({ table, record });
29
- };
30
-
31
- const insertWithChecks = ({ table, record }) => {
32
- try {
33
- const schema = getSchema(table);
34
- const pk = getPrimaryKey(schema.columns);
35
-
36
- if (record[pk] === undefined) {
37
- const config = getConfig();
38
- const path = buildDataPath(config, table);
39
- const data = readData(path);
40
- record = attachPrimaryKey(record, pk, data);
41
- }
42
-
43
- validate(schema, record);
44
-
45
- return insertBase({ table, record });
46
-
47
- } catch (err) {
48
- throw new Error(`Insert failed [${table}]: ${err.message}`);
49
- }
50
- };
51
-
52
- export default insertWithChecks;
@@ -1,26 +0,0 @@
1
- import { getConfig } from "../../../../core/configStore.js";
2
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
3
- import { readData } from "../../../helpers/file/read.js";
4
- import { writeData } from "../../../helpers/file/write.js";
5
-
6
- const updateBase = ({ table, pk, updates }) => {
7
- const config = getConfig();
8
- const path = buildDataPath(config, table);
9
-
10
- const data = readData(path);
11
-
12
- const index = data.findIndex(r => r.pk === pk);
13
- if (index === -1) {
14
- throw new Error(`Record with pk ${pk} not found`);
15
- }
16
-
17
- const existing = data[index];
18
- const updated = { ...existing, ...updates, pk: existing.pk }; // 🔥 keep pk safe
19
-
20
- data[index] = updated;
21
- writeData(path, data);
22
-
23
- return updated;
24
- };
25
-
26
- export default updateBase;
@@ -1,18 +0,0 @@
1
- import updateBase from "./updateBase.js";
2
- import validate from "../../../helpers/validate.js";
3
- import { getSchema } from "../../../config/getSchema.js";
4
-
5
- const updateWithChecks = ({ table, pk, record }) => {
6
- if (!pk) throw new Error("pk is required");
7
-
8
- const schema = getSchema(table);
9
-
10
- // merge for validation
11
- const merged = { ...record, pk };
12
-
13
- validate(schema, merged); // 🔥 reuse same validator
14
-
15
- return updateBase({ table, pk, updates: record });
16
- };
17
-
18
- export default updateWithChecks;
@@ -1,13 +0,0 @@
1
- import { getConfig } from "../../../../core/configStore.js";
2
- import { buildDataPath } from "../../../../utils/pathBuilder.js";
3
-
4
- import { readData } from "../../../helpers/file/read.js";
5
-
6
- export default ({ table }) => {
7
- const cfg = getConfig();
8
- const path = buildDataPath(cfg, table);
9
-
10
- const data = readData(path) || [];
11
-
12
- return Array.isArray(data) ? data.length : 0;
13
- };
@@ -1 +0,0 @@
1
- export { default as count } from "./count.js";
@@ -1,18 +0,0 @@
1
- import { getConfig } from "../../../core/configStore.js";
2
- import { buildDataPath } from "../../../utils/pathBuilder.js";
3
- import { readData } from "../../helpers/file/read.js";
4
-
5
- const filterByColumns = ({ table, where = {} }) => {
6
- const cfg = getConfig();
7
- const path = buildDataPath(cfg, table);
8
-
9
- const data = readData(path) || [];
10
-
11
- return data.filter(row =>
12
- Object.entries(where).every(([key, val]) =>
13
- row[key] === val
14
- )
15
- );
16
- };
17
-
18
- export default filterByColumns;
@@ -1,18 +0,0 @@
1
- import { getConfig } from "../../../core/configStore.js";
2
- import { buildDataPath } from "../../../utils/pathBuilder.js";
3
- import { getPrimaryKey } from "../../helpers/pkHelper.js";
4
- import { getSchema } from "../../config/getSchema.js";
5
- import { readData } from "../../helpers/file/read.js";
6
-
7
- const filterByPk = ({ table, id }) => {
8
- const cfg = getConfig();
9
- const schema = getSchema(table);
10
- const pk = getPrimaryKey(schema.columns);
11
-
12
- const path = buildDataPath(cfg, table);
13
- const data = readData(path);
14
-
15
- return data.filter(row => Number(row[pk]) === Number(id)) || [];
16
- };
17
-
18
- export default filterByPk;
@@ -1,14 +0,0 @@
1
- import { getConfig } from "../../../core/configStore.js";
2
- import { buildDataPath } from "../../../utils/pathBuilder.js";
3
- import { readData } from "../../helpers/file/read.js";
4
-
5
- const findAll = ({ table }) => {
6
- const config = getConfig();
7
- const path = buildDataPath(config, table);
8
-
9
- const data = readData(path);
10
-
11
- return data;
12
- };
13
-
14
- export default findAll;
@@ -1,18 +0,0 @@
1
- import { getConfig } from "../../../core/configStore.js";
2
- import { buildDataPath } from "../../../utils/pathBuilder.js";
3
- import { getPrimaryKey } from "../../helpers/pkHelper.js";
4
- import { getSchema } from "../../config/getSchema.js";
5
- import { readData } from "../../helpers/file/read.js";
6
-
7
- const findByPk = ({ table, id }) => {
8
- const cfg = getConfig();
9
- const schema = getSchema(table);
10
- const pk = getPrimaryKey(schema.columns);
11
-
12
- const path = buildDataPath(cfg, table);
13
- const data = readData(path);
14
-
15
- return data.find(row => Number(row[pk]) === Number(id)) || null;
16
- };
17
-
18
- export default findByPk;
@@ -1,8 +0,0 @@
1
- import * as aggregate from "./aggregate/index.js";
2
-
3
- export { default as findAll } from "./findAll.js";
4
- export { default as findByPk } from "./findByPk.js";
5
- export { default as filterByPk } from "./filterByPk.js";
6
- export { default as filterByColumns } from "./filterByColumns.js";
7
-
8
- export { aggregate };
@@ -1,28 +0,0 @@
1
- const insertAsIs = (mutate, tableName) => (record) =>
2
- mutate.insertAsIs({ table: tableName, record });
3
-
4
- const insertFlat = (mutate, tableName) => (record) =>
5
- mutate.insertFlat({ table: tableName, record });
6
-
7
- const insertGenPk = (mutate, tableName) => (record) =>
8
- mutate.insertGenPk({ table: tableName, record });
9
-
10
- const insertWithChecks = (mutate, tableName) => (record) =>
11
- mutate.insertWithChecks({ table: tableName, record });
12
-
13
- const deleteWithChecks = (mutate, tableName) => (pk) =>
14
- mutate.deleteWithChecks({ table: tableName, pk });
15
-
16
- const updateWithChecks = (mutate, tableName) => (pk, record) =>
17
- mutate.updateWithChecks({ table: tableName, pk, record });
18
-
19
- const buildMutate = (mutate, tableName) => ({
20
- insertAsIs: insertAsIs(mutate, tableName),
21
- insertFlat: insertFlat(mutate, tableName),
22
- insertGenPk: insertGenPk(mutate, tableName),
23
- insertWithChecks: insertWithChecks(mutate, tableName),
24
- deleteWithChecks: deleteWithChecks(mutate, tableName),
25
- updateWithChecks: updateWithChecks(mutate, tableName)
26
- });
27
-
28
- export default buildMutate;
@@ -1,27 +0,0 @@
1
- import * as aggregate from "../engine/query/aggregate/index.js";
2
-
3
- const findAll = (query, tableName) => () =>
4
- query.findAll({ table: tableName });
5
-
6
- const findByPk = (query, tableName) => (id) =>
7
- query.findByPk({ table: tableName, id });
8
-
9
- const filterByPk = (query, tableName) => (id) =>
10
- query.filterByPk({ table: tableName, id });
11
-
12
- const filterByColumns = (query, tableName) => (where) =>
13
- query.filterByColumns({ table: tableName, where });
14
-
15
- const buildQuery = (query, tableName) => ({
16
- findAll: findAll(query, tableName),
17
- findByPk: findByPk(query, tableName),
18
- filterByPk: filterByPk(query, tableName),
19
- filterByColumns: filterByColumns(query, tableName),
20
-
21
- aggregate: {
22
- count: () =>
23
- query.aggregate.count({ table: tableName })
24
- }
25
- });
26
-
27
- export default buildQuery;
@@ -1,7 +0,0 @@
1
- import fs from "fs";
2
-
3
- export const readData = (path) => {
4
- if (!fs.existsSync(path)) return [];
5
-
6
- return JSON.parse(fs.readFileSync(path, "utf-8"));
7
- };
@@ -1,5 +0,0 @@
1
- import fs from "fs";
2
-
3
- export const writeData = (path, data) => {
4
- fs.writeFileSync(path, JSON.stringify(data, null, 2));
5
- };
@@ -1,19 +0,0 @@
1
- export const getPrimaryKey = (columns) => {
2
- const pkColumn = columns.find(c => c.primary);
3
- if (!pkColumn) throw new Error("Primary key not defined");
4
- return pkColumn.field;
5
- };
6
-
7
- export const attachPrimaryKey = (record, pk, data) => {
8
- let maxId = 0;
9
-
10
- for (const row of data) {
11
- const val = Number(row[pk]) || 0;
12
- if (val > maxId) maxId = val;
13
- }
14
-
15
- return {
16
- ...record,
17
- [pk]: maxId + 1
18
- };
19
- };
@@ -1,27 +0,0 @@
1
- import required from "./validators/required.js";
2
- import type from "./validators/type.js";
3
- import minMax from "./validators/minMax.js";
4
- import length from "./validators/length.js";
5
- import enumCheck from "./validators/enum.js";
6
- import pattern from "./validators/pattern.js";
7
- import setDefault from "./validators/default.js";
8
-
9
- const validators = [required, type, minMax, length, enumCheck, pattern];
10
-
11
- const validate = (schema, record) => {
12
- if (!schema?.columns) throw new Error("Invalid schema");
13
-
14
- for (const col of schema.columns) {
15
- if (!col.isConsider) continue;
16
-
17
- setDefault(col, record); // 🔥 mutate first
18
-
19
- const value = record[col.field];
20
-
21
- for (const fn of validators) {
22
- fn(col, value, record);
23
- }
24
- }
25
- };
26
-
27
- export default validate;
@@ -1,27 +0,0 @@
1
- export const validateRecord = (record, columns, data) => {
2
- columns.forEach(col => {
3
- const value = record[col.field];
4
-
5
- if (col.required && (value === undefined || value === null || value === "")) {
6
- throw new Error(`${col.field} is required`);
7
- }
8
-
9
- if (value === undefined) return;
10
-
11
- if (col.unique && data.some(r => r[col.field] === value)) {
12
- throw new Error(`${col.field} must be unique`);
13
- }
14
- });
15
- };
16
-
17
- export const validateFilterKeys = (filter, columns) => {
18
- const validColumns = columns.map(col => col.field);
19
-
20
- const invalidKeys = Object.keys(filter).filter(
21
- key => !validColumns.includes(key)
22
- );
23
-
24
- if (invalidKeys.length > 0) {
25
- throw new Error(`Invalid columns: ${invalidKeys.join(", ")}`);
26
- };
27
- };
@@ -1,5 +0,0 @@
1
- export default (col, record) => {
2
- if (record[col.field] == null && col.defaultValue !== undefined) {
3
- record[col.field] = col.defaultValue;
4
- }
5
- };
@@ -1,7 +0,0 @@
1
- export default (col, value) => {
2
- if (value == null || !col.enum) return;
3
-
4
- if (!col.enum.includes(value)) {
5
- throw new Error(`${col.field} must be one of ${col.enum.join(", ")}`);
6
- }
7
- };
@@ -1,11 +0,0 @@
1
- export default (col, value) => {
2
- if (value == null || typeof value !== "string") return;
3
-
4
- if (col.minLength != null && value.length < col.minLength) {
5
- throw new Error(`${col.field} min length ${col.minLength}`);
6
- }
7
-
8
- if (col.maxLength != null && value.length > col.maxLength) {
9
- throw new Error(`${col.field} max length ${col.maxLength}`);
10
- }
11
- };
@@ -1,11 +0,0 @@
1
- export default (col, value) => {
2
- if (value == null) return;
3
-
4
- if (col.min != null && value < col.min) {
5
- throw new Error(`${col.field} must be >= ${col.min}`);
6
- }
7
-
8
- if (col.max != null && value > col.max) {
9
- throw new Error(`${col.field} must be <= ${col.max}`);
10
- }
11
- };
@@ -1,8 +0,0 @@
1
- export default (col, value) => {
2
- if (value == null || !col.pattern) return;
3
-
4
- const regex = new RegExp(col.pattern);
5
- if (!regex.test(value)) {
6
- throw new Error(`${col.field} format invalid`);
7
- }
8
- };
@@ -1,5 +0,0 @@
1
- export default (col, value) => {
2
- if ((col.isInput || col.primary) && (value === undefined || value === null || value === "")) {
3
- throw new Error(`${col.field} is required`);
4
- }
5
- };
@@ -1,15 +0,0 @@
1
- export default (col, value) => {
2
- if (value == null) return;
3
-
4
- if (col.type === "text" && typeof value !== "string") {
5
- throw new Error(`${col.field} must be string`);
6
- }
7
-
8
- if (col.type === "number" && typeof value !== "number") {
9
- throw new Error(`${col.field} must be number`);
10
- }
11
-
12
- if (col.type === "boolean" && typeof value !== "boolean") {
13
- throw new Error(`${col.field} must be boolean`);
14
- }
15
- };
@@ -1,8 +0,0 @@
1
- export default (col, value, tableData) => {
2
- if (!col.unique || value == null) return;
3
-
4
- const exists = tableData?.some(r => r[col.field] === value);
5
- if (exists) {
6
- throw new Error(`${col.field} must be unique`);
7
- }
8
- };
@@ -1,133 +0,0 @@
1
- {
2
- "query": {
3
- "findAll": {
4
- "args": [],
5
- "desc": "Retrieve all rows from the table",
6
- "example": [
7
- "",
8
- "const tableData = table.query.findAll();",
9
- "",
10
- "console.log('Table Data:', tableData);"
11
- ]
12
- },
13
- "findByPk": {
14
- "args": [
15
- "pk"
16
- ],
17
- "desc": "Retrieve a single row by primary key",
18
- "example": [
19
- "const table = kschema.table('LedgerNames');",
20
- "const row = table.query.findByPk(1);",
21
- "console.log('Row by PK:', row);"
22
- ]
23
- },
24
- "filterByPk": {
25
- "args": [
26
- "pk"
27
- ],
28
- "desc": "Filter rows matching primary key",
29
- "example": [
30
- "const table = kschema.table('LedgerNames');",
31
- "const rows = table.query.filterByPk(1);",
32
- "console.log('Filtered Rows (PK):', rows);"
33
- ]
34
- },
35
- "filterByColumns": {
36
- "args": [
37
- "where"
38
- ],
39
- "desc": "Filter rows using column conditions",
40
- "example": [
41
- "const table = kschema.table('LedgerNames');",
42
- "const rows = table.query.filterByColumns({ name: 'Cash' });",
43
- "console.log('Filtered Rows (Columns):', rows);"
44
- ]
45
- },
46
- "aggregate": {
47
- "count": {
48
- "args": [
49
- "column?"
50
- ],
51
- "desc": "Count rows or values of a column",
52
- "example": [
53
- "const table = kschema.table('LedgerNames');",
54
- "const total = table.query.aggregate.count();",
55
- "console.log('Total Rows Count:', total);"
56
- ]
57
- }
58
- }
59
- },
60
- "mutate": {
61
- "insertAsIs": {
62
- "args": [
63
- "record"
64
- ],
65
- "desc": "Insert record without modification",
66
- "example": [
67
- "const insertedRow = table.mutate.insertAsIs({ LedgerName: 'KeshavSoft' });",
68
- "",
69
- "console.log('Inserted record as insertAsIs : ', insertedRow);"
70
- ]
71
- },
72
- "insertFlat": {
73
- "args": [
74
- "record"
75
- ],
76
- "desc": "Insert flattened record",
77
- "example": [
78
- "const table = kschema.table('LedgerNames');",
79
- "table.mutate.insertFlat({ name: 'Bank' });",
80
- "console.log('Inserted flat record');"
81
- ]
82
- },
83
- "insertGenPk": {
84
- "args": [
85
- "record"
86
- ],
87
- "desc": "Insert record with auto-generated primary key",
88
- "example": [
89
- "const insertedRow = table.mutate.insertGenPk({ LedgerName: 'KeshavSoft' });",
90
- "",
91
- "console.log('Inserted record as insertGenPk : ', insertedRow);"
92
- ]
93
- },
94
- "insertWithChecks": {
95
- "args": [
96
- "record"
97
- ],
98
- "desc": "Insert record with validation checks",
99
- "example": [
100
- "try {",
101
- "\tconst fromInserted = table.mutate.insertWithChecks({ LedgerName: 'Keshav' });",
102
- "",
103
- "\tconsole.log('fromInserted : ', fromInserted);",
104
- "} catch (err) {",
105
- "\tconsole.log(err.message);",
106
- "};"
107
- ]
108
- },
109
- "deleteWithChecks": {
110
- "args": [
111
- "pk"
112
- ],
113
- "desc": "Delete record by primary key with validation",
114
- "example": [
115
- "const table = kschema.table('LedgerNames');",
116
- "table.mutate.deleteWithChecks(1);",
117
- "console.log('Deleted record with checks');"
118
- ]
119
- },
120
- "updateWithChecks": {
121
- "args": [
122
- "pk",
123
- "record"
124
- ],
125
- "desc": "Update record by primary key with validation",
126
- "example": [
127
- "const table = kschema.table('LedgerNames');",
128
- "table.mutate.updateWithChecks(1, { name: 'Updated Ledger' });",
129
- "console.log('Updated record with checks');"
130
- ]
131
- }
132
- }
133
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes