@things-factory/accounting 10.1.142 → 10.1.144
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.
- package/dist-server/service/account/account-match.d.ts +9 -0
- package/dist-server/service/account/account-match.js +25 -0
- package/dist-server/service/account/account-match.js.map +1 -1
- package/dist-server/service/transaction/transaction-mutation.js +4 -3
- package/dist-server/service/transaction/transaction-mutation.js.map +1 -1
- package/dist-server/service/transaction/transaction-service.js +18 -0
- package/dist-server/service/transaction/transaction-service.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/translations/en.json +2 -1
- package/translations/ko.json +2 -1
|
@@ -12,6 +12,15 @@ export declare function aliasesOf(account: Pick<AccountForMatch, 'name' | 'alias
|
|
|
12
12
|
* under an income account because a word happens to match.
|
|
13
13
|
*/
|
|
14
14
|
export declare function accountMatcher<T extends AccountForMatch>(accounts: readonly T[]): (texts: readonly (string | null | undefined)[], type?: string | null) => T | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Give each row a person writes that names no account the one its words mean (§`accountMatcher`): a confirmed line by
|
|
17
|
+
* its description then its ledger category, a forecast by its description, among the active accounts of its direction
|
|
18
|
+
* - the row's own, or the stored one for a change that does not say. A row that says `account` (an account or none)
|
|
19
|
+
* keeps what it says; a row whose words mean nothing is saved without one.
|
|
20
|
+
*/
|
|
21
|
+
export declare function assignAccounts<T extends Record<string, any>>(tx: EntityManager, domain: {
|
|
22
|
+
id: string;
|
|
23
|
+
}, inputs: T[]): Promise<T[]>;
|
|
15
24
|
export interface AccountLinking {
|
|
16
25
|
/** Rows given an account, per kind: confirmed transactions, forecasts, recurring items. */
|
|
17
26
|
linked: {
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.aliasesOf = aliasesOf;
|
|
4
4
|
exports.accountMatcher = accountMatcher;
|
|
5
|
+
exports.assignAccounts = assignAccounts;
|
|
5
6
|
exports.linkAccounts = linkAccounts;
|
|
6
7
|
const typeorm_1 = require("typeorm");
|
|
8
|
+
const account_1 = require("./account");
|
|
7
9
|
const recurring_cash_item_1 = require("../recurring-cash-item/recurring-cash-item");
|
|
8
10
|
const transaction_1 = require("../transaction/transaction");
|
|
9
11
|
const key = (text) => String(text ?? '')
|
|
@@ -40,6 +42,29 @@ function accountMatcher(accounts) {
|
|
|
40
42
|
return undefined;
|
|
41
43
|
};
|
|
42
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* Give each row a person writes that names no account the one its words mean (§`accountMatcher`): a confirmed line by
|
|
47
|
+
* its description then its ledger category, a forecast by its description, among the active accounts of its direction
|
|
48
|
+
* - the row's own, or the stored one for a change that does not say. A row that says `account` (an account or none)
|
|
49
|
+
* keeps what it says; a row whose words mean nothing is saved without one.
|
|
50
|
+
*/
|
|
51
|
+
async function assignAccounts(tx, domain, inputs) {
|
|
52
|
+
const textsOf = (row, category) => category === transaction_1.TransactionCategory.FORECAST ? [row.description] : [row.description, row.ledgerCategory];
|
|
53
|
+
const wants = (row) => row.cuFlag !== '-' && !('account' in row) && (row.description || row.ledgerCategory);
|
|
54
|
+
if (!inputs.some(wants))
|
|
55
|
+
return inputs;
|
|
56
|
+
const accounts = await tx.getRepository(account_1.Account).find({ where: { domain: { id: domain.id }, active: true } });
|
|
57
|
+
const match = accountMatcher(accounts);
|
|
58
|
+
const edited = inputs.filter(row => wants(row) && row.id && row.cuFlag !== '+').map(row => row.id);
|
|
59
|
+
const stored = new Map((edited.length ? await tx.getRepository(transaction_1.Transaction).find({ where: { domain: { id: domain.id }, id: (0, typeorm_1.In)(edited) }, select: ['id', 'type', 'category'] }) : []).map(row => [row.id, row]));
|
|
60
|
+
return inputs.map(row => {
|
|
61
|
+
if (!wants(row))
|
|
62
|
+
return row;
|
|
63
|
+
const before = stored.get(row.id);
|
|
64
|
+
const account = match(textsOf(row, row.category ?? before?.category), row.type ?? before?.type);
|
|
65
|
+
return account ? { ...row, account: { id: account.id } } : row;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
43
68
|
/**
|
|
44
69
|
* Give every row without an account the one its words mean: a confirmed transaction by its description then its
|
|
45
70
|
* ledger category, a forecast by its description, a recurring item by its name. `apply` false writes nothing. Rows a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account-match.js","sourceRoot":"","sources":["../../../server/service/account/account-match.ts"],"names":[],"mappings":";;AAyBA,8BAEC;AAMD,wCAiBC;AAcD,oCAmCC;AAnGD,qCAA+C;AAE/C,oFAA8E;AAC9E,4DAA6E;AAe7E,MAAM,GAAG,GAAG,CAAC,IAA+B,EAAE,EAAE,CAC9C,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;KACf,SAAS,CAAC,KAAK,CAAC;KAChB,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;KAC7B,WAAW,EAAE,CAAA;AAElB,4EAA4E;AAC5E,SAAgB,SAAS,CAAC,OAAkD;IAC1E,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAA;AAC/G,CAAC;AAED;;;GAGG;AACH,SAAgB,cAAc,CAA4B,QAAsB;IAC9E,MAAM,KAAK,GAAmC,EAAE,CAAA;IAChD,KAAK,MAAM,OAAO,IAAI,QAAQ;QAAE,KAAK,MAAM,KAAK,IAAI,SAAS,CAAC,OAAO,CAAC;YAAE,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC;gBAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAA;IAC7I,KAAK,CAAC,IAAI,CAA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GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;QACrF,IAAI,CAAC,KAAK;YAAE,OAAM;QAClB,KAAK,MAAM,CAAC,EAAE,EAAE,GAAG,CAAC,IAAI,MAAM;YAC5B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,GAAG;gBAAE,MAAM,EAAE,CAAC,aAAa,CAAC,MAAa,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,EAAS,CAAC,CAAA;IAC7I,CAAC,CAAA;IAED,MAAM,GAAG,CAAC,cAAc,EAAE,yBAAW,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,cAAc,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,iCAAmB,CAAC,SAAS,EAAE,CAAC,CAAA;IAClJ,MAAM,GAAG,CAAC,WAAW,EAAE,yBAAW,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,iCAAmB,CAAC,QAAQ,EAAE,CAAC,CAAA;IAC1H,MAAM,GAAG,CAAC,WAAW,EAAE,uCAAiB,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IAC7E,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { EntityManager, IsNull } from 'typeorm'\n\nimport { RecurringCashItem } from '../recurring-cash-item/recurring-cash-item'\nimport { Transaction, TransactionCategory } from '../transaction/transaction'\n\n/*\n * Which account some words mean. An account is known by its name and its aliases; the longest one contained in the\n * text wins, among accounts of the row's direction. Two different accounts matching equally long is no answer, and\n * nothing matching is no answer - a row nobody can place stays unplaced, to be listed, not filed under a catch-all.\n */\n\nexport interface AccountForMatch {\n id: string\n name: string\n type: string\n aliases?: string | null\n}\n\nconst key = (text: string | null | undefined) =>\n String(text ?? '')\n .normalize('NFC')\n .replace(/[\\s\\-_.·,()]+/g, '')\n .toLowerCase()\n\n/** An account's name and its aliases (one per line, or comma separated). */\nexport function aliasesOf(account: Pick<AccountForMatch, 'name' | 'aliases'>): string[] {\n return [account.name, ...String(account.aliases ?? '').split(/[\\n,]/)].map(one => one.trim()).filter(Boolean)\n}\n\n/**\n * A function telling which account some words mean. `type` limits it to that direction - an expense is never filed\n * under an income account because a word happens to match.\n */\nexport function accountMatcher<T extends AccountForMatch>(accounts: readonly T[]) {\n const words: { word: string; account: T }[] = []\n for (const account of accounts) for (const alias of aliasesOf(account)) if (key(alias).length >= 2) words.push({ word: key(alias), account })\n words.sort((a, b) => b.word.length - a.word.length)\n\n return (texts: readonly (string | null | undefined)[], type?: string | null): T | undefined => {\n for (const text of texts) {\n const hay = key(text)\n if (!hay) continue\n const hits = words.filter(one => (!type || one.account.type === type) && hay.includes(one.word))\n if (!hits.length) continue\n const longest = hits[0].word.length\n const top = new Set(hits.filter(one => one.word.length === longest).map(one => one.account.id))\n return top.size === 1 ? hits[0].account : undefined\n }\n return undefined\n }\n}\n\nexport interface AccountLinking {\n /** Rows given an account, per kind: confirmed transactions, forecasts, recurring items. */\n linked: { transactions: number; forecasts: number; recurring: number }\n /** The words of confirmed transactions no account matched. */\n unmatched: string[]\n}\n\n/**\n * Give every row without an account the one its words mean: a confirmed transaction by its description then its\n * ledger category, a forecast by its description, a recurring item by its name. `apply` false writes nothing. Rows a\n * person already filed are left alone.\n */\nexport async function linkAccounts(\n tx: EntityManager,\n domain: { id: string },\n match: ReturnType<typeof accountMatcher>,\n apply: boolean\n): Promise<AccountLinking> {\n const report: AccountLinking = { linked: { transactions: 0, forecasts: 0, recurring: 0 }, unmatched: [] }\n\n const run = async <T extends { id: string }>(\n label: keyof AccountLinking['linked'],\n entity: new () => T,\n texts: (row: T) => (string | null | undefined)[],\n typeOf: (row: T) => string | null,\n scope: Record<string, any> = {}\n ) => {\n const rows = (await tx.getRepository(entity as any).find({ where: { domain: { id: domain.id }, ...scope, account: IsNull() } as any })) as T[]\n const groups = new Map<string, string[]>()\n for (const row of rows) {\n const account = match(texts(row), typeOf(row))\n if (!account) {\n if (label === 'transactions') report.unmatched.push(String(texts(row)[0] ?? ''))\n continue\n }\n groups.set(account.id, [...(groups.get(account.id) ?? []), row.id])\n }\n report.linked[label] = [...groups.values()].reduce((sum, ids) => sum + ids.length, 0)\n if (!apply) return\n for (const [id, ids] of groups)\n for (let i = 0; i < ids.length; i += 500) await tx.getRepository(entity as any).update(ids.slice(i, i + 500), { account: { id } } as any)\n }\n\n await run('transactions', Transaction, row => [row.description, row.ledgerCategory], row => row.type, { category: TransactionCategory.CONFIRMED })\n await run('forecasts', Transaction, row => [row.description], row => row.type, { category: TransactionCategory.FORECAST })\n await run('recurring', RecurringCashItem, row => [row.name], row => row.type)\n return report\n}\n"]}
|
|
1
|
+
{"version":3,"file":"account-match.js","sourceRoot":"","sources":["../../../server/service/account/account-match.ts"],"names":[],"mappings":";;AA2BA,8BAEC;AAMD,wCAiBC;AAQD,wCAkBC;AAcD,oCAmCC;AA/HD,qCAAmD;AAEnD,uCAAmC;AAEnC,oFAA8E;AAC9E,4DAA6E;AAe7E,MAAM,GAAG,GAAG,CAAC,IAA+B,EAAE,EAAE,CAC9C,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;KACf,SAAS,CAAC,KAAK,CAAC;KAChB,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;KAC7B,WAAW,EAAE,CAAA;AAElB,4EAA4E;AAC5E,SAAgB,SAAS,CAAC,OAAkD;IAC1E,OAAO,CAAC,OAAO,CAAC,IAAI,E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,GAAG,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;IAC7E,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { EntityManager, In, IsNull } from 'typeorm'\n\nimport { Account } from './account'\n\nimport { RecurringCashItem } from '../recurring-cash-item/recurring-cash-item'\nimport { Transaction, TransactionCategory } from '../transaction/transaction'\n\n/*\n * Which account some words mean. An account is known by its name and its aliases; the longest one contained in the\n * text wins, among accounts of the row's direction. Two different accounts matching equally long is no answer, and\n * nothing matching is no answer - a row nobody can place stays unplaced, to be listed, not filed under a catch-all.\n */\n\nexport interface AccountForMatch {\n id: string\n name: string\n type: string\n aliases?: string | null\n}\n\nconst key = (text: string | null | undefined) =>\n String(text ?? '')\n .normalize('NFC')\n .replace(/[\\s\\-_.·,()]+/g, '')\n .toLowerCase()\n\n/** An account's name and its aliases (one per line, or comma separated). */\nexport function aliasesOf(account: Pick<AccountForMatch, 'name' | 'aliases'>): string[] {\n return [account.name, ...String(account.aliases ?? '').split(/[\\n,]/)].map(one => one.trim()).filter(Boolean)\n}\n\n/**\n * A function telling which account some words mean. `type` limits it to that direction - an expense is never filed\n * under an income account because a word happens to match.\n */\nexport function accountMatcher<T extends AccountForMatch>(accounts: readonly T[]) {\n const words: { word: string; account: T }[] = []\n for (const account of accounts) for (const alias of aliasesOf(account)) if (key(alias).length >= 2) words.push({ word: key(alias), account })\n words.sort((a, b) => b.word.length - a.word.length)\n\n return (texts: readonly (string | null | undefined)[], type?: string | null): T | undefined => {\n for (const text of texts) {\n const hay = key(text)\n if (!hay) continue\n const hits = words.filter(one => (!type || one.account.type === type) && hay.includes(one.word))\n if (!hits.length) continue\n const longest = hits[0].word.length\n const top = new Set(hits.filter(one => one.word.length === longest).map(one => one.account.id))\n return top.size === 1 ? hits[0].account : undefined\n }\n return undefined\n }\n}\n\n/**\n * Give each row a person writes that names no account the one its words mean (§`accountMatcher`): a confirmed line by\n * its description then its ledger category, a forecast by its description, among the active accounts of its direction\n * - the row's own, or the stored one for a change that does not say. A row that says `account` (an account or none)\n * keeps what it says; a row whose words mean nothing is saved without one.\n */\nexport async function assignAccounts<T extends Record<string, any>>(tx: EntityManager, domain: { id: string }, inputs: T[]): Promise<T[]> {\n const textsOf = (row: Record<string, any>, category?: string) =>\n category === TransactionCategory.FORECAST ? [row.description] : [row.description, row.ledgerCategory]\n const wants = (row: Record<string, any>) => row.cuFlag !== '-' && !('account' in row) && (row.description || row.ledgerCategory)\n if (!inputs.some(wants)) return inputs\n\n const accounts = await tx.getRepository(Account).find({ where: { domain: { id: domain.id }, active: true } as any })\n const match = accountMatcher(accounts)\n const edited = inputs.filter(row => wants(row) && row.id && row.cuFlag !== '+').map(row => row.id)\n const stored = new Map(\n (edited.length ? await tx.getRepository(Transaction).find({ where: { domain: { id: domain.id }, id: In(edited) } as any, select: ['id', 'type', 'category'] as any }) : []).map(row => [row.id, row])\n )\n return inputs.map(row => {\n if (!wants(row)) return row\n const before = stored.get(row.id)\n const account = match(textsOf(row, row.category ?? before?.category), row.type ?? before?.type)\n return account ? { ...row, account: { id: account.id } } : row\n })\n}\n\nexport interface AccountLinking {\n /** Rows given an account, per kind: confirmed transactions, forecasts, recurring items. */\n linked: { transactions: number; forecasts: number; recurring: number }\n /** The words of confirmed transactions no account matched. */\n unmatched: string[]\n}\n\n/**\n * Give every row without an account the one its words mean: a confirmed transaction by its description then its\n * ledger category, a forecast by its description, a recurring item by its name. `apply` false writes nothing. Rows a\n * person already filed are left alone.\n */\nexport async function linkAccounts(\n tx: EntityManager,\n domain: { id: string },\n match: ReturnType<typeof accountMatcher>,\n apply: boolean\n): Promise<AccountLinking> {\n const report: AccountLinking = { linked: { transactions: 0, forecasts: 0, recurring: 0 }, unmatched: [] }\n\n const run = async <T extends { id: string }>(\n label: keyof AccountLinking['linked'],\n entity: new () => T,\n texts: (row: T) => (string | null | undefined)[],\n typeOf: (row: T) => string | null,\n scope: Record<string, any> = {}\n ) => {\n const rows = (await tx.getRepository(entity as any).find({ where: { domain: { id: domain.id }, ...scope, account: IsNull() } as any })) as T[]\n const groups = new Map<string, string[]>()\n for (const row of rows) {\n const account = match(texts(row), typeOf(row))\n if (!account) {\n if (label === 'transactions') report.unmatched.push(String(texts(row)[0] ?? ''))\n continue\n }\n groups.set(account.id, [...(groups.get(account.id) ?? []), row.id])\n }\n report.linked[label] = [...groups.values()].reduce((sum, ids) => sum + ids.length, 0)\n if (!apply) return\n for (const [id, ids] of groups)\n for (let i = 0; i < ids.length; i += 500) await tx.getRepository(entity as any).update(ids.slice(i, i + 500), { account: { id } } as any)\n }\n\n await run('transactions', Transaction, row => [row.description, row.ledgerCategory], row => row.type, { category: TransactionCategory.CONFIRMED })\n await run('forecasts', Transaction, row => [row.description], row => row.type, { category: TransactionCategory.FORECAST })\n await run('recurring', RecurringCashItem, row => [row.name], row => row.type)\n return report\n}\n"]}
|
|
@@ -5,22 +5,23 @@ const tslib_1 = require("tslib");
|
|
|
5
5
|
const type_graphql_1 = require("type-graphql");
|
|
6
6
|
const shell_1 = require("@things-factory/shell");
|
|
7
7
|
const transaction_1 = require("./transaction");
|
|
8
|
+
const account_match_1 = require("../account/account-match");
|
|
8
9
|
const transaction_service_1 = require("./transaction-service");
|
|
9
10
|
const transaction_type_1 = require("./transaction-type");
|
|
10
11
|
let TransactionMutation = class TransactionMutation {
|
|
11
12
|
async createTransaction(transaction, context) {
|
|
12
13
|
const { domain, user, tx } = context.state;
|
|
13
|
-
const [saved] = await (0, transaction_service_1.saveTransactions)(tx, domain, user, [{ ...transaction, cuFlag: '+' }]);
|
|
14
|
+
const [saved] = await (0, transaction_service_1.saveTransactions)(tx, domain, user, await (0, account_match_1.assignAccounts)(tx, domain, [{ ...transaction, cuFlag: '+' }]));
|
|
14
15
|
return saved;
|
|
15
16
|
}
|
|
16
17
|
async updateTransaction(id, patch, context) {
|
|
17
18
|
const { domain, user, tx } = context.state;
|
|
18
|
-
const [saved] = await (0, transaction_service_1.saveTransactions)(tx, domain, user, [{ ...patch, id, cuFlag: 'M' }]);
|
|
19
|
+
const [saved] = await (0, transaction_service_1.saveTransactions)(tx, domain, user, await (0, account_match_1.assignAccounts)(tx, domain, [{ ...patch, id, cuFlag: 'M' }]));
|
|
19
20
|
return saved;
|
|
20
21
|
}
|
|
21
22
|
async updateMultipleTransaction(patches, context) {
|
|
22
23
|
const { domain, user, tx } = context.state;
|
|
23
|
-
return await (0, transaction_service_1.saveTransactions)(tx, domain, user, patches);
|
|
24
|
+
return await (0, transaction_service_1.saveTransactions)(tx, domain, user, await (0, account_match_1.assignAccounts)(tx, domain, patches));
|
|
24
25
|
}
|
|
25
26
|
async deleteTransaction(id, context) {
|
|
26
27
|
const { domain, user, tx } = context.state;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-mutation.js","sourceRoot":"","sources":["../../../server/service/transaction/transaction-mutation.ts"],"names":[],"mappings":";;;;AAAA,+CAAqF;AAErF,iDAAqD;AAErD,+CAA2C;AAC3C,+DAAwD;AACxD,yDAAqE;AAI9D,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAIxB,AAAN,KAAK,CAAC,iBAAiB,CACD,WAA2B,EACxC,OAAwB;QAE/B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,OAAO,CAAC,KAAK,CAAA;QAC1C,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,IAAA,sCAAgB,EAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,GAAG,WAAW,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,CAAA;
|
|
1
|
+
{"version":3,"file":"transaction-mutation.js","sourceRoot":"","sources":["../../../server/service/transaction/transaction-mutation.ts"],"names":[],"mappings":";;;;AAAA,+CAAqF;AAErF,iDAAqD;AAErD,+CAA2C;AAC3C,4DAAyD;AACzD,+DAAwD;AACxD,yDAAqE;AAI9D,IAAM,mBAAmB,GAAzB,MAAM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\n\nimport { Transaction } from './transaction'\nimport { assignAccounts } from '../account/account-match'\nimport { saveTransactions } from './transaction-service'\nimport { NewTransaction, TransactionPatch } from './transaction-type'\n\n@Resolver(Transaction)\n@UseMiddleware(SpeakRefusals)\nexport class TransactionMutation {\n @Directive('@transaction')\n @Directive('@privilege(category: \"accounting\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Transaction, { description: 'To create new Transaction' })\n async createTransaction(\n @Arg('transaction') transaction: NewTransaction,\n @Ctx() context: ResolverContext\n ): Promise<Transaction> {\n const { domain, user, tx } = context.state\n const [saved] = await saveTransactions(tx, domain, user, await assignAccounts(tx, domain, [{ ...transaction, cuFlag: '+' }]))\n\n return saved\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"accounting\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Transaction, { description: 'To modify Transaction information' })\n async updateTransaction(\n @Arg('id') id: string,\n @Arg('patch') patch: TransactionPatch,\n @Ctx() context: ResolverContext\n ): Promise<Transaction> {\n const { domain, user, tx } = context.state\n const [saved] = await saveTransactions(tx, domain, user, await assignAccounts(tx, domain, [{ ...patch, id, cuFlag: 'M' }]))\n\n return saved\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"accounting\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => [Transaction], { description: 'To add, modify and delete multiple Transactions' })\n async updateMultipleTransaction(\n @Arg('patches', type => [TransactionPatch]) patches: TransactionPatch[],\n @Ctx() context: ResolverContext\n ): Promise<Transaction[]> {\n const { domain, user, tx } = context.state\n\n return await saveTransactions(tx, domain, user, await assignAccounts(tx, domain, patches))\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"accounting\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'To delete Transaction' })\n async deleteTransaction(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<boolean> {\n const { domain, user, tx } = context.state\n await saveTransactions(tx, domain, user, [{ id, cuFlag: '-' }])\n\n return true\n }\n\n @Directive('@transaction')\n @Directive('@privilege(category: \"accounting\", privilege: \"mutation\", domainOwnerGranted: true)')\n @Mutation(returns => Boolean, { description: 'To delete multiple Transactions' })\n async deleteTransactions(\n @Arg('ids', type => [String]) ids: string[],\n @Ctx() context: ResolverContext\n ): Promise<boolean> {\n const { domain, user, tx } = context.state\n await saveTransactions(\n tx,\n domain,\n user,\n ids.map(id => ({ id, cuFlag: '-' }))\n )\n\n return true\n }\n}\n"]}
|
|
@@ -4,7 +4,11 @@ exports.protectBankFacts = protectBankFacts;
|
|
|
4
4
|
exports.saveTransactions = saveTransactions;
|
|
5
5
|
const typeorm_1 = require("typeorm");
|
|
6
6
|
const shell_1 = require("@things-factory/shell");
|
|
7
|
+
const biz_base_1 = require("@things-factory/biz-base");
|
|
8
|
+
const account_1 = require("../account/account");
|
|
7
9
|
const bank_account_1 = require("../bank-account/bank-account");
|
|
10
|
+
const bank_statement_1 = require("../bank-statement/bank-statement");
|
|
11
|
+
const recurring_cash_item_1 = require("../recurring-cash-item/recurring-cash-item");
|
|
8
12
|
const cash_flow_type_1 = require("../cash-flow-type");
|
|
9
13
|
const payment_1 = require("../payment/payment");
|
|
10
14
|
const payment_service_1 = require("../payment/payment-service");
|
|
@@ -29,6 +33,13 @@ function protectBankFacts(current, patch) {
|
|
|
29
33
|
throw new shell_1.Refusal('bank-facts-locked', {}, 'Bank facts can only be updated from a statement; annotations remain editable');
|
|
30
34
|
}
|
|
31
35
|
}
|
|
36
|
+
/** The rows a transaction names besides its bank account, each of the caller's domain. */
|
|
37
|
+
const REFERENCES = [
|
|
38
|
+
['account', () => account_1.Account],
|
|
39
|
+
['counterparty', () => biz_base_1.Counterparty],
|
|
40
|
+
['recurringItem', () => recurring_cash_item_1.RecurringCashItem],
|
|
41
|
+
['bankStatement', () => bank_statement_1.BankStatement]
|
|
42
|
+
];
|
|
32
43
|
/** What its payments depend on - they are checked again, and their owners follow, when one of these changes. */
|
|
33
44
|
const FACTS = ['amount', 'type', 'currency', 'transactionDate'];
|
|
34
45
|
/**
|
|
@@ -47,6 +58,9 @@ function rowOf(input, current) {
|
|
|
47
58
|
throw new shell_1.Refusal('transaction-type-required', {}, 'type: money in or money out');
|
|
48
59
|
if (!current && (row.amount === undefined || row.amount === null))
|
|
49
60
|
row.amount = 0;
|
|
61
|
+
/* An emptied currency is won, the column's own default - a row is never without one. */
|
|
62
|
+
if ('currency' in row && !row.currency)
|
|
63
|
+
row.currency = 'KRW';
|
|
50
64
|
if (category === transaction_1.TransactionCategory.CONFIRMED) {
|
|
51
65
|
const period = (0, transaction_period_1.yearMonthOf)(merged.transactionDate);
|
|
52
66
|
if (!period)
|
|
@@ -124,6 +138,10 @@ async function saveTransactions(tx, domain, user, inputs) {
|
|
|
124
138
|
if (account.currency)
|
|
125
139
|
row.currency = account.currency;
|
|
126
140
|
}
|
|
141
|
+
/* What a row names is the caller's own - never another domain's account, counterparty, item or statement. */
|
|
142
|
+
for (const [field, entity] of REFERENCES)
|
|
143
|
+
if (row[field]?.id && !(await tx.getRepository(entity()).findOne({ where: { domain: { id: domain.id }, id: row[field].id }, withDeleted: true })))
|
|
144
|
+
throw new shell_1.Refusal('transaction-reference-not-found', { field }, `${field} was not found - reload and try again`);
|
|
127
145
|
if (row.bankFingerprint) {
|
|
128
146
|
const twin = await repo.findOne({ where: { domain: { id: domain.id }, bankFingerprint: row.bankFingerprint } });
|
|
129
147
|
if (twin && twin.id !== current?.id)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-service.js","sourceRoot":"","sources":["../../../server/service/transaction/transaction-service.ts"],"names":[],"mappings":";;AA6BA,4CAYC;AA0ED,4CA0EC;AA7LD,qCAA2C;AAE3C,iDAA+C;AAE/C,+DAA0D;AAC1D,sDAAgD;AAChD,gDAA4C;AAC5C,gEAAgE;AAChE,gEAA0E;AAC1E,+CAAmG;AACnG,6DAA+D;AAe/D,uHAAuH;AACvH,MAAM,UAAU,GAAG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tC,MAAM,IAAA,iCAAe,EAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;QAC9E,KAAK,MAAM,IAAI,IAAI,IAAA,8BAAY,GAAE;YAAE,MAAM,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;QACpI,KAAK,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,KAAK;YACtC,MAAM,IAAA,iCAAe,EAAC,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;IAC/E,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { EntityManager, In } from 'typeorm'\n\nimport { Refusal } from '@things-factory/shell'\n\nimport { BankAccount } from '../bank-account/bank-account'\nimport { CashFlowType } from '../cash-flow-type'\nimport { Payment } from '../payment/payment'\nimport { checkPaymentsWithin } from '../payment/payment-service'\nimport { paymentRules, paymentTargetOf } from '../payment/payment-targets'\nimport { ForecastStatus, Transaction, TransactionCategory, TransactionSource } from './transaction'\nimport { forecastDay, yearMonthOf } from './transaction-period'\n\n/** A transaction as a module writes it: what a person may write, and the facts a bank statement gives. */\nexport type TransactionInput = Partial<\n Omit<Transaction, 'bankAccount' | 'account' | 'counterparty' | 'recurringItem' | 'bankStatement'>\n> & {\n id?: string\n cuFlag?: string\n bankAccount?: { id: string } | null\n account?: { id: string } | null\n counterparty?: { id: string } | null\n recurringItem?: { id: string } | null\n bankStatement?: { id: string } | null\n}\n\n/** What a bank statement says of a line - changed only by a statement; what a person writes beside them stays open. */\nconst BANK_FACTS = ['transactionDate', 'type', 'amount', 'balance', 'currency', 'bankAccount'] as const\n\n/** A line that came from a bank statement keeps the statement's facts (§`BANK_FACTS`). */\nexport function protectBankFacts(current: Partial<Transaction> & { bankAccountId?: string }, patch: Record<string, any>): void {\n if (current.source !== TransactionSource.BANK_STATEMENT) return\n for (const field of BANK_FACTS) {\n if (!(field in patch)) continue\n const before = field === 'bankAccount' ? current.bankAccountId ?? current.bankAccount?.id : (current as any)[field]\n const after = field === 'bankAccount' ? patch.bankAccount?.id : patch[field]\n const equal = ['amount', 'balance'].includes(field)\n ? (before == null && after == null) || (before != null && after != null && Number(before) === Number(after))\n : before === after\n if (!equal)\n throw new Refusal('bank-facts-locked', {}, 'Bank facts can only be updated from a statement; annotations remain editable')\n }\n}\n\n/** What its payments depend on - they are checked again, and their owners follow, when one of these changes. */\nconst FACTS = ['amount', 'type', 'currency', 'transactionDate'] as const\n\n/**\n * The row a patch writes over the current one: a confirmed transaction has a day and takes its year and month from it;\n * a forecast has a year and a month, and the day its timing names.\n */\nfunction rowOf(input: TransactionInput, current: Transaction | undefined): Record<string, any> {\n const { id, cuFlag, ...fields } = input\n const row: Record<string, any> = { ...fields }\n const merged = { ...current, ...row }\n const category = merged.category ?? TransactionCategory.CONFIRMED\n row.category = category\n\n if (!current && !row.type) throw new Refusal('transaction-type-required', {}, 'type: money in or money out')\n if (row.type !== undefined && !Object.values(CashFlowType).includes(row.type))\n throw new Refusal('transaction-type-required', {}, 'type: money in or money out')\n if (!current && (row.amount === undefined || row.amount === null)) row.amount = 0\n\n if (category === TransactionCategory.CONFIRMED) {\n const period = yearMonthOf(merged.transactionDate)\n if (!period)\n throw new Refusal(\n 'transaction-date-required',\n { value: merged.transactionDate ?? '' },\n 'transactionDate: YYYY-MM-DD'\n )\n Object.assign(row, period, { status: null })\n } else {\n const [year, month] = [Number(merged.year), Number(merged.month)]\n if (!year) throw new Refusal('forecast-year-required', {}, 'year: the year it is planned in')\n if (!(month >= 1 && month <= 12))\n throw new Refusal('month-out-of-range', { month: merged.month ?? '' }, 'month: must be 1 to 12')\n if (!String(merged.description ?? '').trim())\n throw new Refusal('forecast-description-required', {}, 'description: what is planned')\n Object.assign(row, { year, month, transactionDate: forecastDay(year, month, merged.timing) })\n if (!merged.status) row.status = ForecastStatus.PLANNED\n }\n\n if (\n merged.probability !== undefined &&\n merged.probability !== null &&\n !(merged.probability >= 0 && merged.probability <= 100)\n ) {\n throw new Refusal('probability-out-of-range', {}, 'probability: must be 0 to 100')\n }\n\n return row\n}\n\n/** The payments on these transactions, and the transfers into them, by target kind. */\nasync function paymentsOn(tx: EntityManager, domain: { id: string }, ids: string[]): Promise<Payment[]> {\n if (!ids.length) return []\n const repo = tx.getRepository(Payment)\n return [\n ...(await repo.find({\n where: { domain: { id: domain.id }, transaction: { id: In(ids) } },\n relations: ['transaction']\n })),\n ...(await repo.find({\n where: { domain: { id: domain.id }, targetType: 'Transaction', targetId: In(ids) },\n relations: ['transaction']\n }))\n ]\n}\n\n/**\n * Apply rows to a domain's transactions: `+` (or no id) adds, `M` changes, `-` deletes (softly - a financial row\n * that was deleted stays readable). A transaction that pays something, or is paid, is unlinked before it is\n * deleted; when its money changes, its payments are checked again - the general rule and each target kind's own.\n * A line from a bank statement keeps the statement's facts (§`protectBankFacts`).\n */\nexport async function saveTransactions(\n tx: EntityManager,\n domain: { id: string },\n user: any,\n inputs: TransactionInput[]\n): Promise<Transaction[]> {\n const repo = tx.getRepository(Transaction)\n\n const deletes = [...new Set(inputs.filter(one => one.cuFlag === '-' && one.id).map(one => one.id!))]\n if (deletes.length) {\n const found = await repo.find({ where: { domain: { id: domain.id }, id: In(deletes) } })\n if (found.length !== deletes.length)\n throw new Refusal('transaction-not-found', {}, 'a transaction was not found - reload and try again')\n if ((await paymentsOn(tx, domain, deletes)).length)\n throw new Refusal('transaction-has-payments', {}, 'unlink what the transaction paid before deleting it')\n await repo.softRemove(found)\n }\n\n const saved: Transaction[] = []\n const factsChanged: string[] = []\n for (const input of inputs.filter(one => one.cuFlag !== '-')) {\n const isNew = !input.id || input.cuFlag === '+'\n const current = isNew ? undefined : await repo.findOne({ where: { domain: { id: domain.id }, id: input.id } })\n if (!isNew && !current)\n throw new Refusal('transaction-not-found', {}, 'a transaction was not found - reload and try again')\n\n if (current) protectBankFacts(current, input)\n const row = rowOf(input, current)\n if (row.bankAccount?.id && !('currency' in input)) {\n const account = await tx\n .getRepository(BankAccount)\n .findOne({ where: { domain: { id: domain.id }, id: row.bankAccount.id } })\n if (!account)\n throw new Refusal('bank-account-not-found', {}, 'the bank account was not found - reload and try again')\n if (account.currency) row.currency = account.currency\n }\n\n if (row.bankFingerprint) {\n const twin = await repo.findOne({ where: { domain: { id: domain.id }, bankFingerprint: row.bankFingerprint } })\n if (twin && twin.id !== current?.id)\n throw new Refusal(\n 'bank-line-twice',\n { day: twin.transactionDate ?? '' },\n 'this bank line is already in the books'\n )\n }\n\n const written = await repo.save({ ...(current ?? { domain, creator: user }), ...row, updater: user } as Transaction)\n if (current && FACTS.some(field => field in row && row[field] !== (current as any)[field]))\n factsChanged.push(current.id)\n saved.push(written)\n }\n\n if (factsChanged.length) {\n const payments = await paymentsOn(tx, domain, factsChanged)\n await checkPaymentsWithin(\n tx,\n domain,\n payments.map(one => one.transaction.id)\n )\n const kinds = new Map<string, Payment[]>()\n for (const payment of payments) kinds.set(payment.targetType, [...(kinds.get(payment.targetType) ?? []), payment])\n const touchedOf = (ofKind: Payment[]) => ({\n targetIds: [...new Set(ofKind.map(one => one.targetId))],\n transactionIds: [...new Set(ofKind.map(one => one.transaction.id))]\n })\n for (const [targetType, ofKind] of kinds)\n await paymentTargetOf(targetType)?.validate?.(tx, domain, touchedOf(ofKind))\n for (const rule of paymentRules()) await rule(tx, domain, { transactionIds: [...new Set(payments.map(one => one.transaction.id))] })\n for (const [targetType, ofKind] of kinds)\n await paymentTargetOf(targetType)?.onSaved?.(tx, domain, touchedOf(ofKind))\n }\n\n return saved\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transaction-service.js","sourceRo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,UAAU,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;QAC9E,KAAK,MAAM,IAAI,IAAI,IAAA,8BAAY,GAAE;YAAE,MAAM,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,cAAc,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAA;QACpI,KAAK,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,KAAK;YACtC,MAAM,IAAA,iCAAe,EAAC,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;IAC/E,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { EntityManager, In } from 'typeorm'\n\nimport { Refusal } from '@things-factory/shell'\n\nimport { Counterparty } from '@things-factory/biz-base'\n\nimport { Account } from '../account/account'\nimport { BankAccount } from '../bank-account/bank-account'\nimport { BankStatement } from '../bank-statement/bank-statement'\nimport { RecurringCashItem } from '../recurring-cash-item/recurring-cash-item'\nimport { CashFlowType } from '../cash-flow-type'\nimport { Payment } from '../payment/payment'\nimport { checkPaymentsWithin } from '../payment/payment-service'\nimport { paymentRules, paymentTargetOf } from '../payment/payment-targets'\nimport { ForecastStatus, Transaction, TransactionCategory, TransactionSource } from './transaction'\nimport { forecastDay, yearMonthOf } from './transaction-period'\n\n/** A transaction as a module writes it: what a person may write, and the facts a bank statement gives. */\nexport type TransactionInput = Partial<\n Omit<Transaction, 'bankAccount' | 'account' | 'counterparty' | 'recurringItem' | 'bankStatement'>\n> & {\n id?: string\n cuFlag?: string\n bankAccount?: { id: string } | null\n account?: { id: string } | null\n counterparty?: { id: string } | null\n recurringItem?: { id: string } | null\n bankStatement?: { id: string } | null\n}\n\n/** What a bank statement says of a line - changed only by a statement; what a person writes beside them stays open. */\nconst BANK_FACTS = ['transactionDate', 'type', 'amount', 'balance', 'currency', 'bankAccount'] as const\n\n/** A line that came from a bank statement keeps the statement's facts (§`BANK_FACTS`). */\nexport function protectBankFacts(current: Partial<Transaction> & { bankAccountId?: string }, patch: Record<string, any>): void {\n if (current.source !== TransactionSource.BANK_STATEMENT) return\n for (const field of BANK_FACTS) {\n if (!(field in patch)) continue\n const before = field === 'bankAccount' ? current.bankAccountId ?? current.bankAccount?.id : (current as any)[field]\n const after = field === 'bankAccount' ? patch.bankAccount?.id : patch[field]\n const equal = ['amount', 'balance'].includes(field)\n ? (before == null && after == null) || (before != null && after != null && Number(before) === Number(after))\n : before === after\n if (!equal)\n throw new Refusal('bank-facts-locked', {}, 'Bank facts can only be updated from a statement; annotations remain editable')\n }\n}\n\n/** The rows a transaction names besides its bank account, each of the caller's domain. */\nconst REFERENCES: [string, () => any][] = [\n ['account', () => Account],\n ['counterparty', () => Counterparty],\n ['recurringItem', () => RecurringCashItem],\n ['bankStatement', () => BankStatement]\n]\n\n/** What its payments depend on - they are checked again, and their owners follow, when one of these changes. */\nconst FACTS = ['amount', 'type', 'currency', 'transactionDate'] as const\n\n/**\n * The row a patch writes over the current one: a confirmed transaction has a day and takes its year and month from it;\n * a forecast has a year and a month, and the day its timing names.\n */\nfunction rowOf(input: TransactionInput, current: Transaction | undefined): Record<string, any> {\n const { id, cuFlag, ...fields } = input\n const row: Record<string, any> = { ...fields }\n const merged = { ...current, ...row }\n const category = merged.category ?? TransactionCategory.CONFIRMED\n row.category = category\n\n if (!current && !row.type) throw new Refusal('transaction-type-required', {}, 'type: money in or money out')\n if (row.type !== undefined && !Object.values(CashFlowType).includes(row.type))\n throw new Refusal('transaction-type-required', {}, 'type: money in or money out')\n if (!current && (row.amount === undefined || row.amount === null)) row.amount = 0\n /* An emptied currency is won, the column's own default - a row is never without one. */\n if ('currency' in row && !row.currency) row.currency = 'KRW'\n\n if (category === TransactionCategory.CONFIRMED) {\n const period = yearMonthOf(merged.transactionDate)\n if (!period)\n throw new Refusal(\n 'transaction-date-required',\n { value: merged.transactionDate ?? '' },\n 'transactionDate: YYYY-MM-DD'\n )\n Object.assign(row, period, { status: null })\n } else {\n const [year, month] = [Number(merged.year), Number(merged.month)]\n if (!year) throw new Refusal('forecast-year-required', {}, 'year: the year it is planned in')\n if (!(month >= 1 && month <= 12))\n throw new Refusal('month-out-of-range', { month: merged.month ?? '' }, 'month: must be 1 to 12')\n if (!String(merged.description ?? '').trim())\n throw new Refusal('forecast-description-required', {}, 'description: what is planned')\n Object.assign(row, { year, month, transactionDate: forecastDay(year, month, merged.timing) })\n if (!merged.status) row.status = ForecastStatus.PLANNED\n }\n\n if (\n merged.probability !== undefined &&\n merged.probability !== null &&\n !(merged.probability >= 0 && merged.probability <= 100)\n ) {\n throw new Refusal('probability-out-of-range', {}, 'probability: must be 0 to 100')\n }\n\n return row\n}\n\n/** The payments on these transactions, and the transfers into them, by target kind. */\nasync function paymentsOn(tx: EntityManager, domain: { id: string }, ids: string[]): Promise<Payment[]> {\n if (!ids.length) return []\n const repo = tx.getRepository(Payment)\n return [\n ...(await repo.find({\n where: { domain: { id: domain.id }, transaction: { id: In(ids) } },\n relations: ['transaction']\n })),\n ...(await repo.find({\n where: { domain: { id: domain.id }, targetType: 'Transaction', targetId: In(ids) },\n relations: ['transaction']\n }))\n ]\n}\n\n/**\n * Apply rows to a domain's transactions: `+` (or no id) adds, `M` changes, `-` deletes (softly - a financial row\n * that was deleted stays readable). A transaction that pays something, or is paid, is unlinked before it is\n * deleted; when its money changes, its payments are checked again - the general rule and each target kind's own.\n * A line from a bank statement keeps the statement's facts (§`protectBankFacts`).\n */\nexport async function saveTransactions(\n tx: EntityManager,\n domain: { id: string },\n user: any,\n inputs: TransactionInput[]\n): Promise<Transaction[]> {\n const repo = tx.getRepository(Transaction)\n\n const deletes = [...new Set(inputs.filter(one => one.cuFlag === '-' && one.id).map(one => one.id!))]\n if (deletes.length) {\n const found = await repo.find({ where: { domain: { id: domain.id }, id: In(deletes) } })\n if (found.length !== deletes.length)\n throw new Refusal('transaction-not-found', {}, 'a transaction was not found - reload and try again')\n if ((await paymentsOn(tx, domain, deletes)).length)\n throw new Refusal('transaction-has-payments', {}, 'unlink what the transaction paid before deleting it')\n await repo.softRemove(found)\n }\n\n const saved: Transaction[] = []\n const factsChanged: string[] = []\n for (const input of inputs.filter(one => one.cuFlag !== '-')) {\n const isNew = !input.id || input.cuFlag === '+'\n const current = isNew ? undefined : await repo.findOne({ where: { domain: { id: domain.id }, id: input.id } })\n if (!isNew && !current)\n throw new Refusal('transaction-not-found', {}, 'a transaction was not found - reload and try again')\n\n if (current) protectBankFacts(current, input)\n const row = rowOf(input, current)\n if (row.bankAccount?.id && !('currency' in input)) {\n const account = await tx\n .getRepository(BankAccount)\n .findOne({ where: { domain: { id: domain.id }, id: row.bankAccount.id } })\n if (!account)\n throw new Refusal('bank-account-not-found', {}, 'the bank account was not found - reload and try again')\n if (account.currency) row.currency = account.currency\n }\n\n /* What a row names is the caller's own - never another domain's account, counterparty, item or statement. */\n for (const [field, entity] of REFERENCES)\n if (row[field]?.id && !(await tx.getRepository(entity()).findOne({ where: { domain: { id: domain.id }, id: row[field].id } as any, withDeleted: true })))\n throw new Refusal('transaction-reference-not-found', { field }, `${field} was not found - reload and try again`)\n\n if (row.bankFingerprint) {\n const twin = await repo.findOne({ where: { domain: { id: domain.id }, bankFingerprint: row.bankFingerprint } })\n if (twin && twin.id !== current?.id)\n throw new Refusal(\n 'bank-line-twice',\n { day: twin.transactionDate ?? '' },\n 'this bank line is already in the books'\n )\n }\n\n const written = await repo.save({ ...(current ?? { domain, creator: user }), ...row, updater: user } as Transaction)\n if (current && FACTS.some(field => field in row && row[field] !== (current as any)[field]))\n factsChanged.push(current.id)\n saved.push(written)\n }\n\n if (factsChanged.length) {\n const payments = await paymentsOn(tx, domain, factsChanged)\n await checkPaymentsWithin(\n tx,\n domain,\n payments.map(one => one.transaction.id)\n )\n const kinds = new Map<string, Payment[]>()\n for (const payment of payments) kinds.set(payment.targetType, [...(kinds.get(payment.targetType) ?? []), payment])\n const touchedOf = (ofKind: Payment[]) => ({\n targetIds: [...new Set(ofKind.map(one => one.targetId))],\n transactionIds: [...new Set(ofKind.map(one => one.transaction.id))]\n })\n for (const [targetType, ofKind] of kinds)\n await paymentTargetOf(targetType)?.validate?.(tx, domain, touchedOf(ofKind))\n for (const rule of paymentRules()) await rule(tx, domain, { transactionIds: [...new Set(payments.map(one => one.transaction.id))] })\n for (const [targetType, ofKind] of kinds)\n await paymentTargetOf(targetType)?.onSaved?.(tx, domain, touchedOf(ofKind))\n }\n\n return saved\n}\n"]}
|