@things-factory/accounting 10.1.136 → 10.1.138
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/payment/payment-history.d.ts +1 -0
- package/dist-server/service/payment/payment-history.js +5 -0
- package/dist-server/service/payment/payment-history.js.map +1 -1
- package/dist-server/service/payment/payment-service.js +14 -6
- package/dist-server/service/payment/payment-service.js.map +1 -1
- package/dist-server/service/payment/payment-targets.d.ts +10 -0
- package/dist-server/service/payment/payment-targets.js.map +1 -1
- package/dist-server/service/payment/payment-type.d.ts +2 -0
- package/dist-server/service/payment/payment-type.js +14 -0
- package/dist-server/service/payment/payment-type.js.map +1 -1
- package/dist-server/service/payment/payment.d.ts +1 -0
- package/dist-server/service/payment/payment.js +8 -0
- package/dist-server/service/payment/payment.js.map +1 -1
- package/dist-server/service/transaction/transaction-service.js +15 -13
- package/dist-server/service/transaction/transaction-service.js.map +1 -1
- package/dist-server/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
|
@@ -62,6 +62,11 @@ tslib_1.__decorate([
|
|
|
62
62
|
(0, type_graphql_1.Field)(type => type_graphql_1.Float, { nullable: true, description: 'amount at this version' }),
|
|
63
63
|
tslib_1.__metadata("design:type", Number)
|
|
64
64
|
], PaymentHistory.prototype, "amount", void 0);
|
|
65
|
+
tslib_1.__decorate([
|
|
66
|
+
(0, typeorm_1.Column)((0, shell_1.moneyColumn)({ nullable: true })),
|
|
67
|
+
(0, type_graphql_1.Field)(type => type_graphql_1.Float, { nullable: true, description: 'targetAmount at this version' }),
|
|
68
|
+
tslib_1.__metadata("design:type", Number)
|
|
69
|
+
], PaymentHistory.prototype, "targetAmount", void 0);
|
|
65
70
|
tslib_1.__decorate([
|
|
66
71
|
(0, typeorm_1.Column)({ nullable: true }),
|
|
67
72
|
(0, type_graphql_1.Field)(type => payment_1.PaymentPurpose, { nullable: true, description: 'purpose at this version' }),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-history.js","sourceRoot":"","sources":["../../../server/service/payment/payment-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAgE;AAChE,qCAA8F;AAE9F,8DAKiC;AACjC,yDAAgD;AAChD,6CAA4C;AAC5C,iDAA2D;AAE3D,4DAAwD;AACxD,uCAAkE;AAElE,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAA;AAEpC,0DAA0D;AAanD,IAAM,cAAc,GAApB,MAAM,cAAc;IAApB;QAOL,YAAO,GAAY,CAAC,CAAA;
|
|
1
|
+
{"version":3,"file":"payment-history.js","sourceRoot":"","sources":["../../../server/service/payment/payment-history.ts"],"names":[],"mappings":";;;;AAAA,+CAAgE;AAChE,qCAA8F;AAE9F,8DAKiC;AACjC,yDAAgD;AAChD,6CAA4C;AAC5C,iDAA2D;AAE3D,4DAAwD;AACxD,uCAAkE;AAElE,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAA;AAEpC,0DAA0D;AAanD,IAAM,cAAc,GAApB,MAAM,cAAc;IAApB;QAOL,YAAO,GAAY,CAAC,CAAA;IA8FtB,CAAC;CAAA,CAAA;AArGY,wCAAc;AAGhB;IAFR,IAAA,gCAAsB,EAAC,MAAM,CAAC;IAC9B,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,iBAAE,EAAE,EAAE,WAAW,EAAE,kCAAkC,EAAE,CAAC;;0CACpD;AAInB;IAFC,IAAA,gBAAM,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;IACtC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,gBAAgB,EAAE,CAAC;;+CACrC;AAIpB;IAFC,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AC,MAAM;YACR,CAAC,CAAC,aAAa,IAAI,QAAQ;gBACzB,CAAC,CAAC,UAAU;gBACZ,CAAC,CAAC,aAAa,IAAI,OAAO;oBACxB,CAAC,CAAC,UAAU;oBACZ,CAAC,CAAC,SAAS;QACnB,IAAI,EACF,aAAa,IAAI,UAAU,IAAI,aAAa,IAAI,OAAO,IAAI,aAAa,IAAI,SAAS;YACnF,CAAC,CAAC,mCAAiB;YACnB,CAAC,CAAC,SAAS;QACf,MAAM,EAAE,aAAa,IAAI,UAAU,IAAI,aAAa,IAAI,OAAO,IAAI,aAAa,IAAI,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE;KAC/G,CAAC;;8CAC+B;yBApGtB,cAAc;IAZ1B,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EACJ,sBAAsB,EACtB,CAAC,cAA8B,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,UAAU,EAAE,cAAc,CAAC,OAAO,CAAC,EACvF,EAAE,MAAM,EAAE,IAAI,EAAE,CACjB;IACA,IAAA,eAAK,EACJ,sBAAsB,EACtB,CAAC,cAA8B,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,MAAM,EAAE,cAAc,CAAC,UAAU,EAAE,cAAc,CAAC,OAAO,CAAC,EAC9G,EAAE,MAAM,EAAE,IAAI,EAAE,CACjB;IACA,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;GAC5C,cAAc,CAqG1B","sourcesContent":["import { Field, Float, ID, Int, ObjectType } from 'type-graphql'\nimport { Column, Entity, Index, ManyToOne, PrimaryGeneratedColumn, RelationId } from 'typeorm'\n\nimport {\n HistoryActionColumn,\n HistoryActionType,\n HistoryEntityInterface,\n HistoryOriginalIdColumn\n} from '@operato/typeorm-history'\nimport { User } from '@things-factory/auth-base'\nimport { config } from '@things-factory/env'\nimport { Domain, moneyColumn } from '@things-factory/shell'\n\nimport { Transaction } from '../transaction/transaction'\nimport { Payment, PaymentMethod, PaymentPurpose } from './payment'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\n/** Each version of a payment, written when it changes. */\n@Entity()\n@Index(\n 'ix_payment_history_0',\n (paymentHistory: PaymentHistory) => [paymentHistory.originalId, paymentHistory.version],\n { unique: true }\n)\n@Index(\n 'ix_payment_history_1',\n (paymentHistory: PaymentHistory) => [paymentHistory.domain, paymentHistory.originalId, paymentHistory.version],\n { unique: true }\n)\n@ObjectType({ description: 'History Entity of Payment' })\nexport class PaymentHistory implements HistoryEntityInterface<Payment> {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier of the version' })\n readonly id: string\n\n @Column({ nullable: true, default: 1 })\n @Field({ nullable: true, description: 'Version number' })\n version?: number = 1\n\n @ManyToOne(type => Domain)\n @Field(type => Domain, { nullable: true, description: 'The domain' })\n domain?: Domain\n\n @RelationId((paymentHistory: PaymentHistory) => paymentHistory.domain)\n domainId?: string\n\n @ManyToOne(type => Transaction, { nullable: true, createForeignKeyConstraints: false })\n @Field(type => Transaction, { nullable: true, description: 'transaction at this version' })\n transaction: Transaction\n\n @RelationId((paymentHistory: PaymentHistory) => paymentHistory.transaction)\n transactionId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'targetType at this version' })\n targetType: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'targetId at this version' })\n targetId: string\n\n @Column(moneyColumn({ nullable: true }))\n @Field(type => Float, { nullable: true, description: 'amount at this version' })\n amount: number\n\n @Column(moneyColumn({ nullable: true }))\n @Field(type => Float, { nullable: true, description: 'targetAmount at this version' })\n targetAmount: number\n\n @Column({ nullable: true })\n @Field(type => PaymentPurpose, { nullable: true, description: 'purpose at this version' })\n purpose: PaymentPurpose\n\n @Column({ nullable: true })\n @Field(type => PaymentMethod, { nullable: true, description: 'method at this version' })\n method: PaymentMethod\n\n @Column({ type: 'text', nullable: true })\n @Field({ nullable: true, description: 'basis at this version' })\n basis: string\n\n @Column({ type: 'text', nullable: true })\n @Field({ nullable: true, description: 'notes at this version' })\n notes: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When it was created' })\n createdAt?: Date\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When this version was written' })\n updatedAt?: Date\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'When it was deleted' })\n deletedAt?: Date\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Who created it' })\n creator?: User\n\n @RelationId((paymentHistory: PaymentHistory) => paymentHistory.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Who wrote this version' })\n updater?: User\n\n @RelationId((paymentHistory: PaymentHistory) => paymentHistory.updater)\n updaterId?: string\n\n @HistoryOriginalIdColumn()\n public originalId!: string\n\n @HistoryActionColumn({\n nullable: false,\n type:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'enum'\n : DATABASE_TYPE == 'oracle'\n ? 'varchar2'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'varchar',\n enum:\n DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? HistoryActionType\n : undefined,\n length: DATABASE_TYPE == 'postgres' || DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb' ? undefined : 10\n })\n public action!: HistoryActionType\n}\n"]}
|
|
@@ -65,6 +65,12 @@ function rowOf(patch, isNew) {
|
|
|
65
65
|
throw new shell_1.Refusal('payment-amount-not-positive', {}, 'amount: must be more than zero');
|
|
66
66
|
row.amount = amount;
|
|
67
67
|
}
|
|
68
|
+
if (patch.targetAmount !== undefined) {
|
|
69
|
+
const targetAmount = patch.targetAmount === null ? null : Number(patch.targetAmount);
|
|
70
|
+
if (targetAmount !== null && !(targetAmount > 0))
|
|
71
|
+
throw new shell_1.Refusal('payment-amount-not-positive', {}, 'targetAmount: must be more than zero');
|
|
72
|
+
row.targetAmount = targetAmount;
|
|
73
|
+
}
|
|
68
74
|
if (patch.method !== undefined)
|
|
69
75
|
row.method = patch.method ?? payment_1.PaymentMethod.PERSON;
|
|
70
76
|
if (patch.basis !== undefined)
|
|
@@ -129,12 +135,14 @@ async function savePayments(tx, domain, user, patches) {
|
|
|
129
135
|
saved.push(written);
|
|
130
136
|
}
|
|
131
137
|
await checkPaymentsWithin(tx, domain, [...touched.values()].flatMap(kind => [...kind.transactionIds]));
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
+
const touchedOf = (kind) => ({
|
|
139
|
+
targetIds: [...kind.targetIds],
|
|
140
|
+
transactionIds: [...kind.transactionIds]
|
|
141
|
+
});
|
|
142
|
+
for (const [targetType, kind] of touched)
|
|
143
|
+
await (0, payment_targets_1.paymentTargetOf)(targetType)?.validate?.(tx, domain, touchedOf(kind));
|
|
144
|
+
for (const [targetType, kind] of touched)
|
|
145
|
+
await (0, payment_targets_1.paymentTargetOf)(targetType)?.onSaved?.(tx, domain, touchedOf(kind));
|
|
138
146
|
return saved;
|
|
139
147
|
}
|
|
140
148
|
//# sourceMappingURL=payment-service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-service.js","sourceRoot":"","sources":["../../../server/service/payment/payment-service.ts"],"names":[],"mappings":";;AAeA,kDAiCC;AAwCD,oCA2EC;AAnKD,qCAA2C;AAE3C,iDAA+C;AAE/C,4DAAwD;AACxD,uCAAkD;AAClD,uDAAmD;AAGnD,4FAA4F;AAC5F,MAAM,IAAI,GAAG,KAAK,CAAA;AAElB;;GAEG;AACI,KAAK,UAAU,mBAAmB,CACvC,EAAiB,EACjB,MAAsB,EACtB,cAAwB;IAExB,MAAM,GAAG,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,CAAC,CAAA;IACxC,IA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EAAE,IAAI,CAAC,IAAI,OAAO,EAAE,CAAC;QACzC,MAAM,IAAA,iCAAe,EAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC;YAC9B,cAAc,EAAE,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC;SACzC,CAAC,CAAA;IACJ,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { EntityManager, In } from 'typeorm'\n\nimport { Refusal } from '@things-factory/shell'\n\nimport { Transaction } from '../transaction/transaction'\nimport { Payment, PaymentMethod } from './payment'\nimport { paymentTargetOf } from './payment-targets'\nimport { PaymentPatch } from './payment-type'\n\n/** Amounts are decimals; a sum within half a cent of the transaction is the transaction. */\nconst CENT = 0.005\n\n/**\n * Within one purpose a transaction pays no more than itself. Run after its payments or its amount change.\n */\nexport async function checkPaymentsWithin(\n tx: EntityManager,\n domain: { id: string },\n transactionIds: string[]\n): Promise<void> {\n const ids = [...new Set(transactionIds)]\n if (!ids.length) return\n\n const transactions = await tx\n .getRepository(Transaction)\n .find({ where: { domain: { id: domain.id }, id: In(ids) }, select: ['id', 'amount'] })\n const payments = await tx\n .getRepository(Payment)\n .find({ where: { domain: { id: domain.id }, transaction: { id: In(ids) } }, relations: ['transaction'] })\n const paid = new Map<string, number>()\n for (const payment of payments) {\n const key = `${payment.transaction.id}|${payment.purpose}`\n paid.set(key, (paid.get(key) ?? 0) + Number(payment.amount))\n }\n for (const transaction of transactions) {\n for (const [key, sum] of paid) {\n const [id, purpose] = key.split('|')\n if (id !== transaction.id) continue\n const amount = Math.abs(Number(transaction.amount))\n if (sum > amount + CENT) {\n throw new Refusal(\n 'payment-over-transaction',\n { purpose, paid: sum, amount },\n `${purpose}: ${sum} put on a transaction of ${amount}`\n )\n }\n }\n }\n}\n\n/** A patch as the row it writes: the target kind known, the amount more than zero, the purpose the kind's. */\nfunction rowOf(patch: PaymentPatch, isNew: boolean): Partial<Payment> & { transactionId?: string } {\n const row: Record<string, any> = {}\n const transactionId = patch.transaction?.id\n if (isNew && !transactionId)\n throw new Refusal('payment-transaction-required', {}, 'a payment needs the transaction it is a part of')\n if (transactionId) row.transactionId = transactionId\n\n if (patch.targetType !== undefined || isNew) {\n const target = paymentTargetOf(String(patch.targetType ?? ''))\n if (!target)\n throw new Refusal(\n 'payment-target-unknown',\n { targetType: patch.targetType },\n `'${patch.targetType}' is not a kind of target any module registered`\n )\n row.targetType = patch.targetType\n row.purpose = target.purpose\n }\n if (patch.targetId !== undefined || isNew) {\n if (!patch.targetId) throw new Refusal('payment-target-required', {}, 'a payment needs what it paid')\n row.targetId = patch.targetId\n }\n if (patch.amount !== undefined || isNew) {\n const amount = Number(patch.amount)\n if (!(amount > 0)) throw new Refusal('payment-amount-not-positive', {}, 'amount: must be more than zero')\n row.amount = amount\n }\n if (patch.method !== undefined) row.method = patch.method ?? PaymentMethod.PERSON\n if (patch.basis !== undefined) row.basis = patch.basis || null\n if (patch.notes !== undefined) row.notes = patch.notes || null\n return row\n}\n\n/**\n * Apply rows to a domain's payments: `+` (or no id) adds, `M` changes, `-` deletes (softly). Then the general rule\n * (§`checkPaymentsWithin`) and each touched kind's own rules run, in the same database transaction.\n */\nexport async function savePayments(\n tx: EntityManager,\n domain: { id: string },\n user: any,\n patches: PaymentPatch[]\n): Promise<Payment[]> {\n const repo = tx.getRepository(Payment)\n const transactions = tx.getRepository(Transaction)\n const touched = new Map<string, { targetIds: Set<string>; transactionIds: Set<string> }>()\n const touch = (payment: { targetType: string; targetId: string; transactionId?: string }) => {\n const kind = touched.get(payment.targetType) ?? { targetIds: new Set<string>(), transactionIds: new Set<string>() }\n kind.targetIds.add(payment.targetId)\n if (payment.transactionId) kind.transactionIds.add(payment.transactionId)\n touched.set(payment.targetType, kind)\n }\n\n const deletes = patches.filter(one => one.cuFlag === '-' && one.id).map(one => one.id!)\n if (deletes.length) {\n const owned = await repo.find({ where: { domain: { id: domain.id }, id: In(deletes) }, relations: ['transaction'] })\n if (owned.length !== new Set(deletes).size)\n throw new Refusal('payment-not-found', {}, 'a payment was not found - reload and try again')\n for (const one of owned) touch({ ...one, transactionId: one.transaction.id })\n await repo.softDelete({ id: In(deletes) })\n }\n\n const saved: Payment[] = []\n for (const patch of patches.filter(one => one.cuFlag !== '-')) {\n const isNew = !patch.id || patch.cuFlag === '+'\n const { transactionId, ...row } = rowOf(patch, isNew)\n const current = isNew\n ? undefined\n : await repo.findOne({ where: { domain: { id: domain.id }, id: patch.id }, relations: ['transaction'] })\n if (!isNew && !current) throw new Refusal('payment-not-found', {}, 'a payment was not found - reload and try again')\n\n const transactionOf = transactionId ?? current!.transaction.id\n const transaction = await transactions.findOne({ where: { domain: { id: domain.id }, id: transactionOf } })\n if (!transaction)\n throw new Refusal('payment-transaction-not-found', {}, 'the transaction was not found - reload and try again')\n\n const targetType = row.targetType ?? current!.targetType\n const targetId = row.targetId ?? current!.targetId\n const twin = await repo.findOne({\n where: { domain: { id: domain.id }, transaction: { id: transaction.id }, targetType, targetId }\n })\n if (twin && twin.id !== current?.id)\n throw new Refusal(\n 'payment-twice',\n { targetType, targetId },\n 'the transaction already pays this - change that payment instead'\n )\n\n if (current) touch({ ...current, transactionId: current.transaction.id })\n const written = await repo.save({\n ...(current ?? { domain, creator: user }),\n ...row,\n transaction,\n updater: user\n } as Payment)\n touch({ targetType: written.targetType, targetId: written.targetId, transactionId: transaction.id })\n saved.push(written)\n }\n\n await checkPaymentsWithin(\n tx,\n domain,\n [...touched.values()].flatMap(kind => [...kind.transactionIds])\n )\n for (const [targetType, kind] of touched) {\n await paymentTargetOf(targetType)?.validate?.(tx, domain, {\n targetIds: [...kind.targetIds],\n transactionIds: [...kind.transactionIds]\n })\n }\n\n return saved\n}\n"]}
|
|
1
|
+
{"version":3,"file":"payment-service.js","sourceRoot":"","sources":["../../../server/service/payment/payment-service.ts"],"names":[],"mappings":";;AAeA,kDAiCC;AA8CD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A;IAEnH,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import { EntityManager, In } from 'typeorm'\n\nimport { Refusal } from '@things-factory/shell'\n\nimport { Transaction } from '../transaction/transaction'\nimport { Payment, PaymentMethod } from './payment'\nimport { paymentTargetOf } from './payment-targets'\nimport { PaymentPatch } from './payment-type'\n\n/** Amounts are decimals; a sum within half a cent of the transaction is the transaction. */\nconst CENT = 0.005\n\n/**\n * Within one purpose a transaction pays no more than itself. Run after its payments or its amount change.\n */\nexport async function checkPaymentsWithin(\n tx: EntityManager,\n domain: { id: string },\n transactionIds: string[]\n): Promise<void> {\n const ids = [...new Set(transactionIds)]\n if (!ids.length) return\n\n const transactions = await tx\n .getRepository(Transaction)\n .find({ where: { domain: { id: domain.id }, id: In(ids) }, select: ['id', 'amount'] })\n const payments = await tx\n .getRepository(Payment)\n .find({ where: { domain: { id: domain.id }, transaction: { id: In(ids) } }, relations: ['transaction'] })\n const paid = new Map<string, number>()\n for (const payment of payments) {\n const key = `${payment.transaction.id}|${payment.purpose}`\n paid.set(key, (paid.get(key) ?? 0) + Number(payment.amount))\n }\n for (const transaction of transactions) {\n for (const [key, sum] of paid) {\n const [id, purpose] = key.split('|')\n if (id !== transaction.id) continue\n const amount = Math.abs(Number(transaction.amount))\n if (sum > amount + CENT) {\n throw new Refusal(\n 'payment-over-transaction',\n { purpose, paid: sum, amount },\n `${purpose}: ${sum} put on a transaction of ${amount}`\n )\n }\n }\n }\n}\n\n/** A patch as the row it writes: the target kind known, the amount more than zero, the purpose the kind's. */\nfunction rowOf(patch: PaymentPatch, isNew: boolean): Partial<Payment> & { transactionId?: string } {\n const row: Record<string, any> = {}\n const transactionId = patch.transaction?.id\n if (isNew && !transactionId)\n throw new Refusal('payment-transaction-required', {}, 'a payment needs the transaction it is a part of')\n if (transactionId) row.transactionId = transactionId\n\n if (patch.targetType !== undefined || isNew) {\n const target = paymentTargetOf(String(patch.targetType ?? ''))\n if (!target)\n throw new Refusal(\n 'payment-target-unknown',\n { targetType: patch.targetType },\n `'${patch.targetType}' is not a kind of target any module registered`\n )\n row.targetType = patch.targetType\n row.purpose = target.purpose\n }\n if (patch.targetId !== undefined || isNew) {\n if (!patch.targetId) throw new Refusal('payment-target-required', {}, 'a payment needs what it paid')\n row.targetId = patch.targetId\n }\n if (patch.amount !== undefined || isNew) {\n const amount = Number(patch.amount)\n if (!(amount > 0)) throw new Refusal('payment-amount-not-positive', {}, 'amount: must be more than zero')\n row.amount = amount\n }\n if (patch.targetAmount !== undefined) {\n const targetAmount = patch.targetAmount === null ? null : Number(patch.targetAmount)\n if (targetAmount !== null && !(targetAmount > 0))\n throw new Refusal('payment-amount-not-positive', {}, 'targetAmount: must be more than zero')\n row.targetAmount = targetAmount\n }\n if (patch.method !== undefined) row.method = patch.method ?? PaymentMethod.PERSON\n if (patch.basis !== undefined) row.basis = patch.basis || null\n if (patch.notes !== undefined) row.notes = patch.notes || null\n return row\n}\n\n/**\n * Apply rows to a domain's payments: `+` (or no id) adds, `M` changes, `-` deletes (softly). Then the general rule\n * (§`checkPaymentsWithin`) and each touched kind's own rules run, in the same database transaction.\n */\nexport async function savePayments(\n tx: EntityManager,\n domain: { id: string },\n user: any,\n patches: PaymentPatch[]\n): Promise<Payment[]> {\n const repo = tx.getRepository(Payment)\n const transactions = tx.getRepository(Transaction)\n const touched = new Map<string, { targetIds: Set<string>; transactionIds: Set<string> }>()\n const touch = (payment: { targetType: string; targetId: string; transactionId?: string }) => {\n const kind = touched.get(payment.targetType) ?? { targetIds: new Set<string>(), transactionIds: new Set<string>() }\n kind.targetIds.add(payment.targetId)\n if (payment.transactionId) kind.transactionIds.add(payment.transactionId)\n touched.set(payment.targetType, kind)\n }\n\n const deletes = patches.filter(one => one.cuFlag === '-' && one.id).map(one => one.id!)\n if (deletes.length) {\n const owned = await repo.find({ where: { domain: { id: domain.id }, id: In(deletes) }, relations: ['transaction'] })\n if (owned.length !== new Set(deletes).size)\n throw new Refusal('payment-not-found', {}, 'a payment was not found - reload and try again')\n for (const one of owned) touch({ ...one, transactionId: one.transaction.id })\n await repo.softDelete({ id: In(deletes) })\n }\n\n const saved: Payment[] = []\n for (const patch of patches.filter(one => one.cuFlag !== '-')) {\n const isNew = !patch.id || patch.cuFlag === '+'\n const { transactionId, ...row } = rowOf(patch, isNew)\n const current = isNew\n ? undefined\n : await repo.findOne({ where: { domain: { id: domain.id }, id: patch.id }, relations: ['transaction'] })\n if (!isNew && !current) throw new Refusal('payment-not-found', {}, 'a payment was not found - reload and try again')\n\n const transactionOf = transactionId ?? current!.transaction.id\n const transaction = await transactions.findOne({ where: { domain: { id: domain.id }, id: transactionOf } })\n if (!transaction)\n throw new Refusal('payment-transaction-not-found', {}, 'the transaction was not found - reload and try again')\n\n const targetType = row.targetType ?? current!.targetType\n const targetId = row.targetId ?? current!.targetId\n const twin = await repo.findOne({\n where: { domain: { id: domain.id }, transaction: { id: transaction.id }, targetType, targetId }\n })\n if (twin && twin.id !== current?.id)\n throw new Refusal(\n 'payment-twice',\n { targetType, targetId },\n 'the transaction already pays this - change that payment instead'\n )\n\n if (current) touch({ ...current, transactionId: current.transaction.id })\n const written = await repo.save({\n ...(current ?? { domain, creator: user }),\n ...row,\n transaction,\n updater: user\n } as Payment)\n touch({ targetType: written.targetType, targetId: written.targetId, transactionId: transaction.id })\n saved.push(written)\n }\n\n await checkPaymentsWithin(\n tx,\n domain,\n [...touched.values()].flatMap(kind => [...kind.transactionIds])\n )\n const touchedOf = (kind: { targetIds: Set<string>; transactionIds: Set<string> }) => ({\n targetIds: [...kind.targetIds],\n transactionIds: [...kind.transactionIds]\n })\n for (const [targetType, kind] of touched) await paymentTargetOf(targetType)?.validate?.(tx, domain, touchedOf(kind))\n for (const [targetType, kind] of touched) await paymentTargetOf(targetType)?.onSaved?.(tx, domain, touchedOf(kind))\n\n return saved\n}\n"]}
|
|
@@ -24,6 +24,16 @@ export interface PaymentTarget {
|
|
|
24
24
|
targetIds: string[];
|
|
25
25
|
transactionIds: string[];
|
|
26
26
|
}) => Promise<void>;
|
|
27
|
+
/**
|
|
28
|
+
* What the owner keeps in step with its targets' payments - a round's collected amount and day - run after every
|
|
29
|
+
* kind's rules passed, in the same database transaction.
|
|
30
|
+
*/
|
|
31
|
+
onSaved?: (tx: EntityManager, domain: {
|
|
32
|
+
id: string;
|
|
33
|
+
}, touched: {
|
|
34
|
+
targetIds: string[];
|
|
35
|
+
transactionIds: string[];
|
|
36
|
+
}) => Promise<void>;
|
|
27
37
|
}
|
|
28
38
|
/** Register a kind of target. A kind is registered once; registering it again is a mistake in the app. */
|
|
29
39
|
export declare function registerPaymentTarget(targetType: string, target: PaymentTarget): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-targets.js","sourceRoot":"","sources":["../../../server/service/payment/payment-targets.ts"],"names":[],"mappings":";;
|
|
1
|
+
{"version":3,"file":"payment-targets.js","sourceRoot":"","sources":["../../../server/service/payment/payment-targets.ts"],"names":[],"mappings":";;AAuCA,sDAGC;AAED,0CAEC;AAED,4DAEC;AAdD,MAAM,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAA;AAEhD,0GAA0G;AAC1G,SAAgB,qBAAqB,CAAC,UAAkB,EAAE,MAAqB;IAC7E,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,UAAU,uBAAuB,CAAC,CAAA;IAClG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,CAAA;AACjC,CAAC;AAED,SAAgB,eAAe,CAAC,UAAkB;IAChD,OAAO,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAA;AAChC,CAAC;AAED,SAAgB,wBAAwB;IACtC,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;AAC5B,CAAC","sourcesContent":["import { EntityManager } from 'typeorm'\n\nimport { PaymentPurpose } from './payment'\n\n/**\n * The kinds of thing a transaction can pay, registered by the module that owns them.\n *\n * accounting keeps the general rules - the target kind is known, a transaction pays no more than itself within one\n * purpose. What a target may take (a contract round's capacity, one VAT period per withdrawal) is the owner's rule,\n * run in the same database transaction after the payments are written.\n */\nexport interface PaymentTarget {\n /** What a payment on this kind tells of its transaction. */\n purpose: PaymentPurpose\n /** What people call each target - 「H2026021 3차」 - for the screens that list what a transaction paid. */\n label?: (tx: EntityManager, domain: { id: string }, targetIds: string[]) => Promise<Map<string, string>>\n /**\n * The owner's rules on the payments of its targets, given the targets and transactions a save touched. Throw a\n * `Refusal` to refuse the save.\n */\n validate?: (\n tx: EntityManager,\n domain: { id: string },\n touched: { targetIds: string[]; transactionIds: string[] }\n ) => Promise<void>\n /**\n * What the owner keeps in step with its targets' payments - a round's collected amount and day - run after every\n * kind's rules passed, in the same database transaction.\n */\n onSaved?: (\n tx: EntityManager,\n domain: { id: string },\n touched: { targetIds: string[]; transactionIds: string[] }\n ) => Promise<void>\n}\n\nconst targets = new Map<string, PaymentTarget>()\n\n/** Register a kind of target. A kind is registered once; registering it again is a mistake in the app. */\nexport function registerPaymentTarget(targetType: string, target: PaymentTarget): void {\n if (targets.has(targetType)) throw new Error(`payment target '${targetType}' is registered twice`)\n targets.set(targetType, target)\n}\n\nexport function paymentTargetOf(targetType: string): PaymentTarget | undefined {\n return targets.get(targetType)\n}\n\nexport function registeredPaymentTargets(): string[] {\n return [...targets.keys()]\n}\n"]}
|
|
@@ -5,6 +5,7 @@ export declare class NewPayment {
|
|
|
5
5
|
targetType: string;
|
|
6
6
|
targetId: string;
|
|
7
7
|
amount: number;
|
|
8
|
+
targetAmount?: number;
|
|
8
9
|
method?: PaymentMethod;
|
|
9
10
|
basis?: string;
|
|
10
11
|
notes?: string;
|
|
@@ -15,6 +16,7 @@ export declare class PaymentPatch {
|
|
|
15
16
|
targetType?: string;
|
|
16
17
|
targetId?: string;
|
|
17
18
|
amount?: number;
|
|
19
|
+
targetAmount?: number;
|
|
18
20
|
method?: PaymentMethod;
|
|
19
21
|
basis?: string;
|
|
20
22
|
notes?: string;
|
|
@@ -24,6 +24,13 @@ tslib_1.__decorate([
|
|
|
24
24
|
(0, type_graphql_1.Field)(type => type_graphql_1.Float, { description: 'The part of the transaction put on the target' }),
|
|
25
25
|
tslib_1.__metadata("design:type", Number)
|
|
26
26
|
], NewPayment.prototype, "amount", void 0);
|
|
27
|
+
tslib_1.__decorate([
|
|
28
|
+
(0, type_graphql_1.Field)(type => type_graphql_1.Float, {
|
|
29
|
+
nullable: true,
|
|
30
|
+
description: "The amount in the target document's currency; empty when it is the transaction's"
|
|
31
|
+
}),
|
|
32
|
+
tslib_1.__metadata("design:type", Number)
|
|
33
|
+
], NewPayment.prototype, "targetAmount", void 0);
|
|
27
34
|
tslib_1.__decorate([
|
|
28
35
|
(0, type_graphql_1.Field)(type => payment_1.PaymentMethod, { nullable: true, description: 'Who made the link - a person when not given' }),
|
|
29
36
|
tslib_1.__metadata("design:type", String)
|
|
@@ -62,6 +69,13 @@ tslib_1.__decorate([
|
|
|
62
69
|
(0, type_graphql_1.Field)(type => type_graphql_1.Float, { nullable: true, description: 'The part of the transaction put on the target' }),
|
|
63
70
|
tslib_1.__metadata("design:type", Number)
|
|
64
71
|
], PaymentPatch.prototype, "amount", void 0);
|
|
72
|
+
tslib_1.__decorate([
|
|
73
|
+
(0, type_graphql_1.Field)(type => type_graphql_1.Float, {
|
|
74
|
+
nullable: true,
|
|
75
|
+
description: "The amount in the target document's currency; empty when it is the transaction's"
|
|
76
|
+
}),
|
|
77
|
+
tslib_1.__metadata("design:type", Number)
|
|
78
|
+
], PaymentPatch.prototype, "targetAmount", void 0);
|
|
65
79
|
tslib_1.__decorate([
|
|
66
80
|
(0, type_graphql_1.Field)(type => payment_1.PaymentMethod, { nullable: true, description: 'Who made the link' }),
|
|
67
81
|
tslib_1.__metadata("design:type", String)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-type.js","sourceRoot":"","sources":["../../../server/service/payment/payment-type.ts"],"names":[],"mappings":";;;;A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d;IADC,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,8BAA8B,EAAE,CAAC;;4CACxD;uBAhCJ,YAAY;IADxB,IAAA,wBAAS,EAAC,EAAE,WAAW,EAAE,2EAA2E,EAAE,CAAC;GAC3F,YAAY,CAiCxB;AAGM,IAAM,WAAW,GAAjB,MAAM,WAAW;CAMvB,CAAA;AANY,kCAAW;AAEtB;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,CAAC,iBAAO,CAAC,EAAE,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;;0CACvD;AAGhB;IADC,IAAA,oBAAK,EAAC,IAAI,CAAC,EAAE,CAAC,kBAAG,EAAE,EAAE,WAAW,EAAE,2BAA2B,EAAE,CAAC;;0CACpD;sBALF,WAAW;IADvB,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,oBAAoB,EAAE,CAAC;GACrC,WAAW,CAMvB","sourcesContent":["import { ObjectType, Field, Float, InputType, Int, ID } from 'type-graphql'\n\nimport { ObjectRef } from '@things-factory/shell'\n\nimport { Payment, PaymentMethod } from './payment'\n\n@InputType({ description: 'A new part of a transaction put on what it paid' })\nexport class NewPayment {\n @Field(type => ObjectRef, { description: 'The transaction a part of which this is' })\n transaction: ObjectRef\n\n @Field({ description: 'The kind of what was paid, as registered' })\n targetType: string\n\n @Field({ description: 'The id of what was paid' })\n targetId: string\n\n @Field(type => Float, { description: 'The part of the transaction put on the target' })\n amount: number\n\n @Field(type => Float, {\n nullable: true,\n description: \"The amount in the target document's currency; empty when it is the transaction's\"\n })\n targetAmount?: number\n\n @Field(type => PaymentMethod, { nullable: true, description: 'Who made the link - a person when not given' })\n method?: PaymentMethod\n\n @Field({ nullable: true, description: 'Why a rule made the link' })\n basis?: string\n\n @Field({ nullable: true, description: 'Notes' })\n notes?: string\n}\n\n@InputType({ description: 'A change to a payment, or a grid row: cuFlag + adds, M changes, - deletes' })\nexport class PaymentPatch {\n @Field(type => ID, { nullable: true, description: 'The payment to change or delete' })\n id?: string\n\n @Field(type => ObjectRef, { nullable: true, description: 'The transaction a part of which this is' })\n transaction?: ObjectRef\n\n @Field({ nullable: true, description: 'The kind of what was paid, as registered' })\n targetType?: string\n\n @Field({ nullable: true, description: 'The id of what was paid' })\n targetId?: string\n\n @Field(type => Float, { nullable: true, description: 'The part of the transaction put on the target' })\n amount?: number\n\n @Field(type => Float, {\n nullable: true,\n description: \"The amount in the target document's currency; empty when it is the transaction's\"\n })\n targetAmount?: number\n\n @Field(type => PaymentMethod, { nullable: true, description: 'Who made the link' })\n method?: PaymentMethod\n\n @Field({ nullable: true, description: 'Why a rule made the link' })\n basis?: string\n\n @Field({ nullable: true, description: 'Notes' })\n notes?: string\n\n @Field({ nullable: true, description: '+ adds, M changes, - deletes' })\n cuFlag?: string\n}\n\n@ObjectType({ description: 'A page of payments' })\nexport class PaymentList {\n @Field(type => [Payment], { description: 'The payments on this page' })\n items: Payment[]\n\n @Field(type => Int, { description: 'How many there are in all' })\n total: number\n}\n"]}
|
|
@@ -84,6 +84,14 @@ tslib_1.__decorate([
|
|
|
84
84
|
(0, type_graphql_1.Field)(type => type_graphql_1.Float, { description: "The part of the transaction put on the target, in the transaction's currency" }),
|
|
85
85
|
tslib_1.__metadata("design:type", Number)
|
|
86
86
|
], Payment.prototype, "amount", void 0);
|
|
87
|
+
tslib_1.__decorate([
|
|
88
|
+
(0, typeorm_1.Column)((0, shell_1.moneyColumn)({ nullable: true, default: null })),
|
|
89
|
+
(0, type_graphql_1.Field)(type => type_graphql_1.Float, {
|
|
90
|
+
nullable: true,
|
|
91
|
+
description: "The amount in the target document's currency; empty when it is the transaction's"
|
|
92
|
+
}),
|
|
93
|
+
tslib_1.__metadata("design:type", Number)
|
|
94
|
+
], Payment.prototype, "targetAmount", void 0);
|
|
87
95
|
tslib_1.__decorate([
|
|
88
96
|
(0, typeorm_1.Column)(),
|
|
89
97
|
(0, type_graphql_1.Field)(type => PaymentPurpose, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../server/service/payment/payment.ts"],"names":[],"mappings":";;;;AAAA,qCAWgB;AAChB,+CAA6E;AAE7E,iDAA2D;AAC3D,yDAAgD;AAChD,4DAAwD;AAExD,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,2CAAyB,CAAA;IACzB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;AACvB,CAAC,EAJW,cAAc,8BAAd,cAAc,QAIzB;AAED,IAAA,+BAAgB,EAAC,cAAc,EAAE;IAC/B,IAAI,EAAE,gBAAgB;IACtB,WAAW,EACT,qKAAqK;CACxK,CAAC,CAAA;AAEF,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,8BAAa,CAAA;IACb,kCAAiB,CAAA;AACnB,CAAC,EAHW,aAAa,6BAAb,aAAa,QAGxB;AAED,IAAA,+BAAgB,EAAC,aAAa,EAAE;IAC9B,IAAI,EAAE,eAAe;IACrB,WAAW,EAAE,oDAAoD;CAClE,CAAC,CAAA;AAEF;;;;;;;;GAQG;AAYI,IAAM,OAAO,GAAb,MAAM,OAAO;IAAb;QAOL,YAAO,GAAY,CAAC,CAAA;
|
|
1
|
+
{"version":3,"file":"payment.js","sourceRoot":"","sources":["../../../server/service/payment/payment.ts"],"names":[],"mappings":";;;;AAAA,qCAWgB;AAChB,+CAA6E;AAE7E,iDAA2D;AAC3D,yDAAgD;AAChD,4DAAwD;AAExD,IAAY,cAIX;AAJD,WAAY,cAAc;IACxB,2CAAyB,CAAA;IACzB,uCAAqB,CAAA;IACrB,uCAAqB,CAAA;AACvB,CAAC,EAJW,cAAc,8BAAd,cAAc,QAIzB;AAED,IAAA,+BAAgB,EAAC,cAAc,EAAE;IAC/B,IAAI,EAAE,gBAAgB;IACtB,WAAW,EACT,qKAAqK;CACxK,CAAC,CAAA;AAEF,IAAY,aAGX;AAHD,WAAY,aAAa;IACvB,8BAAa,CAAA;IACb,kCAAiB,CAA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OAAO,CAAC;;0CAChC;kBApFP,OAAO;IAXnB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EACJ,cAAc,EACd,CAAC,OAAgB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,EACjG;QACE,MAAM,EAAE,IAAI;QACZ,KAAK,EAAE,sBAAsB;KAC9B,CACF;IACA,IAAA,eAAK,EAAC,cAAc,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACnG,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,6CAA6C,EAAE,CAAC;GAC9D,OAAO,CAqFnB","sourcesContent":["import {\n CreateDateColumn,\n UpdateDateColumn,\n DeleteDateColumn,\n Entity,\n Index,\n Column,\n RelationId,\n ManyToOne,\n VersionColumn,\n PrimaryGeneratedColumn\n} from 'typeorm'\nimport { ObjectType, Field, Float, ID, registerEnumType } from 'type-graphql'\n\nimport { Domain, moneyColumn } from '@things-factory/shell'\nimport { User } from '@things-factory/auth-base'\nimport { Transaction } from '../transaction/transaction'\n\nexport enum PaymentPurpose {\n SETTLEMENT = 'SETTLEMENT',\n EVIDENCE = 'EVIDENCE',\n TRANSFER = 'TRANSFER'\n}\n\nregisterEnumType(PaymentPurpose, {\n name: 'PaymentPurpose',\n description:\n 'What a payment tells of its transaction - the business document it settled, the document that evidences it, or the matching line of a move between our own accounts'\n})\n\nexport enum PaymentMethod {\n RULE = 'RULE',\n PERSON = 'PERSON'\n}\n\nregisterEnumType(PaymentMethod, {\n name: 'PaymentMethod',\n description: 'Who made the link - a rule of the app, or a person'\n})\n\n/**\n * What a transaction paid: a part of it, put on one target - a contract round, a tax invoice, a VAT period, the other\n * line of a transfer between our own accounts. One transaction may pay several targets, and one target be paid by\n * several transactions.\n *\n * The kinds of target are registered by the apps that own them (§`registerPaymentTarget`), each with its purpose.\n * Within one purpose the payments of a transaction add up to no more than the transaction; across purposes the same\n * money is told twice - a deposit settles a round and is evidenced by that round's tax invoice.\n */\n@Entity()\n@Index(\n 'ix_payment_0',\n (payment: Payment) => [payment.domain, payment.transaction, payment.targetType, payment.targetId],\n {\n unique: true,\n where: '\"deleted_at\" IS NULL'\n }\n)\n@Index('ix_payment_1', (payment: Payment) => [payment.domain, payment.targetType, payment.targetId])\n@ObjectType({ description: 'A part of a transaction put on what it paid' })\nexport class Payment {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { description: 'Unique identifier for the payment record' })\n readonly id: string\n\n @VersionColumn()\n @Field({ nullable: true, description: 'Version number used for optimistic locking' })\n version?: number = 1\n\n @ManyToOne(type => Domain)\n @Field(type => Domain, { nullable: true, description: 'The domain to which this payment belongs' })\n domain?: Domain\n\n @RelationId((payment: Payment) => payment.domain)\n domainId?: string\n\n @ManyToOne(type => Transaction, transaction => transaction.payments, { nullable: false })\n @Field(type => Transaction, { description: 'The transaction a part of which this is' })\n transaction: Transaction\n\n @RelationId((payment: Payment) => payment.transaction)\n transactionId?: string\n\n @Column()\n @Field({ description: 'The kind of what was paid, as registered - ContractMilestone, TaxInvoice, Transaction' })\n targetType: string\n\n @Column()\n @Field({ description: 'The id of what was paid' })\n targetId: string\n\n @Column(moneyColumn())\n @Field(type => Float, { description: \"The part of the transaction put on the target, in the transaction's currency\" })\n amount: number\n\n @Column(moneyColumn({ nullable: true, default: null }))\n @Field(type => Float, {\n nullable: true,\n description: \"The amount in the target document's currency; empty when it is the transaction's\"\n })\n targetAmount?: number\n\n @Column()\n @Field(type => PaymentPurpose, {\n description: \"What the payment tells of the transaction - the target kind's purpose\"\n })\n purpose: PaymentPurpose\n\n @Column({ default: PaymentMethod.PERSON })\n @Field(type => PaymentMethod, { description: 'Who made the link' })\n method: PaymentMethod\n\n @Column({ type: 'text', nullable: true })\n @Field({ nullable: true, description: 'Why a rule made the link - what matched' })\n basis?: string\n\n @Column({ type: 'text', nullable: true })\n @Field({ nullable: true, description: 'Notes' })\n notes?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'The date and time when the payment record was created' })\n createdAt?: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'The date and time when the payment record was last updated' })\n updatedAt?: Date\n\n @DeleteDateColumn()\n @Field({ nullable: true, description: 'The date and time when the payment record was deleted' })\n deletedAt?: Date\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'The user who created the payment record' })\n creator?: User\n\n @RelationId((payment: Payment) => payment.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'The user who last updated the payment record' })\n updater?: User\n\n @RelationId((payment: Payment) => payment.updater)\n updaterId?: string\n}\n"]}
|
|
@@ -10,8 +10,8 @@ const payment_service_1 = require("../payment/payment-service");
|
|
|
10
10
|
const payment_targets_1 = require("../payment/payment-targets");
|
|
11
11
|
const transaction_1 = require("./transaction");
|
|
12
12
|
const transaction_period_1 = require("./transaction-period");
|
|
13
|
-
/** What
|
|
14
|
-
const
|
|
13
|
+
/** What its payments depend on - they are checked again, and their owners follow, when one of these changes. */
|
|
14
|
+
const FACTS = ['amount', 'type', 'currency', 'transactionDate'];
|
|
15
15
|
/**
|
|
16
16
|
* The row a patch writes over the current one: a confirmed transaction has a day and takes its year and month from it;
|
|
17
17
|
* a forecast has a year and a month, and the day its timing names.
|
|
@@ -86,7 +86,7 @@ async function saveTransactions(tx, domain, user, inputs) {
|
|
|
86
86
|
await repo.softRemove(found);
|
|
87
87
|
}
|
|
88
88
|
const saved = [];
|
|
89
|
-
const
|
|
89
|
+
const factsChanged = [];
|
|
90
90
|
for (const input of inputs.filter(one => one.cuFlag !== '-')) {
|
|
91
91
|
const isNew = !input.id || input.cuFlag === '+';
|
|
92
92
|
const current = isNew ? undefined : await repo.findOne({ where: { domain: { id: domain.id }, id: input.id } });
|
|
@@ -108,22 +108,24 @@ async function saveTransactions(tx, domain, user, inputs) {
|
|
|
108
108
|
throw new shell_1.Refusal('bank-line-twice', { day: twin.transactionDate ?? '' }, 'this bank line is already in the books');
|
|
109
109
|
}
|
|
110
110
|
const written = await repo.save({ ...(current ?? { domain, creator: user }), ...row, updater: user });
|
|
111
|
-
if (current &&
|
|
112
|
-
|
|
111
|
+
if (current && FACTS.some(field => field in row && row[field] !== current[field]))
|
|
112
|
+
factsChanged.push(current.id);
|
|
113
113
|
saved.push(written);
|
|
114
114
|
}
|
|
115
|
-
if (
|
|
116
|
-
const payments = await paymentsOn(tx, domain,
|
|
115
|
+
if (factsChanged.length) {
|
|
116
|
+
const payments = await paymentsOn(tx, domain, factsChanged);
|
|
117
117
|
await (0, payment_service_1.checkPaymentsWithin)(tx, domain, payments.map(one => one.transaction.id));
|
|
118
118
|
const kinds = new Map();
|
|
119
119
|
for (const payment of payments)
|
|
120
120
|
kinds.set(payment.targetType, [...(kinds.get(payment.targetType) ?? []), payment]);
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
121
|
+
const touchedOf = (ofKind) => ({
|
|
122
|
+
targetIds: [...new Set(ofKind.map(one => one.targetId))],
|
|
123
|
+
transactionIds: [...new Set(ofKind.map(one => one.transaction.id))]
|
|
124
|
+
});
|
|
125
|
+
for (const [targetType, ofKind] of kinds)
|
|
126
|
+
await (0, payment_targets_1.paymentTargetOf)(targetType)?.validate?.(tx, domain, touchedOf(ofKind));
|
|
127
|
+
for (const [targetType, ofKind] of kinds)
|
|
128
|
+
await (0, payment_targets_1.paymentTargetOf)(targetType)?.onSaved?.(tx, domain, touchedOf(ofKind));
|
|
127
129
|
}
|
|
128
130
|
return saved;
|
|
129
131
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction-service.js","sourceRoot":"","sources":["../../../server/service/transaction/transaction-service.ts"],"names":[],"mappings":";;AAg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AAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;gBACxD,cAAc,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;aACpE,CAAC,CAAA;QACJ,CAAC;IACH,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 { paymentTargetOf } from '../payment/payment-targets'\nimport { ForecastStatus, Transaction, TransactionCategory } 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 changes the money of a transaction - its payments are checked again when one of these changes. */\nconst MONEY = ['amount', 'type', 'currency'] 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 */\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 moneyChanged: 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 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 && MONEY.some(field => field in row && row[field] !== (current as any)[field]))\n moneyChanged.push(current.id)\n saved.push(written)\n }\n\n if (moneyChanged.length) {\n const payments = await paymentsOn(tx, domain, moneyChanged)\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 for (const [targetType, ofKind] of kinds) {\n await paymentTargetOf(targetType)?.validate?.(tx, domain, {\n targetIds: [...new Set(ofKind.map(one => one.targetId))],\n transactionIds: [...new Set(ofKind.map(one => one.transaction.id))]\n })\n }\n }\n\n return saved\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transaction-service.js","sourceRoot":"","sources":["../../../server/service/transaction/transaction-service.ts"],"names":[],"mappings":";;AAgGA,4CAwEC;AAxKD,qCAA2C;AAE3C,iDAA+C;AAE/C,+DAA0D;AAC1D,sDAAgD;AAChD,gDAA4C;AAC5C,gEAAgE;AAChE,gEAA4D;AAC5D,+CAAgF;AAChF,6DAA+D;AAe/D,gHAAgH;AAChH,MAAM,KAAK,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,iBAAiB,CAAU,CAAA;AAExE;;;GAGG;AACH,SAAS,KAAK,CAAC,KAAuB,EAAE,OAAgC;IACtE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,KAAK,CAAA;IACvC,MAAM,GAAG,GAAwB,EAAE,GAAG,MAAM,EAAE,CAAA;IAC9C,MAAM,MAAM,GAAG,EAAE,GAAG,OAAO,EAAE,GAAG,GAAG,EAAE,CAAA;IACrC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,IAAI,iCAAmB,CAAC,SAAS,CAAA;IACjE,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAEvB,IAAI,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI;QAAE,MAAM,IAAI,eAAO,CAAC,2BAA2B,EAAE,EAAE,EAAE,6BAA6B,CAAC,CAAA;IAC5G,IAAI,GAAG,CAAC,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,6BAAY,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC;QAC3E,MAAM,IAAI,eAAO,CAAC,2BAA2B,EAAE,EAAE,EAAE,6BAA6B,CAAC,CAAA;IACnF,IAAI,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,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H,MAAM,SAAS,GAAG,CAAC,MAAiB,EAAE,EAAE,CAAC,CAAC;YACxC,SAAS,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;YACxD,cAAc,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;SACpE,CAAC,CAAA;QACF,KAAK,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,KAAK;YACtC,MAAM,IAAA,iCAAe,EAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA;QAC9E,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 { paymentTargetOf } from '../payment/payment-targets'\nimport { ForecastStatus, Transaction, TransactionCategory } 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 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 */\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 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 [targetType, ofKind] of kinds)\n await paymentTargetOf(targetType)?.onSaved?.(tx, domain, touchedOf(ofKind))\n }\n\n return saved\n}\n"]}
|