@things-factory/biz-base 10.1.283 → 10.1.291

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist-client/counterparty-register-form.d.ts +6 -0
  2. package/dist-client/counterparty-register-form.js +37 -11
  3. package/dist-client/counterparty-register.d.ts +12 -0
  4. package/dist-client/counterparty-register.js +26 -8
  5. package/dist-client/counterparty-select.js +7 -2
  6. package/dist-client/index.d.ts +1 -1
  7. package/dist-client/index.js +1 -1
  8. package/dist-server/migrations/1795000000000-issue-party-identifiers.d.ts +11 -0
  9. package/dist-server/migrations/1795000000000-issue-party-identifiers.js +20 -0
  10. package/dist-server/role-tasks.js +2 -0
  11. package/dist-server/service/counterparty/counterparty-choice.d.ts +11 -3
  12. package/dist-server/service/counterparty/counterparty-choice.js +22 -5
  13. package/dist-server/service/counterparty/counterparty-query.d.ts +1 -0
  14. package/dist-server/service/counterparty/counterparty-query.js +20 -3
  15. package/dist-server/service/counterparty/counterparty-scope.d.ts +47 -0
  16. package/dist-server/service/counterparty/counterparty-scope.js +111 -0
  17. package/dist-server/service/counterparty/counterparty-service.d.ts +11 -0
  18. package/dist-server/service/counterparty/counterparty-service.js +64 -2
  19. package/dist-server/service/counterparty/counterparty-standing-resolver.d.ts +9 -0
  20. package/dist-server/service/counterparty/counterparty-standing-resolver.js +94 -0
  21. package/dist-server/service/counterparty/counterparty-standing.d.ts +54 -0
  22. package/dist-server/service/counterparty/counterparty-standing.js +206 -0
  23. package/dist-server/service/counterparty/counterparty-type.d.ts +2 -0
  24. package/dist-server/service/counterparty/counterparty-type.js +8 -0
  25. package/dist-server/service/counterparty/counterparty.d.ts +22 -0
  26. package/dist-server/service/counterparty/counterparty.js +44 -2
  27. package/dist-server/service/counterparty/index.d.ts +2 -1
  28. package/dist-server/service/counterparty/index.js +2 -1
  29. package/dist-server/service/index.d.ts +3 -1
  30. package/dist-server/service/index.js +2 -0
  31. package/dist-server/work-doors.js +1 -1
  32. package/package.json +6 -4
  33. package/translations/en.json +17 -1
  34. package/translations/es.json +17 -1
  35. package/translations/ja.json +17 -1
  36. package/translations/ko.json +17 -1
  37. package/translations/ms.json +17 -1
  38. package/translations/zh.json +17 -1
@@ -12,6 +12,17 @@ type Saved = (tx: EntityManager, domain: {
12
12
  }, saved: Counterparty[]) => Promise<void>;
13
13
  /** Run after every save of counterparties, in the same transaction. */
14
14
  export declare function onCounterpartiesSaved(listener: Saved): void;
15
+ /** Tell the listeners - for a door of this module that saves counterparties other than `saveCounterparties`. */
16
+ export declare function announceCounterpartiesSaved(tx: EntityManager, domain: {
17
+ id: string;
18
+ }, saved: Counterparty[]): Promise<void>;
19
+ /**
20
+ * A PGLN as stored: its 13 digits, the GS1 check digit right (GS1 General Specifications, GLN). Spaces and dashes people
21
+ * write are dropped; anything else is refused, not trimmed into a number - a wrong GLN names somebody else.
22
+ */
23
+ export declare function pglnOf(value: unknown): string | null;
24
+ /** A new counterparty as the row it writes - names trimmed, kind, country, number and GLN in their stored form. */
25
+ export declare function newCounterpartyRowOf(patch: Partial<CounterpartyPatch>): Partial<Counterparty>;
15
26
  /**
16
27
  * Apply grid rows to a domain's counterparties: `+` (or no id) registers, `M` changes, `-` deletes (softly). A
17
28
  * counterparty a contract, a bank line or any other row still names is not deleted (§`refuseTiedRows`). Two
@@ -1,17 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.onCounterpartiesSaved = onCounterpartiesSaved;
4
+ exports.announceCounterpartiesSaved = announceCounterpartiesSaved;
5
+ exports.pglnOf = pglnOf;
6
+ exports.newCounterpartyRowOf = newCounterpartyRowOf;
4
7
  exports.saveCounterparties = saveCounterparties;
8
+ const crypto_1 = require("crypto");
5
9
  const typeorm_1 = require("typeorm");
6
10
  const shell_1 = require("@things-factory/shell");
7
11
  const counterparty_1 = require("./counterparty");
8
12
  const counterparty_bank_account_1 = require("./counterparty-bank-account");
9
13
  const counterparty_names_1 = require("./counterparty-names");
14
+ const counterparty_scope_1 = require("./counterparty-scope");
10
15
  const listeners = [];
11
16
  /** Run after every save of counterparties, in the same transaction. */
12
17
  function onCounterpartiesSaved(listener) {
13
18
  listeners.push(listener);
14
19
  }
20
+ /** Tell the listeners - for a door of this module that saves counterparties other than `saveCounterparties`. */
21
+ async function announceCounterpartiesSaved(tx, domain, saved) {
22
+ for (const listener of listeners)
23
+ await listener(tx, domain, saved);
24
+ }
15
25
  /** The words people write for the kind, as well as the values themselves. */
