@things-factory/biz-base 10.1.282 → 10.1.290

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
@@ -13,6 +13,11 @@ export declare class CounterpartyRegisterForm extends CounterpartyRegisterForm_b
13
13
  static styles: import("lit").CSSResult[];
14
14
  /** The name the picker was searched by - the form starts from it. */
15
15
  name: string;
16
+ /**
17
+ * A seat that registers where it meets a party, not the keeper: the form asks only who the party is, does not read the
18
+ * list by name (that is the keeper's read), and the counterparty waits for the owner of the list to confirm it.
19
+ */
20
+ provisional: boolean;
16
21
  private kind;
17
22
  private businessNumber;
18
23
  private representative;
@@ -21,6 +26,7 @@ export declare class CounterpartyRegisterForm extends CounterpartyRegisterForm_b
21
26
  private timer?;
22
27
  private sameNamed;
23
28
  private save;
29
+ private saveProvisional;
24
30
  connectedCallback(): void;
25
31
  /** What the name check says for the name now in the field. */
26
32
  private get check();
@@ -31,6 +31,18 @@ const REGISTER = gql `
31
31
  }
32
32
  }
33
33
  `;
34
+ /* Where a party is met: provisional, and the one already kept when its number is known (ADR-0211 decisions 9-3, 10-1). */
35
+ const REGISTER_PROVISIONAL = gql `
36
+ mutation ($counterparty: NewCounterparty!) {
37
+ registerProvisionalCounterparty(counterparty: $counterparty) {
38
+ id
39
+ name
40
+ kind
41
+ businessNumber
42
+ standing
43
+ }
44
+ }
45
+ `;
34
46
  /**
35
47
  * Create a counterparty from the picker through createCounterparty. Collect name, kind and known
36
48
  * registration details; emit counterparty on selection and close on cancellation. For a normalized existing
@@ -41,17 +53,23 @@ let CounterpartyRegisterForm = class CounterpartyRegisterForm extends localize(i
41
53
  super(...arguments);
42
54
  /** The name the picker was searched by - the form starts from it. */
43
55
  this.name = '';
56
+ /**
57
+ * A seat that registers where it meets a party, not the keeper: the form asks only who the party is, does not read the
58
+ * list by name (that is the keeper's read), and the counterparty waits for the owner of the list to confirm it.
59
+ */
60
+ this.provisional = false;
44
61
  this.kind = 'COMPANY';
45
62
  this.businessNumber = '';
46
63
  this.representative = '';
47
64
  /** The name asked about - set once the person stops typing. */
48
65
  this.asked = '';
49
66
  this.sameNamed = new QueryController(this, SAME_NAMED, {
50
- variables: () => (this.asked ? { name: this.asked } : undefined),
67
+ variables: () => (this.asked && !this.provisional ? { name: this.asked } : undefined),
51
68
  fetchPolicy: 'no-cache',
52
69
  context: gqlContext()
53
70
  });
54
71
  this.save = new MutationController(this, REGISTER, { context: gqlContext(), showsError: true });
72
+ this.saveProvisional = new MutationController(this, REGISTER_PROVISIONAL, { context: gqlContext(), showsError: true });
55
73
  }
56
74
  /* The shared popup layout (page-standard sections 7, 8): only the body scrolls, labels above native inputs. */