16
26
  const KIND_WORDS = {
17
27
  [counterparty_1.CounterpartyKind.COMPANY]: ['COMPANY', '사업자', '법인', '개인사업자', '회사', '기업'],
@@ -34,6 +44,22 @@ const TEXT = ['aliases', 'branchNumber', 'representative', 'address', 'billingAd
34
44
  * them; it is our company's place in the list, by the names the bank writes it under (ADR-0132 §0-2).
35
45
  */
36
46
  const COMPANY_FACTS = ['businessNumber', 'branchNumber', 'representative', 'address', 'billingAddress', 'businessType', 'businessItem'];
47
+ /**
48
+ * A PGLN as stored: its 13 digits, the GS1 check digit right (GS1 General Specifications, GLN). Spaces and dashes people
49
+ * write are dropped; anything else is refused, not trimmed into a number - a wrong GLN names somebody else.
50
+ */
51
+ function pglnOf(value) {
52
+ const text = String(value ?? '').trim();
53
+ if (!text)
54
+ return null;
55
+ const digits = text.replace(/[\s-]/g, '');
56
+ if (!/^\d{13}$/.test(digits))
57
+ throw new shell_1.Refusal('pgln-invalid', { text }, `'${text}' is not a GLN - 13 digits`);
58
+ const sum = [...digits.slice(0, 12)].reverse().reduce((total, digit, i) => total + Number(digit) * (i % 2 === 0 ? 3 : 1), 0);
59
+ if ((10 - (sum % 10)) % 10 !== Number(digits[12]))
60
+ throw new shell_1.Refusal('pgln-invalid', { text }, `'${text}' is not a GLN - its check digit is wrong`);
61
+ return digits;
62
+ }
37
63
  /** A patch as the row it writes: names trimmed, the kind and the country in their stored form. The number is `numbered`'s. */
38
64
  function rowOf(patch, isNew) {
39
65
  const row = {};
@@ -59,6 +85,8 @@ function rowOf(patch, isNew) {
59
85
  row.zeroRated = true;
60
86
  if (patch.active !== undefined)
61
87
  row.active = patch.active !== false;
88
+ if (patch.pgln !== undefined)
89
+ row.pgln = pglnOf(patch.pgln);
62
90
  return row;
63
91
  }
64
92
  /** The row with its business number in the stored form of its country - the country it has after the change. */
@@ -67,6 +95,10 @@ function numbered(patch, row, current) {
67
95
  return { ...row, businessNumber: (0, counterparty_names_1.businessNumberOf)(patch.businessNumber, 'country' in row ? row.country : current?.country) };
68
96
  return row;
69
97
  }
98
+ /** A new counterparty as the row it writes - names trimmed, kind, country, number and GLN in their stored form. */
99
+ function newCounterpartyRowOf(patch) {
100
+ return numbered(patch, rowOf(patch, true));
101
+ }
70
102
  /**
71
103
  * A `SELF` counterparty holds none of our company's facts, and a domain has one. `rows` are all the rows after the
72
104
  * batch, `written` the ones it writes - only what the batch writes is refused, as with the business number.
@@ -81,6 +113,22 @@ function refuseSelfMisuse(rows, written) {
81
113
  if (selves.length > 1 && written.some(one => one.kind === counterparty_1.CounterpartyKind.SELF))
82
114
  throw new shell_1.Refusal('counterparty-self-taken', { existing: selves[0].name, name: selves[1].name }, `'${selves[0].name}' is already our own company - a domain has one`);
83
115
  }
116
+ /** A PGLN is one counterparty's in the domain, as a business number is - the rows after the batch, less those it deletes. */
117
+ function pglnClash(existing, written, deletes) {
118
+ const holders = new Map();
119
+ for (const one of existing)
120
+ if (one.pgln && !deletes.includes(one.id) && !written.some(w => w.id && w.id === one.id))
121
+ holders.set(one.pgln, one);
122
+ for (const one of written) {
123
+ if (!one.pgln)
124
+ continue;
125
+ const held = holders.get(one.pgln);
126
+ if (held && held.id !== one.id)
127
+ return { pgln: one.pgln, existing: held.name ?? '' };
128
+ holders.set(one.pgln, one);
129
+ }
130
+ return undefined;
131
+ }
84
132
  /**
85
133
  * Apply grid rows to a domain's counterparties: `+` (or no id) registers, `M` changes, `-` deletes (softly). A
86
134
  * counterparty a contract, a bank line or any other row still names is not deleted (§`refuseTiedRows`). Two
@@ -88,6 +136,13 @@ function refuseSelfMisuse(rows, written) {
88
136
  * company is one counterparty with none of its facts (§`refuseSelfMisuse`).
89
137
  */
90
138
  async function saveCounterparties(tx, domain, user, patches) {
139
+ /*
140
+ * A domain that reads its list from another keeps none of its own here (ADR-0211 decision 9-2): a site registers a
141
+ * party it meets as provisional, and the owner confirms it - that door is not this one.
142
+ */
143
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(tx, domain);
144
+ if (scope.ownerId !== domain.id)
145
+ throw new shell_1.Refusal('counterparty-not-owner', { owner: scope.ownerId }, 'this domain reads its counterparties from the domain that owns the list - they are kept there');
91
146
  const repo = tx.getRepository(counterparty_1.Counterparty);
92
147
  const deletes = patches.filter(one => one.cuFlag === '-' && one.id).map(one => one.id);
93
148
  const changed = patches.filter(one => one.id && one.cuFlag !== '-' && one.cuFlag !== '+');
@@ -106,6 +161,9 @@ async function saveCounterparties(tx, domain, user, patches) {
106
161
  const clash = (0, counterparty_names_1.numberClash)(existing, [...updates, ...creates], deletes);
107
162
  if (clash)
108
163
  throw new shell_1.Refusal('counterparty-number-clash', clash, `business number ${clash.number} is already '${clash.existing}' - edit that counterparty instead`);
164
+ const pglnTaken = pglnClash(existing, [...updates, ...creates], deletes);
165
+ if (pglnTaken)
166
+ throw new shell_1.Refusal('counterparty-pgln-clash', pglnTaken, `GLN ${pglnTaken.pgln} is already '${pglnTaken.existing}' - edit that counterparty instead`);
109
167
  const after = new Map(existing.filter(one => !deletes.includes(one.id)).map(one => [one.id, one]));
110
168
  for (const row of updates)
111
169
  after.set(row.id, { ...after.get(row.id), ...row });
@@ -124,8 +182,12 @@ async function saveCounterparties(tx, domain, user, patches) {
124
182
  const saved = [];
125
183
  for (const row of updates)
126
184
  saved.push(await repo.save({ ...currents.get(row.id), ...row, updater: user }));
127
- for (const row of creates)
128
- saved.push(await repo.save({ ...row, domain, creator: user, updater: user }));
185
+ /* Each new row is named once, under its domain's namespace, by its own id (ADR-0211 decisions 3, 11). */
186
+ const namespace = creates.length ? await (0, counterparty_scope_1.partyNamespaceOf)(tx, domain) : '';
187
+ for (const row of creates) {
188
+ const id = (0, crypto_1.randomUUID)();
189
+ saved.push(await repo.save({ ...row, id, partyIdentifier: (0, counterparty_scope_1.issuePartyIdentifier)(namespace, id), domain, creator: user, updater: user }));
190
+ }
129
191
  for (const listener of listeners)
130
192
  await listener(tx, domain, saved);
131
193
  return saved;
@@ -0,0 +1,9 @@
1
+ import { Counterparty } from './counterparty';
2
+ import { NewCounterparty } from './counterparty-type';
3
+ export declare class CounterpartyStandingResolver {
4
+ registerProvisionalCounterparty(input: NewCounterparty, context: ResolverContext): Promise<Counterparty>;
5
+ provisionalCounterparties(context: ResolverContext): Promise<Counterparty[]>;
6
+ confirmCounterparties(ids: string[], reason: string, context: ResolverContext): Promise<Counterparty[]>;
7
+ mergeCounterparty(id: string, into: string, reason: string, context: ResolverContext): Promise<Counterparty>;
8
+ unmergeCounterparty(id: string, reason: string, context: ResolverContext): Promise<Counterparty>;
9
+ }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CounterpartyStandingResolver = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const type_graphql_1 = require("type-graphql");
6
+ const shell_1 = require("@things-factory/shell");
7
+ const counterparty_1 = require("./counterparty");
8
+ const counterparty_standing_1 = require("./counterparty-standing");
9
+ const counterparty_type_1 = require("./counterparty-type");
10
+ /*
11
+ * The doors of ADR-0211 decision 10. Registering where a party is met is its own narrow privilege
12
+ * (`counterparty-registration`, task `biz-base.counterparty-registering`) - a gate, a dock or a sales seat makes a
13
+ * provisional row and nothing more. Confirming and merging are the keeper's (`counterparty:mutation`) in the domain
14
+ * that owns the list.
15
+ */
16
+ let CounterpartyStandingResolver = class CounterpartyStandingResolver {
17
+ async registerProvisionalCounterparty(input, context) {
18
+ const { tx, domain, user } = context.state;
19
+ return await (0, counterparty_standing_1.registerProvisionalCounterparty)(tx, domain, user, input);
20
+ }
21
+ async provisionalCounterparties(context) {
22
+ return await (0, counterparty_standing_1.provisionalCounterpartiesUnder)((0, shell_1.getRepository)(counterparty_1.Counterparty).manager, context.state.domain.id);
23
+ }
24
+ async confirmCounterparties(ids, reason, context) {
25
+ const { tx, domain, user } = context.state;
26
+ return await (0, counterparty_standing_1.confirmCounterparties)(tx, domain, user, ids, reason);
27
+ }
28
+ async mergeCounterparty(id, into, reason, context) {
29
+ const { tx, domain, user } = context.state;
30
+ return await (0, counterparty_standing_1.mergeCounterparty)(tx, domain, user, id, into, reason);
31
+ }
32
+ async unmergeCounterparty(id, reason, context) {
33
+ const { tx, domain, user } = context.state;
34
+ return await (0, counterparty_standing_1.unmergeCounterparty)(tx, domain, user, id, reason);
35
+ }
36
+ };
37
+ exports.CounterpartyStandingResolver = CounterpartyStandingResolver;
38
+ tslib_1.__decorate([
39
+ (0, type_graphql_1.Directive)('@transaction'),
40
+ (0, type_graphql_1.Directive)('@privilege(category: "counterparty-registration", privilege: "mutation", domainOwnerGranted: true)'),
41
+ (0, type_graphql_1.Mutation)(returns => counterparty_1.Counterparty, { description: 'Register a counterparty where it was met - provisional, usable at once; the one already kept when its number or GLN is known' }),
42
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('counterparty')),
43
+ tslib_1.__param(1, (0, type_graphql_1.Ctx)()),
44
+ tslib_1.__metadata("design:type", Function),
45
+ tslib_1.__metadata("design:paramtypes", [counterparty_type_1.NewCounterparty, Object]),
46
+ tslib_1.__metadata("design:returntype", Promise)
47
+ ], CounterpartyStandingResolver.prototype, "registerProvisionalCounterparty", null);
48
+ tslib_1.__decorate([
49
+ (0, type_graphql_1.Directive)('@privilege(category: "counterparty", privilege: "query", domainOwnerGranted: true)'),
50
+ (0, type_graphql_1.Query)(returns => [counterparty_1.Counterparty], { description: 'The provisional counterparties waiting for this domain, as the owner of the list, to confirm or merge them' }),
51
+ tslib_1.__param(0, (0, type_graphql_1.Ctx)()),
52
+ tslib_1.__metadata("design:type", Function),
53
+ tslib_1.__metadata("design:paramtypes", [Object]),
54
+ tslib_1.__metadata("design:returntype", Promise)
55
+ ], CounterpartyStandingResolver.prototype, "provisionalCounterparties", null);
56
+ tslib_1.__decorate([
57
+ (0, type_graphql_1.Directive)('@transaction'),
58
+ (0, type_graphql_1.Directive)('@privilege(category: "counterparty", privilege: "mutation", domainOwnerGranted: true)'),
59
+ (0, type_graphql_1.Mutation)(returns => [counterparty_1.Counterparty], { description: "Confirm provisional counterparties - each moves to this domain's list, its id and identifier kept" }),
60
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('ids', type => [String])),
61
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('reason', { nullable: true })),
62
+ tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
63
+ tslib_1.__metadata("design:type", Function),
64
+ tslib_1.__metadata("design:paramtypes", [Array, String, Object]),
65
+ tslib_1.__metadata("design:returntype", Promise)
66
+ ], CounterpartyStandingResolver.prototype, "confirmCounterparties", null);
67
+ tslib_1.__decorate([
68
+ (0, type_graphql_1.Directive)('@transaction'),
69
+ (0, type_graphql_1.Directive)('@privilege(category: "counterparty", privilege: "mutation", domainOwnerGranted: true)'),
70
+ (0, type_graphql_1.Mutation)(returns => counterparty_1.Counterparty, { description: 'A provisional counterparty is one this domain keeps already - it points there and stays' }),
71
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
72
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('into')),
73
+ tslib_1.__param(2, (0, type_graphql_1.Arg)('reason', { nullable: true })),
74
+ tslib_1.__param(3, (0, type_graphql_1.Ctx)()),
75
+ tslib_1.__metadata("design:type", Function),
76
+ tslib_1.__metadata("design:paramtypes", [String, String, String, Object]),
77
+ tslib_1.__metadata("design:returntype", Promise)
78
+ ], CounterpartyStandingResolver.prototype, "mergeCounterparty", null);
79
+ tslib_1.__decorate([
80
+ (0, type_graphql_1.Directive)('@transaction'),
81
+ (0, type_graphql_1.Directive)('@privilege(category: "counterparty", privilege: "mutation", domainOwnerGranted: true)'),
82
+ (0, type_graphql_1.Mutation)(returns => counterparty_1.Counterparty, { description: 'Take a merge back - the counterparty waits to be confirmed again' }),
83
+ tslib_1.__param(0, (0, type_graphql_1.Arg)('id')),
84
+ tslib_1.__param(1, (0, type_graphql_1.Arg)('reason', { nullable: true })),
85
+ tslib_1.__param(2, (0, type_graphql_1.Ctx)()),
86
+ tslib_1.__metadata("design:type", Function),
87
+ tslib_1.__metadata("design:paramtypes", [String, String, Object]),
88
+ tslib_1.__metadata("design:returntype", Promise)
89
+ ], CounterpartyStandingResolver.prototype, "unmergeCounterparty", null);
90
+ exports.CounterpartyStandingResolver = CounterpartyStandingResolver = tslib_1.__decorate([
91
+ (0, type_graphql_1.Resolver)(counterparty_1.Counterparty),
92
+ (0, type_graphql_1.UseMiddleware)(shell_1.SpeakRefusals)
93
+ ], CounterpartyStandingResolver);
94
+ //# sourceMappingURL=counterparty-standing-resolver.js.map
@@ -0,0 +1,54 @@
1
+ import { EntityManager } from 'typeorm';
2
+ import { Counterparty } from './counterparty';
3
+ import { CounterpartyPatch } from './counterparty-type';
4
+ type WaitingChanged = (tx: EntityManager, ownerId: string) => Promise<void>;
5
+ /**
6
+ * Hear when what waits for an owner changes - a counterparty registered where it was met, confirmed, merged or unmerged.
7
+ * Not `onCounterpartiesSaved`: a listener there links rows by name, and a merged row is no counterparty to link to.
8
+ */
9
+ export declare function onProvisionalCounterpartiesChanged(listener: WaitingChanged): void;
10
+ /** The fact kind this module writes to fact-change - what moved on a counterparty's standing. */
11
+ export declare const COUNTERPARTY_FACT_KIND = "counterparty";
12
+ /**
13
+ * The domains whose list `ownerId` keeps: itself and those under it, less any subtree whose top declares a list of its
14
+ * own (ADR-0211 decision 9-1 - the closest owner wins).
15
+ */
16
+ export declare function domainsReadingFrom(tx: EntityManager, ownerId: string): Promise<string[]>;
17
+ /** What a provisional registration writes - who the party is, nothing the keeper keeps about it (ADR-0211 decision 10-1). */
18
+ export declare const PROVISIONAL_FIELDS: readonly ["name", "kind", "country", "businessNumber", "pgln", "aliases"];
19
+ /**
20
+ * Register a counterparty where it was met (ADR-0211 decisions 9-3, 10-1, 10-2). Not a new row when the list already has
21
+ * the party by its number or GLN - that row is the answer. Our own company is the owner's to keep, not a site's.
22
+ */
23
+ export declare function registerProvisionalCounterparty(tx: EntityManager, domain: {
24
+ id: string;
25
+ }, user: any, input: Partial<CounterpartyPatch>): Promise<Counterparty>;
26
+ /** The provisional counterparties waiting for the owner `ownerId` - registered under it, neither confirmed nor merged. */
27
+ export declare function provisionalCounterpartiesUnder(tx: EntityManager, ownerId: string): Promise<Counterparty[]>;
28
+ /**
29
+ * Confirm provisional counterparties: each moves to the owner's list, its id and identifier kept, so every row and event
30
+ * that named it still does (ADR-0211 decision 10-3). One the owner already has by its number or GLN is refused - it is
31
+ * to be merged, not kept twice.
32
+ */
33
+ export declare function confirmCounterparties(tx: EntityManager, domain: {
34
+ id: string;
35
+ }, user: any, ids: string[], reason?: string): Promise<Counterparty[]>;
36
+ /**
37
+ * The provisional counterparty `id` is the owner's `intoId` (ADR-0211 decision 10-4). The row is not deleted - whatever
38
+ * named it resolves by following `mergedInto` one step - and so the merge can be taken back (`unmergeCounterparty`).
39
+ */
40
+ export declare function mergeCounterparty(tx: EntityManager, domain: {
41
+ id: string;
42
+ }, user: any, id: string, intoId: string, reason?: string): Promise<Counterparty>;
43
+ /** Take a merge back - the row waits to be confirmed again. */
44
+ export declare function unmergeCounterparty(tx: EntityManager, domain: {
45
+ id: string;
46
+ }, user: any, id: string, reason?: string): Promise<Counterparty>;
47
+ /** The counterparty a row names, following a merge one step - what a reader of an old row asks. */
48
+ export declare function counterpartyFollowingMerge(tx: EntityManager, id: string): Promise<Counterparty | null>;
49
+ /**
50
+ * Money leaves only toward a confirmed counterparty (ADR-0211 decision 10-2). A paying door asks this before it saves;
51
+ * a merged one is refused too - pay the one it was merged into.
52
+ */
53
+ export declare function assertConfirmedCounterparty(tx: EntityManager, id: string | null | undefined): Promise<void>;
54
+ export {};
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROVISIONAL_FIELDS = exports.COUNTERPARTY_FACT_KIND = void 0;
4
+ exports.onProvisionalCounterpartiesChanged = onProvisionalCounterpartiesChanged;
5
+ exports.domainsReadingFrom = domainsReadingFrom;
6
+ exports.registerProvisionalCounterparty = registerProvisionalCounterparty;
7
+ exports.provisionalCounterpartiesUnder = provisionalCounterpartiesUnder;
8
+ exports.confirmCounterparties = confirmCounterparties;
9
+ exports.mergeCounterparty = mergeCounterparty;
10
+ exports.unmergeCounterparty = unmergeCounterparty;
11
+ exports.counterpartyFollowingMerge = counterpartyFollowingMerge;
12
+ exports.assertConfirmedCounterparty = assertConfirmedCounterparty;
13
+ const crypto_1 = require("crypto");
14
+ const typeorm_1 = require("typeorm");
15
+ const fact_change_1 = require("@things-factory/fact-change");
16
+ const shell_1 = require("@things-factory/shell");
17
+ const counterparty_1 = require("./counterparty");
18
+ const counterparty_bank_account_1 = require("./counterparty-bank-account");
19
+ const counterparty_service_1 = require("./counterparty-service");
20
+ const counterparty_scope_1 = require("./counterparty-scope");
21
+ const waitingListeners = [];
22
+ /**
23
+ * Hear when what waits for an owner changes - a counterparty registered where it was met, confirmed, merged or unmerged.
24
+ * Not `onCounterpartiesSaved`: a listener there links rows by name, and a merged row is no counterparty to link to.
25
+ */
26
+ function onProvisionalCounterpartiesChanged(listener) {
27
+ waitingListeners.push(listener);
28
+ }
29
+ async function waitingChanged(tx, ownerId) {
30
+ for (const listener of waitingListeners)
31
+ await listener(tx, ownerId);
32
+ }
33
+ /** The fact kind this module writes to fact-change - what moved on a counterparty's standing. */
34
+ exports.COUNTERPARTY_FACT_KIND = 'counterparty';
35
+ /**
36
+ * The domains whose list `ownerId` keeps: itself and those under it, less any subtree whose top declares a list of its
37
+ * own (ADR-0211 decision 9-1 - the closest owner wins).
38
+ */
39
+ async function domainsReadingFrom(tx, ownerId) {
40
+ const found = [ownerId];
41
+ let frontier = [ownerId];
42
+ while (frontier.length) {
43
+ const children = await tx.getRepository(shell_1.Domain).find({ where: { parent: { id: (0, typeorm_1.In)(frontier) } }, select: ['id'] });
44
+ if (!children.length)
45
+ break;
46
+ const owners = new Set((await tx.getRepository(shell_1.EnvVar).find({ where: { domain: { id: (0, typeorm_1.In)(children.map(one => one.id)) }, name: counterparty_scope_1.COUNTERPARTY_LIST_OWNER_VAR, active: true } }))
47
+ .filter(one => String(one.value ?? '').trim().toLowerCase() === 'true')
48
+ .map(one => one.domainId));
49
+ frontier = children.map(one => one.id).filter(id => !owners.has(id) && !found.includes(id));
50
+ found.push(...frontier);
51
+ }
52
+ return found;
53
+ }
54
+ /** What a provisional registration writes - who the party is, nothing the keeper keeps about it (ADR-0211 decision 10-1). */
55
+ exports.PROVISIONAL_FIELDS = ['name', 'kind', 'country', 'businessNumber', 'pgln', 'aliases'];
56
+ /** The same party by what identifies it past its name - a business number or a GLN - among `rows`, following a merge one step. */
57
+ function sameParty(rows, row) {
58
+ const hit = rows.find(one => (row.businessNumber && one.businessNumber === row.businessNumber) || (row.pgln && one.pgln === row.pgln));
59
+ if (!hit?.mergedIntoId)
60
+ return hit;
61
+ return rows.find(one => one.id === hit.mergedIntoId) ?? hit;
62
+ }
63
+ /**
64
+ * Register a counterparty where it was met (ADR-0211 decisions 9-3, 10-1, 10-2). Not a new row when the list already has
65
+ * the party by its number or GLN - that row is the answer. Our own company is the owner's to keep, not a site's.
66
+ */
67
+ async function registerProvisionalCounterparty(tx, domain, user, input) {
68
+ /* Only what identifies the party (decision 10-1) - the rest is the keeper's to write once it is confirmed. */
69
+ const row = (0, counterparty_service_1.newCounterpartyRowOf)(Object.fromEntries(exports.PROVISIONAL_FIELDS.filter(field => input[field] !== undefined).map(field => [field, input[field]])));
70
+ if (row.kind === counterparty_1.CounterpartyKind.SELF)
71
+ throw new shell_1.Refusal('counterparty-self-not-provisional', {}, 'our own company is kept by the owner of the list, not registered where it is met');
72
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(tx, domain);
73
+ const repo = tx.getRepository(counterparty_1.Counterparty);
74
+ if (row.businessNumber || row.pgln) {
75
+ const readable = (await repo.find({ where: { domain: { id: (0, typeorm_1.In)([scope.domainId, scope.ownerId]) } } })).filter(one => (0, counterparty_scope_1.isReadableBy)(one, scope));
76
+ const known = sameParty(readable, row);
77
+ if (known)
78
+ return known;
79
+ }
80
+ const id = (0, crypto_1.randomUUID)();
81
+ const namespace = await (0, counterparty_scope_1.partyNamespaceOf)(tx, domain);
82
+ const saved = await repo.save({
83
+ ...row,
84
+ id,
85
+ partyIdentifier: (0, counterparty_scope_1.issuePartyIdentifier)(namespace, id),
86
+ standing: counterparty_1.CounterpartyStanding.PROVISIONAL,
87
+ domain,
88
+ creator: user,
89
+ updater: user
90
+ });
91
+ await (0, counterparty_service_1.announceCounterpartiesSaved)(tx, domain, [saved]);
92
+ await waitingChanged(tx, scope.ownerId);
93
+ return saved;
94
+ }
95
+ /** The provisional counterparties waiting for the owner `ownerId` - registered under it, neither confirmed nor merged. */
96
+ async function provisionalCounterpartiesUnder(tx, ownerId) {
97
+ const under = await domainsReadingFrom(tx, ownerId);
98
+ return await tx.getRepository(counterparty_1.Counterparty).find({
99
+ where: { domain: { id: (0, typeorm_1.In)(under) }, standing: counterparty_1.CounterpartyStanding.PROVISIONAL, mergedInto: (0, typeorm_1.IsNull)() },
100
+ order: { createdAt: 'ASC' }
101
+ });
102
+ }
103
+ async function refuseUnlessOwner(tx, domain) {
104
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(tx, domain);
105
+ if (scope.ownerId !== domain.id)
106
+ throw new shell_1.Refusal('counterparty-not-owner', { owner: scope.ownerId }, 'only the domain that owns the counterparty list confirms or merges');
107
+ }
108
+ async function waitingRows(tx, ownerId, ids) {
109
+ const waiting = await provisionalCounterpartiesUnder(tx, ownerId);
110
+ const rows = ids.map(id => waiting.find(one => one.id === id));
111
+ if (rows.some(one => !one))
112
+ throw new shell_1.Refusal('counterparty-not-provisional', {}, 'a counterparty is not waiting to be confirmed - reload and try again');
113
+ return rows;
114
+ }
115
+ /**
116
+ * Confirm provisional counterparties: each moves to the owner's list, its id and identifier kept, so every row and event
117
+ * that named it still does (ADR-0211 decision 10-3). One the owner already has by its number or GLN is refused - it is
118
+ * to be merged, not kept twice.
119
+ */
120
+ async function confirmCounterparties(tx, domain, user, ids, reason) {
121
+ await refuseUnlessOwner(tx, domain);
122
+ const rows = await waitingRows(tx, domain.id, [...new Set(ids)]);
123
+ const repo = tx.getRepository(counterparty_1.Counterparty);
124
+ const kept = await repo.find({ where: { domain: { id: domain.id } } });
125
+ const confirmed = [];
126
+ for (const row of rows) {
127
+ const twin = sameParty(kept.filter(one => one.id !== row.id), row);
128
+ if (twin)
129
+ throw new shell_1.Refusal('counterparty-confirm-clash', { name: row.name, existing: twin.name }, `'${row.name}' is '${twin.name}' already - merge it into that one`);
130
+ const from = row.domainId;
131
+ if (from !== domain.id) {
132
+ await repo.update({ id: row.id }, { domain: { id: domain.id }, standing: counterparty_1.CounterpartyStanding.CONFIRMED, updater: user });
133
+ await tx.getRepository(counterparty_bank_account_1.CounterpartyBankAccount).update({ counterparty: { id: row.id } }, { domain: { id: domain.id } });
134
+ }
135
+ else {
136
+ await repo.update({ id: row.id }, { standing: counterparty_1.CounterpartyStanding.CONFIRMED, updater: user });
137
+ }
138
+ await (0, fact_change_1.recordFactChanges)(tx, domain, {
139
+ factKind: exports.COUNTERPARTY_FACT_KIND,
140
+ factName: row.id,
141
+ changes: [
142
+ { field: 'standing', fromValue: counterparty_1.CounterpartyStanding.PROVISIONAL, toValue: counterparty_1.CounterpartyStanding.CONFIRMED },
143
+ ...(from !== domain.id ? [{ field: 'domain', fromValue: from, toValue: domain.id }] : [])
144
+ ]
145
+ }, { user, source: 'confirm', reason });
146
+ const after = (await repo.findOneBy({ id: row.id }));
147
+ kept.push(after);
148
+ confirmed.push(after);
149
+ }
150
+ await (0, counterparty_service_1.announceCounterpartiesSaved)(tx, domain, confirmed);
151
+ await waitingChanged(tx, domain.id);
152
+ return confirmed;
153
+ }
154
+ /**
155
+ * The provisional counterparty `id` is the owner's `intoId` (ADR-0211 decision 10-4). The row is not deleted - whatever
156
+ * named it resolves by following `mergedInto` one step - and so the merge can be taken back (`unmergeCounterparty`).
157
+ */
158
+ async function mergeCounterparty(tx, domain, user, id, intoId, reason) {
159
+ await refuseUnlessOwner(tx, domain);
160
+ const [row] = await waitingRows(tx, domain.id, [id]);
161
+ const repo = tx.getRepository(counterparty_1.Counterparty);
162
+ const into = await repo.findOne({ where: { id: intoId, domain: { id: domain.id }, mergedInto: (0, typeorm_1.IsNull)() } });
163
+ if (!into || into.id === row.id)
164
+ throw new shell_1.Refusal('counterparty-merge-target', {}, 'merge into a counterparty of this list');
165
+ await repo.update({ id: row.id }, { mergedInto: { id: into.id }, updater: user });
166
+ await (0, fact_change_1.recordFactChanges)(tx, domain, { factKind: exports.COUNTERPARTY_FACT_KIND, factName: row.id, changes: [{ field: 'mergedInto', toValue: into.id }] }, { user, source: 'merge', reason });
167
+ await waitingChanged(tx, domain.id);
168
+ return (await repo.findOneBy({ id: row.id }));
169
+ }
170
+ /** Take a merge back - the row waits to be confirmed again. */
171
+ async function unmergeCounterparty(tx, domain, user, id, reason) {
172
+ await refuseUnlessOwner(tx, domain);
173
+ const repo = tx.getRepository(counterparty_1.Counterparty);
174
+ const under = await domainsReadingFrom(tx, domain.id);
175
+ const row = await repo.findOne({ where: { id, domain: { id: (0, typeorm_1.In)(under) } } });
176
+ if (!row?.mergedIntoId)
177
+ throw new shell_1.Refusal('counterparty-not-merged', {}, 'the counterparty is not merged into another');
178
+ await repo.update({ id: row.id }, { mergedInto: null, updater: user });
179
+ await (0, fact_change_1.recordFactChanges)(tx, domain, { factKind: exports.COUNTERPARTY_FACT_KIND, factName: row.id, changes: [{ field: 'mergedInto', fromValue: row.mergedIntoId }] }, { user, source: 'unmerge', reason });
180
+ await waitingChanged(tx, domain.id);
181
+ return (await repo.findOneBy({ id: row.id }));
182
+ }
183
+ /** The counterparty a row names, following a merge one step - what a reader of an old row asks. */
184
+ async function counterpartyFollowingMerge(tx, id) {
185
+ const repo = tx.getRepository(counterparty_1.Counterparty);
186
+ const row = await repo.findOne({ where: { id }, withDeleted: true });
187
+ if (!row?.mergedIntoId)
188
+ return row;
189
+ return (await repo.findOne({ where: { id: row.mergedIntoId }, withDeleted: true })) ?? row;
190
+ }
191
+ /**
192
+ * Money leaves only toward a confirmed counterparty (ADR-0211 decision 10-2). A paying door asks this before it saves;
193
+ * a merged one is refused too - pay the one it was merged into.
194
+ */
195
+ async function assertConfirmedCounterparty(tx, id) {
196
+ if (!id)
197
+ return;
198
+ const row = await tx.getRepository(counterparty_1.Counterparty).findOne({ where: { id } });
199
+ if (!row)
200
+ return;
201
+ if (row.mergedIntoId)
202
+ throw new shell_1.Refusal('counterparty-merged', { name: row.name }, `'${row.name}' was merged into another counterparty - choose that one`);
203
+ if (row.standing === counterparty_1.CounterpartyStanding.PROVISIONAL)
204
+ throw new shell_1.Refusal('counterparty-not-confirmed', { name: row.name }, `'${row.name}' is registered provisionally - money is paid only to a confirmed counterparty`);
205
+ }
206
+ //# sourceMappingURL=counterparty-standing.js.map
@@ -5,6 +5,7 @@ export declare class NewCounterparty {
5
5
  kind?: CounterpartyKind;
6
6
  country?: string;
7
7
  businessNumber?: string;
8
+ pgln?: string;
8
9
  branchNumber?: string;
9
10
  representative?: string;
10
11
  address?: string;
@@ -23,6 +24,7 @@ export declare class CounterpartyPatch {
23
24
  kind?: string;
24
25
  country?: string;
25
26
  businessNumber?: string;
27
+ pgln?: string;
26
28
  branchNumber?: string;
27
29
  representative?: string;
28
30
  address?: string;
@@ -27,6 +27,10 @@ tslib_1.__decorate([
27
27
  (0, type_graphql_1.Field)({ nullable: true, description: 'Business registration number' }),
28
28
  tslib_1.__metadata("design:type", String)
29
29
  ], NewCounterparty.prototype, "businessNumber", void 0);
30
+ tslib_1.__decorate([
31
+ (0, type_graphql_1.Field)({ nullable: true, description: 'GS1 GLN identifying it as a party (PGLN), 13 digits' }),
32
+ tslib_1.__metadata("design:type", String)
33
+ ], NewCounterparty.prototype, "pgln", void 0);
30
34
  tslib_1.__decorate([
31
35
  (0, type_graphql_1.Field)({ nullable: true, description: 'Sub-business place number' }),
32
36
  tslib_1.__metadata("design:type", String)
@@ -97,6 +101,10 @@ tslib_1.__decorate([
97
101
  (0, type_graphql_1.Field)({ nullable: true, description: 'Business registration number' }),
98
102
  tslib_1.__metadata("design:type", String)
99
103
  ], CounterpartyPatch.prototype, "businessNumber", void 0);
104
+ tslib_1.__decorate([
105
+ (0, type_graphql_1.Field)({ nullable: true, description: 'GS1 GLN identifying it as a party (PGLN), 13 digits' }),
106
+ tslib_1.__metadata("design:type", String)
107
+ ], CounterpartyPatch.prototype, "pgln", void 0);
100
108
  tslib_1.__decorate([
101
109
  (0, type_graphql_1.Field)({ nullable: true, description: 'Sub-business place number' }),
102
110
  tslib_1.__metadata("design:type", String)
@@ -12,6 +12,15 @@ export declare enum CounterpartyKind {
12
12
  PERSON = "PERSON",
13
13
  SELF = "SELF"
14
14
  }
15
+ /**
16
+ * Whether the list's owner has confirmed a counterparty (ADR-0211 decision 10-2). Every row there was before is
17
+ * `CONFIRMED`; a site registers a `PROVISIONAL` one where it meets a party it does not know, and the owning domain
18
+ * confirms or merges it. Money leaves only toward a confirmed one.
19
+ */
20
+ export declare enum CounterpartyStanding {
21
+ PROVISIONAL = "PROVISIONAL",
22
+ CONFIRMED = "CONFIRMED"
23
+ }
15
24
  /**
16
25
  * A company or person a domain signs with, bills, is billed by, or pays — its own list of them.
17
26
  *
@@ -33,6 +42,19 @@ export declare class Counterparty {
33
42
  kind: CounterpartyKind;
34
43
  country?: string;
35
44
  businessNumber?: string;
45
+ /**
46
+ * The name of this counterparty past its own database - on an event, to another product or site, to another system
47
+ * (ADR-0211 decisions 3, 11, 13). Issued once when the row is made - `<namespace>/sd/<this id, 32 hex>` by the contract's
48
+ * `partyUri` - and never changed: a confirmed row keeps its id, a merged row stays. Inside the database a row points
49
+ * at the counterparty by `id`; people read its name.
50
+ */
51
+ partyIdentifier?: string;
52
+ /** Its GS1 Global Location Number as a party (PGLN), when it has one - another name it is known by, not its identifier (ADR-0211 decision 11-3). */
53
+ pgln?: string;
54
+ standing: CounterpartyStanding;
55
+ /** The counterparty this one turned out to be (ADR-0211 decision 10-4) - the row stays so what named it still resolves; a reader follows one step. */
56
+ mergedInto?: Counterparty;
57
+ mergedIntoId?: string;
36
58
  branchNumber?: string;
37
59
  representative?: string;
38
60
  address?: string;