57
75
  static { this.styles = [
@@ -105,6 +123,8 @@ let CounterpartyRegisterForm = class CounterpartyRegisterForm extends localize(i
105
123
  /** What the name check says for the name now in the field. */
106
124
  get check() {
107
125
  const name = this.name.trim();
126
+ if (this.provisional)
127
+ return name ? 'free' : 'idle';
108
128
  if (!name || this.asked !== name)
109
129
  return 'idle';
110
130
  if (this.sameNamed.loading)
@@ -115,13 +135,13 @@ let CounterpartyRegisterForm = class CounterpartyRegisterForm extends localize(i
115
135
  return found.length ? 'taken' : 'free';
116
136
  }
117
137
  get registrable() {
118
- return this.check === 'free' && !this.save.pending;
138
+ return this.check === 'free' && !this.save.pending && !this.saveProvisional.pending;
119
139
  }
120
140
  render() {
121
141
  const check = this.check;
122
142
  return html `
123
143
  <div class="body">
124
- <p guide>${i18next.t('text.counterparty-register-guide')}</p>
144
+ <p guide>${i18next.t(this.provisional ? 'text.counterparty-register-provisional-guide' : 'text.counterparty-register-guide')}</p>
125
145
 
126
146
  <label class="field">
127
147
  <span>${i18next.t('field.counterparty-name')}</span>
@@ -148,10 +168,12 @@ let CounterpartyRegisterForm = class CounterpartyRegisterForm extends localize(i
148
168
  <span>${i18next.t('text.business-number-hint')}</span>
149
169
  </label>
150
170
 
151
- <label class="field">
152
- <span>${i18next.t('field.representative')}</span>
153
- <input name="representative" .value=${this.representative} @input=${(e) => (this.representative = e.target.value)} />
154
- </label>
171
+ ${this.provisional
172
+ ? nothing
173
+ : html `<label class="field">
174
+ <span>${i18next.t('field.representative')}</span>
175
+ <input name="representative" .value=${this.representative} @input=${(e) => (this.representative = e.target.value)} />
176
+ </label>`}
155
177
  </div>
156
178
 
157
179
  <ox-popup-actions>
@@ -186,21 +208,25 @@ let CounterpartyRegisterForm = class CounterpartyRegisterForm extends localize(i
186
208
  name: this.name.trim(),
187
209
  kind: this.kind,
188
210
  ...(this.businessNumber.trim() ? { businessNumber: this.businessNumber.trim() } : {}),
189
- ...(this.representative.trim() ? { representative: this.representative.trim() } : {})
211
+ ...(!this.provisional && this.representative.trim() ? { representative: this.representative.trim() } : {})
190
212
  };
191
- const data = await this.save.run({ counterparty });
192
- const saved = data?.createCounterparty;
213
+ const data = this.provisional ? await this.saveProvisional.run({ counterparty }) : await this.save.run({ counterparty });
214
+ const saved = this.provisional ? data?.registerProvisionalCounterparty : data?.createCounterparty;
193
215
  if (saved)
194
216
  this.take(saved);
195
217
  }
196
218
  take(one) {
197
- this.dispatchEvent(new CustomEvent('counterparty', { detail: { id: one.id, name: one.name, businessNumber: one.businessNumber ?? null, kind: one.kind ?? null } }));
219
+ this.dispatchEvent(new CustomEvent('counterparty', { detail: { id: one.id, name: one.name, businessNumber: one.businessNumber ?? null, kind: one.kind ?? null, standing: one.standing ?? null } }));
198
220
  }
199
221
  };
200
222
  __decorate([
201
223
  property({ type: String }),
202
224
  __metadata("design:type", Object)
203
225
  ], CounterpartyRegisterForm.prototype, "name", void 0);
226
+ __decorate([
227
+ property({ type: Boolean }),
228
+ __metadata("design:type", Object)
229
+ ], CounterpartyRegisterForm.prototype, "provisional", void 0);
204
230
  __decorate([
205
231
  state(),
206
232
  __metadata("design:type", Object)
@@ -5,6 +5,7 @@ export type CounterpartyPick = {
5
5
  name: string;
6
6
  businessNumber?: string | null;
7
7
  kind?: string | null;
8
+ standing?: string | null;
8
9
  };
9
10
  /** Registering a counterparty is the counterparty keeper's - the privilege `createCounterparty` asks (ADR-0195 decision 5). */
10
11
  export declare const COUNTERPARTY_REGISTER_PRIVILEGE: {
@@ -12,6 +13,17 @@ export declare const COUNTERPARTY_REGISTER_PRIVILEGE: {
12
13
  privilege: string;
13
14
  domainOwnerGranted: boolean;
14
15
  };
16
+ /**
17
+ * Registering where a party is met - a gate, a dock, a sales seat - makes a provisional counterparty and nothing more
18
+ * (operato-application ADR-0211 decision 10-1): `registerProvisionalCounterparty` asks this.
19
+ */
20
+ export declare const COUNTERPARTY_PROVISIONAL_PRIVILEGE: {
21
+ category: string;
22
+ privilege: string;
23
+ domainOwnerGranted: boolean;
24
+ };
25
+ /** How this seat registers: as the keeper (`keep`), provisionally (`provisional`), or not at all. */
26
+ export declare function counterpartyRegistrationMode(): Promise<'keep' | 'provisional' | undefined>;
15
27
  /** Whether this seat may register a counterparty - where it is not, the pickers offer no registering. */
16
28
  export declare function mayRegisterCounterparty(): Promise<boolean>;
17
29
  /**
@@ -5,25 +5,43 @@ import { openPopup } from '@operato/layout';
5
5
  import { hasPrivilege } from '@things-factory/auth-base/dist-client';
6
6
  /** Registering a counterparty is the counterparty keeper's - the privilege `createCounterparty` asks (ADR-0195 decision 5). */
7
7
  export const COUNTERPARTY_REGISTER_PRIVILEGE = { category: 'counterparty', privilege: 'mutation', domainOwnerGranted: true };
8
+ /**
9
+ * Registering where a party is met - a gate, a dock, a sales seat - makes a provisional counterparty and nothing more
10
+ * (operato-application ADR-0211 decision 10-1): `registerProvisionalCounterparty` asks this.
11
+ */
12
+ export const COUNTERPARTY_PROVISIONAL_PRIVILEGE = { category: 'counterparty-registration', privilege: 'mutation', domainOwnerGranted: true };
13
+ /** How this seat registers: as the keeper (`keep`), provisionally (`provisional`), or not at all. */
14
+ export async function counterpartyRegistrationMode() {
15
+ const holds = async (privilege) => {
16
+ try {
17
+ return !!(await hasPrivilege(privilege));
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ };
23
+ if (await holds(COUNTERPARTY_REGISTER_PRIVILEGE))
24
+ return 'keep';
25
+ if (await holds(COUNTERPARTY_PROVISIONAL_PRIVILEGE))
26
+ return 'provisional';
27
+ return undefined;
28
+ }
8
29
  /** Whether this seat may register a counterparty - where it is not, the pickers offer no registering. */
9
30
  export async function mayRegisterCounterparty() {
10
- try {
11
- return !!(await hasPrivilege(COUNTERPARTY_REGISTER_PRIVILEGE));
12
- }
13
- catch {
14
- return false;
15
- }
31
+ return !!(await counterpartyRegistrationMode());
16
32
  }
17
33
  /**
18
34
  * Register a counterparty from the name a picker was searched by, in the short form (ADR-0195 decision 3). Resolves the
19
35
  * counterparty to take - the one registered, or the one of the same name the form led to - or undefined when the
20
36
  * person closed the form.
21
37
  */
22
- export function registerCounterparty(name) {
23
- return new Promise(resolve => {
38
+ export async function registerCounterparty(name) {
39
+ const provisional = (await counterpartyRegistrationMode()) === 'provisional';
40
+ return await new Promise(resolve => {
24
41
  let taken;
25
42
  const handle = openPopup(html `<counterparty-register-form
26
43
  .name=${name}
44
+ .provisional=${provisional}
27
45
  @close=${() => handle.close()}
28
46
  @counterparty=${(e) => ((taken = e.detail), handle.close())}
29
47
  ></counterparty-register-form>`, { backdrop: true, size: 'medium', title: i18next.t('title.counterparty-register') });
@@ -10,7 +10,7 @@ import { mayRegisterCounterparty, registerCounterparty } from './counterparty-re
10
10
  const CHOICES = gql `
11
11
  query ($search: String, $pagination: Pagination) {
12
12
  counterparties: counterpartyChoices(search: $search, pagination: $pagination) {
13
- items { id name businessNumber }
13
+ items { id name businessNumber standing }
14
14
  }
15
15
  }
16
16
  `;
@@ -103,6 +103,11 @@ let CounterpartySelect = class CounterpartySelect extends localize(i18next)(LitE
103
103
  li small {
104
104
  white-space: nowrap;
105
105
  }
106
+
107
+ /* A counterparty registered where it was met, not yet confirmed (ADR-0211 decision 10-2). */
108
+ li small[provisional] {
109
+ color: var(--md-sys-color-tertiary);
110
+ }
106
111
  li small,
107
112
  li.none {
108
113
  color: var(--ui-muted, var(--md-sys-color-on-surface-variant));
@@ -154,7 +159,7 @@ let CounterpartySelect = class CounterpartySelect extends localize(i18next)(LitE
154
159
  ? html `<ul role="listbox">
155
160
  ${this.found.length
156
161
  ? this.found.map((one, index) => html `<li role="option" ?active=${index === this.active} @mousedown=${(e) => (e.preventDefault(), this.choose(one))}>
157
- <span>${one.name}</span>${one.businessNumber ? html `<small>${one.businessNumber}</small>` : nothing}
162
+ <span>${one.name}</span>${one.businessNumber ? html `<small>${one.businessNumber}</small>` : nothing}${one.standing === 'PROVISIONAL' ? html `<small provisional>${i18next.t('text.counterparty-provisional')}</small>` : nothing}
158
163
  </li>`)
159
164
  : html `<li class="none">${i18next.t('text.counterparty-none')}</li>`}
160
165
  ${this.newName
@@ -1,3 +1,3 @@
1
1
  export { CounterpartySelect } from './counterparty-select.js';
2
2
  export { CounterpartyRegisterForm } from './counterparty-register-form.js';
3
- export { COUNTERPARTY_REGISTER_PRIVILEGE, counterpartyCreatable, mayRegisterCounterparty, registerCounterparty, type CounterpartyPick } from './counterparty-register.js';
3
+ export { COUNTERPARTY_PROVISIONAL_PRIVILEGE, COUNTERPARTY_REGISTER_PRIVILEGE, counterpartyCreatable, counterpartyRegistrationMode, mayRegisterCounterparty, registerCounterparty, type CounterpartyPick } from './counterparty-register.js';
@@ -1,4 +1,4 @@
1
1
  export { CounterpartySelect } from './counterparty-select.js';
2
2
  export { CounterpartyRegisterForm } from './counterparty-register-form.js';
3
- export { COUNTERPARTY_REGISTER_PRIVILEGE, counterpartyCreatable, mayRegisterCounterparty, registerCounterparty } from './counterparty-register.js';
3
+ export { COUNTERPARTY_PROVISIONAL_PRIVILEGE, COUNTERPARTY_REGISTER_PRIVILEGE, counterpartyCreatable, counterpartyRegistrationMode, mayRegisterCounterparty, registerCounterparty } from './counterparty-register.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ import { MigrationInterface, QueryRunner } from 'typeorm';
2
+ /**
3
+ * Name the counterparties there were before party identifiers (ADR-0211 decisions 11-6, 12 step 2). Every one stays
4
+ * `CONFIRMED` (the column's default) - nothing a domain does changes. Idempotent: a named row is passed over.
5
+ *
6
+ * Not undone on `down`: an identifier may already be on an event or with another system, and is never taken back (ADR-0038).
7
+ */
8
+ export declare class IssuePartyIdentifiers1795000000000 implements MigrationInterface {
9
+ up(queryRunner: QueryRunner): Promise<void>;
10
+ down(_queryRunner: QueryRunner): Promise<void>;
11
+ }
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IssuePartyIdentifiers1795000000000 = void 0;
4
+ const counterparty_scope_1 = require("../service/counterparty/counterparty-scope");
5
+ /**
6
+ * Name the counterparties there were before party identifiers (ADR-0211 decisions 11-6, 12 step 2). Every one stays
7
+ * `CONFIRMED` (the column's default) - nothing a domain does changes. Idempotent: a named row is passed over.
8
+ *
9
+ * Not undone on `down`: an identifier may already be on an event or with another system, and is never taken back (ADR-0038).
10
+ */
11
+ class IssuePartyIdentifiers1795000000000 {
12
+ async up(queryRunner) {
13
+ const named = await (0, counterparty_scope_1.issueMissingPartyIdentifiers)(queryRunner.manager);
14
+ // eslint-disable-next-line no-console
15
+ console.log(`[IssuePartyIdentifiers] named ${named} counterparties`);
16
+ }
17
+ async down(_queryRunner) { }
18
+ }
19
+ exports.IssuePartyIdentifiers1795000000000 = IssuePartyIdentifiers1795000000000;
20
+ //# sourceMappingURL=1795000000000-issue-party-identifiers.js.map
@@ -11,6 +11,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.ROLE_TASKS = void 0;
12
12
  exports.ROLE_TASKS = [
13
13
  { id: 'biz-base.counterparty-keeping', grants: [{ category: 'counterparty', axes: ['query', 'mutation'] }] },
14
+ /* Registering a party where it is met - a gate, a dock, a sales seat - provisional and nothing more (ADR-0211 decision 10-1). */
15
+ { id: 'biz-base.counterparty-registering', grants: [{ category: 'counterparty-registration', axes: ['mutation'] }, { category: 'counterparty-published', axes: ['query'] }] },
14
16
  /* 인감 대장 - the seals, their keepers and impressions, and which one documents print (ADR-0188). */
15
17
  { id: 'biz-base.seal-keeping', grants: [{ category: 'company-seal', axes: ['query', 'mutation'] }] },
16
18
  { id: 'biz-base.company-keeping', grants: [{ category: 'company', axes: ['query', 'mutation'] }, { category: 'bizplace', axes: ['query', 'mutation'] }, { category: 'biz-option', axes: ['query', 'mutation'] }] }
@@ -1,6 +1,6 @@
1
1
  import { Repository } from 'typeorm';
2
2
  import { ListParam } from '@things-factory/shell';
3
- import { Counterparty, CounterpartyKind } from './counterparty';
3
+ import { Counterparty, CounterpartyKind, CounterpartyStanding } from './counterparty';
4
4
  import { CounterpartyBankAccount } from './counterparty-bank-account';
5
5
  /** What the list door searches - the counterparty keeper's door. */
6
6
  export declare const COUNTERPARTY_SEARCHABLES: string[];
@@ -14,6 +14,8 @@ export declare class CounterpartyChoice {
14
14
  name: string;
15
15
  kind: CounterpartyKind;
16
16
  businessNumber?: string;
17
+ partyIdentifier?: string;
18
+ standing?: CounterpartyStanding;
17
19
  }
18
20
  export declare class CounterpartyChoiceList {
19
21
  items: CounterpartyChoice[];
@@ -34,10 +36,14 @@ export interface ListRules {
34
36
  defaultLimit?: number;
35
37
  maxLimit?: number;
36
38
  }
37
- /** One page of a domain's counterparties - the list door and the choice door read through this one function. */
39
+ /**
40
+ * One page of the counterparties a domain reads - the list door and the choice door read through this one function. A
41
+ * domain under an owner of the list reads the owner's too (ADR-0211 decision 9), so the scope is this module's, not the
42
+ * list's `inherited` switch (which knows only a parent, and no owner).
43
+ */
38
44
  export declare function counterpartyPage(repository: Repository<Counterparty>, domain: {
39
45
  id: string;
40
- }, params: ListParam, rules: ListRules): Promise<{
46
+ }, params: ListParam, rules: ListRules, offered?: boolean): Promise<{
41
47
  items: Counterparty[];
42
48
  total: number;
43
49
  }>;
@@ -53,6 +59,8 @@ export declare function counterpartyChoicesOf(repository: Repository<Counterpart
53
59
  name: string;
54
60
  kind: CounterpartyKind;
55
61
  businessNumber: string;
62
+ partyIdentifier: string;
63
+ standing: CounterpartyStanding;
56
64
  }[];
57
65
  total: number;
58
66
  }>;
@@ -9,6 +9,7 @@ const tslib_1 = require("tslib");
9
9
  const type_graphql_1 = require("type-graphql");
10
10
  const shell_1 = require("@things-factory/shell");
11
11
  const counterparty_1 = require("./counterparty");
12
+ const counterparty_scope_1 = require("./counterparty-scope");
12
13
  /*
13
14
  * Choosing a counterparty without reading it (ADR-0139, design/published-read-privilege): `counterparty-published`
14
15
  * opens what points at a counterparty and nothing else. Its types are its own - no relation to follow - so the closed
@@ -41,6 +42,14 @@ tslib_1.__decorate([
41
42
  (0, type_graphql_1.Field)({ nullable: true, description: 'Business registration number - tells apart two counterparties of one name (ADR-0132)' }),
42
43
  tslib_1.__metadata("design:type", String)
43
44
  ], CounterpartyChoice.prototype, "businessNumber", void 0);
45
+ tslib_1.__decorate([
46
+ (0, type_graphql_1.Field)({ nullable: true, description: 'The URI that names it outside the database - what an event or another product carries (ADR-0211 decision 13)' }),
47
+ tslib_1.__metadata("design:type", String)
48
+ ], CounterpartyChoice.prototype, "partyIdentifier", void 0);
49
+ tslib_1.__decorate([
50
+ (0, type_graphql_1.Field)(type => counterparty_1.CounterpartyStanding, { nullable: true, description: 'Provisional until the owner of the list confirms it - shown, so a picker says so' }),
51
+ tslib_1.__metadata("design:type", String)
52
+ ], CounterpartyChoice.prototype, "standing", void 0);
44
53
  exports.CounterpartyChoice = CounterpartyChoice = tslib_1.__decorate([
45
54
  (0, type_graphql_1.ObjectType)({ description: 'A counterparty as one picks it: which one, and nothing about it' })
46
55
  ], CounterpartyChoice);
@@ -81,10 +90,18 @@ function accountTailOf(number) {
81
90
  const digits = String(number ?? '').replace(/\D/g, '');
82
91
  return digits ? digits.slice(-4) : undefined;
83
92
  }
84
- /** One page of a domain's counterparties - the list door and the choice door read through this one function. */
85
- async function counterpartyPage(repository, domain, params, rules) {
93
+ /**
94
+ * One page of the counterparties a domain reads - the list door and the choice door read through this one function. A
95
+ * domain under an owner of the list reads the owner's too (ADR-0211 decision 9), so the scope is this module's, not the
96
+ * list's `inherited` switch (which knows only a parent, and no owner).
97
+ */
98
+ async function counterpartyPage(repository, domain, params, rules, offered = false) {
99
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(repository.manager, domain);
86
100
  /* Counterparties are found by name - their order is the name's, after any column the reader sorts by. */
87
- const queryBuilder = (0, shell_1.getQueryBuilderFromListParams)({ domain: domain, params, repository, ...rules, alias: 'counterparty', defaultSortings: [{ name: 'name' }] });
101
+ const queryBuilder = (0, counterparty_scope_1.readableBy)((0, shell_1.getQueryBuilderFromListParams)({ params, repository, ...rules, alias: 'counterparty', defaultSortings: [{ name: 'name' }] }), 'counterparty', scope);
102
+ /* A merged counterparty is not offered - the one it was merged into is (ADR-0211 decision 10-4). The keeper's list shows both. */
103
+ if (offered)
104
+ queryBuilder.andWhere('counterparty.mergedInto IS NULL');
88
105
  const [items, total] = await queryBuilder.getManyAndCount();
89
106
  return { items, total };
90
107
  }
@@ -101,8 +118,8 @@ async function counterpartyChoicesOf(repository, domain, params) {
101
118
  sortables: exports.CHOICE_SEARCHABLES,
102
119
  defaultLimit: exports.CHOICE_LIMIT,
103
120
  maxLimit: exports.CHOICE_LIMIT
104
- });
105
- return { items: items.map(one => ({ id: one.id, name: one.name, kind: one.kind, businessNumber: one.businessNumber })), total };
121
+ }, true);
122
+ return { items: items.map(one => ({ id: one.id, name: one.name, kind: one.kind, businessNumber: one.businessNumber, partyIdentifier: one.partyIdentifier, standing: one.standing })), total };
106
123
  }
107
124
  /** The accounts one counterparty is paid into, as one picks them. */
108
125
  async function counterpartyAccountChoicesOf(repository, domain, counterpartyId) {
@@ -10,6 +10,7 @@ export declare class CounterpartyQuery {
10
10
  counterpartiesNamed(name: string, context: ResolverContext): Promise<CounterpartyChoice[]>;
11
11
  counterpartyAccountChoices(counterpartyId: string, context: ResolverContext): Promise<CounterpartyAccountChoice[]>;
12
12
  domain(counterparty: Counterparty): Promise<Domain | null>;
13
+ mergedInto(counterparty: Counterparty): Promise<Counterparty | null>;
13
14
  creator(counterparty: Counterparty): Promise<User | null>;
14
15
  updater(counterparty: Counterparty): Promise<User | null>;
15
16
  }
@@ -3,16 +3,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CounterpartyQuery = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  const type_graphql_1 = require("type-graphql");
6
+ const typeorm_1 = require("typeorm");
6
7
  const auth_base_1 = require("@things-factory/auth-base");
7
8
  const shell_1 = require("@things-factory/shell");
8
9
  const counterparty_1 = require("./counterparty");
9
10
  const counterparty_bank_account_1 = require("./counterparty-bank-account");
10
11
  const counterparty_names_1 = require("./counterparty-names");
11
12
  const counterparty_type_1 = require("./counterparty-type");
13
+ const counterparty_scope_1 = require("./counterparty-scope");
12
14
  const counterparty_choice_1 = require("./counterparty-choice");
13
15
  let CounterpartyQuery = class CounterpartyQuery {
14
16
  async counterparty(id, context) {
15
- return await (0, shell_1.getRepository)(counterparty_1.Counterparty).findOne({ where: { domain: { id: context.state.domain.id }, id } });
17
+ const repository = (0, shell_1.getRepository)(counterparty_1.Counterparty);
18
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(repository.manager, context.state.domain);
19
+ const found = await repository.findOne({ where: { domain: { id: (0, typeorm_1.In)([scope.domainId, scope.ownerId]) }, id } });
20
+ return found && (0, counterparty_scope_1.isReadableBy)(found, scope) ? found : null;
16
21
  }
17
22
  async counterparties(params, context) {
18
23
  return await (0, counterparty_choice_1.counterpartyPage)((0, shell_1.getRepository)(counterparty_1.Counterparty), context.state.domain, params, { searchables: counterparty_choice_1.COUNTERPARTY_SEARCHABLES });
@@ -27,8 +32,10 @@ let CounterpartyQuery = class CounterpartyQuery {
27
32
  * alias is not what a choice shows.
28
33
  */
29
34
  async counterpartiesNamed(name, context) {
30
- const parties = await (0, shell_1.getRepository)(counterparty_1.Counterparty).find({ where: { domain: { id: context.state.domain.id }, active: true } });
31
- return (0, counterparty_names_1.sameNamed)(parties, name).map(({ id, name, kind, businessNumber }) => ({ id, name, kind, businessNumber }));
35
+ const repository = (0, shell_1.getRepository)(counterparty_1.Counterparty);
36
+ const scope = await (0, counterparty_scope_1.counterpartyScopeOf)(repository.manager, context.state.domain);
37
+ const parties = (await repository.find({ where: { domain: { id: (0, typeorm_1.In)([scope.domainId, scope.ownerId]) }, active: true } })).filter(one => (0, counterparty_scope_1.isReadableBy)(one, scope) && !one.mergedIntoId);
38
+ return (0, counterparty_names_1.sameNamed)(parties, name).map(({ id, name, kind, businessNumber, partyIdentifier, standing }) => ({ id, name, kind, businessNumber, partyIdentifier, standing }));
32
39
  }
33
40
  async counterpartyAccountChoices(counterpartyId, context) {
34
41
  return await (0, counterparty_choice_1.counterpartyAccountChoicesOf)((0, shell_1.getRepository)(counterparty_bank_account_1.CounterpartyBankAccount), context.state.domain, counterpartyId);
@@ -36,6 +43,9 @@ let CounterpartyQuery = class CounterpartyQuery {
36
43
  async domain(counterparty) {
37
44
  return counterparty.domain ?? (counterparty.domainId ? await (0, shell_1.getRepository)(shell_1.Domain).findOneBy({ id: counterparty.domainId }) : null);
38
45
  }
46
+ async mergedInto(counterparty) {
47
+ return counterparty.mergedInto ?? (counterparty.mergedIntoId ? await (0, shell_1.getRepository)(counterparty_1.Counterparty).findOneBy({ id: counterparty.mergedIntoId }) : null);
48
+ }
39
49
  async creator(counterparty) {
40
50
  return counterparty.creator ?? (counterparty.creatorId ? await (0, shell_1.getRepository)(auth_base_1.User).findOneBy({ id: counterparty.creatorId }) : null);
41
51
  }
@@ -96,6 +106,13 @@ tslib_1.__decorate([
96
106
  tslib_1.__metadata("design:paramtypes", [counterparty_1.Counterparty]),
97
107
  tslib_1.__metadata("design:returntype", Promise)
98
108
  ], CounterpartyQuery.prototype, "domain", null);
109
+ tslib_1.__decorate([
110
+ (0, type_graphql_1.FieldResolver)(type => counterparty_1.Counterparty, { nullable: true }),
111
+ tslib_1.__param(0, (0, type_graphql_1.Root)()),
112
+ tslib_1.__metadata("design:type", Function),
113
+ tslib_1.__metadata("design:paramtypes", [counterparty_1.Counterparty]),
114
+ tslib_1.__metadata("design:returntype", Promise)
115
+ ], CounterpartyQuery.prototype, "mergedInto", null);
99
116
  tslib_1.__decorate([
100
117
  (0, type_graphql_1.FieldResolver)(type => auth_base_1.User, { nullable: true }),
101
118
  tslib_1.__param(0, (0, type_graphql_1.Root)()),
@@ -0,0 +1,47 @@
1
+ import { EntityManager, SelectQueryBuilder } from 'typeorm';
2
+ import { Counterparty } from './counterparty';
3
+ /** A domain that keeps the counterparty list for the domains under it says so with this variable, value `true`. */
4
+ export declare const COUNTERPARTY_LIST_OWNER_VAR = "counterparty.list-owner";
5
+ /** The namespace a domain issues party identifiers under - an `http(s)://` URL of a domain it controls, or a URN namespace. */
6
+ export declare const PARTY_IDENTITY_NAMESPACE_VAR = "party.identity-namespace";
7
+ /**
8
+ * The namespace when no domain declares one (ADR-0211 decision 11-7): a subdomain of hatiolab.com kept for identifiers
9
+ * only, no tenant in the path - a row id is a uuid, unique across installations, and a subdomain may be renamed or reused.
10
+ */
11
+ export declare const PLATFORM_PARTY_NAMESPACE = "https://id.hatiolab.com";
12
+ /** Who reads which list: the domain asking, and the domain whose list it is (the same when it owns its own). */
13
+ export interface CounterpartyScope {
14
+ domainId: string;
15
+ ownerId: string;
16
+ }
17
+ /** The domain whose list `domain` reads: the closest one in its lineage that declares it owns a list, or itself. */
18
+ export declare function counterpartyScopeOf(tx: EntityManager, domain: {
19
+ id: string;
20
+ parentId?: string | null;
21
+ }): Promise<CounterpartyScope>;
22
+ /**
23
+ * The namespace identifiers are issued under for a counterparty kept in `domain` - its closest declaration, or the
24
+ * platform's. A declaration that is no namespace is refused, not passed over: an identifier issued under the platform
25
+ * while the site meant its own cannot be taken back (ADR-0038).
26
+ */
27
+ export declare function partyNamespaceOf(tx: EntityManager, domain: {
28
+ id: string;
29
+ parentId?: string | null;
30
+ }): Promise<string>;
31
+ /** The identifier of a counterparty row - issued by the contract's one rule (ADR-0211 decision 13-4); refused when it cannot be. */
32
+ export declare function issuePartyIdentifier(namespace: string, rowId: string): string;
33
+ /**
34
+ * Narrow a query on counterparties to what `scope` reads: its own rows, and the owner's - less the owner's people
35
+ * (ADR-0211 decision 9-5: an employee or a landlord is the owner's office's, not a site's). The owner reads only its own.
36
+ */
37
+ export declare function readableBy(qb: SelectQueryBuilder<Counterparty>, alias: string, scope: CounterpartyScope): SelectQueryBuilder<Counterparty>;
38
+ /** The same rule over rows already read - for doors that find by `find`, and for tests. */
39
+ export declare function isReadableBy(row: Pick<Counterparty, 'kind'> & {
40
+ domainId?: string;
41
+ }, scope: CounterpartyScope): boolean;
42
+ /**
43
+ * Name every counterparty that has no identifier yet - the rows there were before identifiers (ADR-0211 decision 11-6).
44
+ * Each is named under its own domain's namespace by its own id, deleted rows too: an old row still names them. Running it
45
+ * twice names nothing the second time. Returns how many it named.
46
+ */
47
+ export declare function issueMissingPartyIdentifiers(tx: EntityManager): Promise<number>;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PLATFORM_PARTY_NAMESPACE = exports.PARTY_IDENTITY_NAMESPACE_VAR = exports.COUNTERPARTY_LIST_OWNER_VAR = void 0;
4
+ exports.counterpartyScopeOf = counterpartyScopeOf;
5
+ exports.partyNamespaceOf = partyNamespaceOf;
6
+ exports.issuePartyIdentifier = issuePartyIdentifier;
7
+ exports.readableBy = readableBy;
8
+ exports.isReadableBy = isReadableBy;
9
+ exports.issueMissingPartyIdentifiers = issueMissingPartyIdentifiers;
10
+ const typeorm_1 = require("typeorm");
11
+ const ops_contract_1 = require("@operato/ops-contract");
12
+ const shell_1 = require("@things-factory/shell");
13
+ const counterparty_1 = require("./counterparty");
14
+ /*
15
+ * Whose counterparty list a domain reads, and under which namespace a counterparty is named (ADR-0211 decisions 9, 11).
16
+ *
17
+ * A site is a domain (operato-warehouse's `siteId` is `Domain.subdomain`), so one carrier would be a row per site if
18
+ * every domain kept its own list. A domain may instead declare that it owns the list - a company over its sites - and
19
+ * the sites under it read that list. The declaration is a domain variable, found by shell's ancestor walk; the closest
20
+ * domain that declares wins (a group may own one list, or each affiliate its own).
21
+ *
22
+ * Read in the caller's transaction: the save that issues an identifier must see the same declaration it writes under.
23
+ */
24
+ /** A domain that keeps the counterparty list for the domains under it says so with this variable, value `true`. */
25
+ exports.COUNTERPARTY_LIST_OWNER_VAR = 'counterparty.list-owner';
26
+ /** The namespace a domain issues party identifiers under - an `http(s)://` URL of a domain it controls, or a URN namespace. */
27
+ exports.PARTY_IDENTITY_NAMESPACE_VAR = 'party.identity-namespace';
28
+ /**
29
+ * The namespace when no domain declares one (ADR-0211 decision 11-7): a subdomain of hatiolab.com kept for identifiers
30
+ * only, no tenant in the path - a row id is a uuid, unique across installations, and a subdomain may be renamed or reused.
31
+ */
32
+ exports.PLATFORM_PARTY_NAMESPACE = 'https://id.hatiolab.com';
33
+ async function lineageOf(tx, domain) {
34
+ const row = 'parentId' in domain ? domain : await tx.getRepository(shell_1.Domain).findOne({ where: { id: domain.id } });
35
+ return await (0, shell_1.getDomainIdsWithAncestors)((row ?? domain), tx);
36
+ }
37
+ /** The closest declaration of `name` in the domain's lineage - its value and the domain that declared it. */
38
+ async function closestDeclaration(tx, lineage, name, accept) {
39
+ const vars = await tx.getRepository(shell_1.EnvVar).find({ where: { domain: { id: (0, typeorm_1.In)(lineage) }, name, active: true } });
40
+ const declared = vars.filter(one => accept(String(one.value ?? '').trim()));
41
+ declared.sort((a, b) => lineage.indexOf(a.domainId) - lineage.indexOf(b.domainId));
42
+ return declared[0] ? { value: String(declared[0].value).trim(), domainId: declared[0].domainId } : undefined;
43
+ }
44
+ /** The domain whose list `domain` reads: the closest one in its lineage that declares it owns a list, or itself. */
45
+ async function counterpartyScopeOf(tx, domain) {
46
+ const lineage = await lineageOf(tx, domain);
47
+ const owner = await closestDeclaration(tx, lineage, exports.COUNTERPARTY_LIST_OWNER_VAR, value => value.toLowerCase() === 'true');
48
+ return { domainId: domain.id, ownerId: owner?.domainId ?? domain.id };
49
+ }
50
+ /**
51
+ * The namespace identifiers are issued under for a counterparty kept in `domain` - its closest declaration, or the
52
+ * platform's. A declaration that is no namespace is refused, not passed over: an identifier issued under the platform
53
+ * while the site meant its own cannot be taken back (ADR-0038).
54
+ */
55
+ async function partyNamespaceOf(tx, domain) {
56
+ const lineage = await lineageOf(tx, domain);
57
+ const declared = await closestDeclaration(tx, lineage, exports.PARTY_IDENTITY_NAMESPACE_VAR, value => !!value);
58
+ if (!declared)
59
+ return exports.PLATFORM_PARTY_NAMESPACE;
60
+ if (!/^https?:\/\/[^/\s.]+(?:\.[^/\s.]+)+/.test(declared.value) && !/^urn:[^:\s]+/.test(declared.value))
61
+ throw new shell_1.Refusal('party-namespace-invalid', { value: declared.value }, `'${declared.value}' is no namespace to issue party identifiers under - an http(s) URL of a domain you control, or a URN namespace`);
62
+ return declared.value;
63
+ }
64
+ /** The identifier of a counterparty row - issued by the contract's one rule (ADR-0211 decision 13-4); refused when it cannot be. */
65
+ function issuePartyIdentifier(namespace, rowId) {
66
+ let uri;
67
+ try {
68
+ uri = (0, ops_contract_1.partyUri)(namespace, rowId);
69
+ }
70
+ catch (e) {
71
+ throw new shell_1.Refusal('party-identifier-invalid', { namespace }, String(e?.message ?? e));
72
+ }
73
+ if (!uri)
74
+ throw new shell_1.Refusal('party-namespace-invalid', { value: namespace }, `'${namespace}' is no namespace to issue party identifiers under`);
75
+ return uri;
76
+ }
77
+ /**
78
+ * Narrow a query on counterparties to what `scope` reads: its own rows, and the owner's - less the owner's people
79
+ * (ADR-0211 decision 9-5: an employee or a landlord is the owner's office's, not a site's). The owner reads only its own.
80
+ */
81
+ function readableBy(qb, alias, scope) {
82
+ if (scope.ownerId === scope.domainId)
83
+ return qb.andWhere(`${alias}.domain = :ownDomain`, { ownDomain: scope.domainId });
84
+ return qb.andWhere(new typeorm_1.Brackets(where => where
85
+ .where(`${alias}.domain = :ownDomain`, { ownDomain: scope.domainId })
86
+ .orWhere(`(${alias}.domain = :ownerDomain AND ${alias}.kind <> :person)`, { ownerDomain: scope.ownerId, person: counterparty_1.CounterpartyKind.PERSON })));
87
+ }
88
+ /** The same rule over rows already read - for doors that find by `find`, and for tests. */
89
+ function isReadableBy(row, scope) {
90
+ if (row.domainId === scope.domainId)
91
+ return true;
92
+ return row.domainId === scope.ownerId && row.kind !== counterparty_1.CounterpartyKind.PERSON;
93
+ }
94
+ /**
95
+ * Name every counterparty that has no identifier yet - the rows there were before identifiers (ADR-0211 decision 11-6).
96
+ * Each is named under its own domain's namespace by its own id, deleted rows too: an old row still names them. Running it
97
+ * twice names nothing the second time. Returns how many it named.
98
+ */
99
+ async function issueMissingPartyIdentifiers(tx) {
100
+ const repo = tx.getRepository(counterparty_1.Counterparty);
101
+ const unnamed = await repo.find({ withDeleted: true, where: { partyIdentifier: (0, typeorm_1.IsNull)() } });
102
+ const namespaces = new Map();
103
+ for (const one of unnamed) {
104
+ const domainId = one.domainId;
105
+ if (!namespaces.has(domainId))
106
+ namespaces.set(domainId, await partyNamespaceOf(tx, { id: domainId }));
107
+ await repo.update({ id: one.id }, { partyIdentifier: issuePartyIdentifier(namespaces.get(domainId), one.id) });
108
+ }
109
+ return unnamed.length;
110
+ }
111
+ //# sourceMappingURL=counterparty-scope.js.map