@mj-biz-apps/contracts-entities 0.1.0

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 (46) hide show
  1. package/LICENSE +183 -0
  2. package/dist/ContractEntity.d.ts +181 -0
  3. package/dist/ContractEntity.d.ts.map +1 -0
  4. package/dist/ContractEntity.js +261 -0
  5. package/dist/ContractEntity.js.map +1 -0
  6. package/dist/ContractTemplateEntity.d.ts +50 -0
  7. package/dist/ContractTemplateEntity.d.ts.map +1 -0
  8. package/dist/ContractTemplateEntity.js +85 -0
  9. package/dist/ContractTemplateEntity.js.map +1 -0
  10. package/dist/ContractTemplateModificationEntity.d.ts +46 -0
  11. package/dist/ContractTemplateModificationEntity.d.ts.map +1 -0
  12. package/dist/ContractTemplateModificationEntity.js +72 -0
  13. package/dist/ContractTemplateModificationEntity.js.map +1 -0
  14. package/dist/ContractTemplateProvisionEntity.d.ts +45 -0
  15. package/dist/ContractTemplateProvisionEntity.d.ts.map +1 -0
  16. package/dist/ContractTemplateProvisionEntity.js +73 -0
  17. package/dist/ContractTemplateProvisionEntity.js.map +1 -0
  18. package/dist/ContractTypeEntity.d.ts +55 -0
  19. package/dist/ContractTypeEntity.d.ts.map +1 -0
  20. package/dist/ContractTypeEntity.js +82 -0
  21. package/dist/ContractTypeEntity.js.map +1 -0
  22. package/dist/contract-state.d.ts +49 -0
  23. package/dist/contract-state.d.ts.map +1 -0
  24. package/dist/contract-state.js +48 -0
  25. package/dist/contract-state.js.map +1 -0
  26. package/dist/generated/entity_subclasses.d.ts +1235 -0
  27. package/dist/generated/entity_subclasses.d.ts.map +1 -0
  28. package/dist/generated/entity_subclasses.js +1817 -0
  29. package/dist/generated/entity_subclasses.js.map +1 -0
  30. package/dist/generated/remote_operations.d.ts +1145 -0
  31. package/dist/generated/remote_operations.d.ts.map +1 -0
  32. package/dist/generated/remote_operations.js +426 -0
  33. package/dist/generated/remote_operations.js.map +1 -0
  34. package/dist/index.d.ts +30 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +49 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/required-field-prose.d.ts +48 -0
  39. package/dist/required-field-prose.d.ts.map +1 -0
  40. package/dist/required-field-prose.js +55 -0
  41. package/dist/required-field-prose.js.map +1 -0
  42. package/dist/value-list-validation.d.ts +69 -0
  43. package/dist/value-list-validation.d.ts.map +1 -0
  44. package/dist/value-list-validation.js +88 -0
  45. package/dist/value-list-validation.js.map +1 -0
  46. package/package.json +33 -0
package/LICENSE ADDED
@@ -0,0 +1,183 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2024 MariaDB plc, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB plc.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Blue Cypress, Inc.
11
+
12
+ Licensed Work: MemberJunction.
13
+ The Licensed Work is (c) 2023-2026 Blue Cypress, Inc.
14
+
15
+ Additional Use Grant: Subject to the terms of this License, Licensor grants
16
+ you the following additional rights to make Production
17
+ Use of the Licensed Work.
18
+
19
+ 1. Internal Use
20
+
21
+ You may make production use of the Licensed Work for
22
+ your own internal business or organizational operations.
23
+
24
+ 2. Nonprofit Use
25
+
26
+ If you are a Nonprofit, you may make production use of
27
+ the Licensed Work for the operations and activities of
28
+ your Organizational Family.
29
+
30
+ 3. MemberJunction Certified Program Use
31
+
32
+ If you are authorized by Licensor under the
33
+ MemberJunction Certified Program to provide professional
34
+ services using the Licensed Work, you may make
35
+ production use of the Licensed Work in providing such
36
+ professional services to a client, provided that:
37
+
38
+ (a) the Licensed Work is deployed in, and the applicable
39
+ production use occurs within, an environment owned,
40
+ leased, licensed, subscribed to, or otherwise controlled
41
+ by that client; and
42
+
43
+ (b) the production use is for that client's own internal
44
+ business or organizational operations or is otherwise
45
+ independently permitted to that client under this
46
+ Additional Use Grant.
47
+
48
+ 4. Definitions Applicable to the Additional Use Grant
49
+
50
+ "Affiliate" means, with respect to a specified Person,
51
+ any other Person that directly or indirectly Controls,
52
+ is Controlled by, or is under common Control with such
53
+ specified Person.
54
+
55
+ "Control" (including the terms "Controls," "Controlled
56
+ by," and "under common Control with") means the direct
57
+ or indirect possession of the power to direct or cause
58
+ the direction of the management and policies of a
59
+ Person, whether through ownership of voting interests,
60
+ by contract, or otherwise.
61
+
62
+ "Organizational Family" means, with respect to a Person,
63
+ (a) such Person and its Affiliates, and (b) any
64
+ nonprofit organization, governmental entity, chapter,
65
+ division, local affiliate, regional affiliate, state
66
+ affiliate, national affiliate, or other entity that is
67
+ formally affiliated with such Person through governing
68
+ documents, a charter, bylaws, a membership agreement, or
69
+ another written organizational instrument, and is
70
+ recognized under such documents as part of the same
71
+ organizational structure.
72
+
73
+ "Nonprofit" means a Person recognized by the Internal
74
+ Revenue Service as exempt from federal income taxation
75
+ under Section 501(c)(3), 501(c)(4), 501(c)(5), or
76
+ 501(c)(6) of the Internal Revenue Code, or a foreign
77
+ organization recognized under substantially equivalent
78
+ laws.
79
+
80
+ A Person claiming eligibility as a Nonprofit shall, upon
81
+ Licensor's reasonable request, provide documentation
82
+ reasonably sufficient to demonstrate that it qualifies
83
+ as a Nonprofit. If such Person materially misrepresents,
84
+ or is unable to demonstrate, its qualification as a
85
+ Nonprofit, the rights granted to such Person under
86
+ Section 2 of this Additional Use Grant shall terminate.
87
+
88
+ "MemberJunction Certified Program" means Licensor's
89
+ then-current program for certifying and authorizing a
90
+ Person to provide professional services using the
91
+ Licensed Work.
92
+
93
+ "Person" means any individual, corporation, limited
94
+ liability company, partnership, association, nonprofit
95
+ organization, governmental entity, or other legal or
96
+ organizational entity.
97
+
98
+ Change Date: Four (4) years from the date the Licensed Work is first
99
+ made available.
100
+
101
+ Change License: MIT License.
102
+
103
+ For information about alternative licensing arrangements for the Licensed
104
+ Work, please contact Blue Cypress, Inc.
105
+
106
+ -----------------------------------------------------------------------------
107
+
108
+ Terms
109
+
110
+ The Licensor hereby grants you the right to copy, modify, create derivative
111
+ works, redistribute, and make non-production use of the Licensed Work. The
112
+ Licensor may make an Additional Use Grant, above, permitting limited
113
+ production use.
114
+
115
+ Effective on the Change Date, or the fourth anniversary of the first publicly
116
+ available distribution of a specific version of the Licensed Work under this
117
+ License, whichever comes first, the Licensor hereby grants you rights under
118
+ the terms of the Change License, and the rights granted in the paragraph
119
+ above terminate.
120
+
121
+ If your use of the Licensed Work does not comply with the requirements
122
+ currently in effect as described in this License, you must purchase a
123
+ commercial license from the Licensor, its affiliated entities, or authorized
124
+ resellers, or you must refrain from using the Licensed Work.
125
+
126
+ All copies of the original and modified Licensed Work, and derivative works
127
+ of the Licensed Work, are subject to this License. This License applies
128
+ separately for each version of the Licensed Work and the Change Date may vary
129
+ for each version of the Licensed Work released by Licensor.
130
+
131
+ You must conspicuously display this License on each original or modified copy
132
+ of the Licensed Work. If you receive the Licensed Work in original or
133
+ modified form from a third party, the terms and conditions set forth in this
134
+ License apply to your use of that work.
135
+
136
+ Any use of the Licensed Work in violation of this License will automatically
137
+ terminate your rights under this License for the current and all other
138
+ versions of the Licensed Work.
139
+
140
+ This License does not grant you any right in any trademark or logo of
141
+ Licensor or its affiliates (provided that you may use a trademark or logo of
142
+ Licensor as expressly required by this License).
143
+
144
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
145
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
146
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
147
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
148
+ TITLE.
149
+
150
+ MariaDB hereby grants you permission to use this License's text to license
151
+ your works, and to refer to it using the trademark "Business Source License",
152
+ as long as you comply with the Covenants of Licensor below.
153
+
154
+ -----------------------------------------------------------------------------
155
+
156
+ Covenants of Licensor
157
+
158
+ In consideration of the right to use this License's text and the "Business
159
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
160
+ other recipients of the licensed work to be provided by Licensor:
161
+
162
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
163
+ or a license that is compatible with GPL Version 2.0 or a later version,
164
+ where "compatible" means that software provided under the Change License
165
+ can be included in a program with software provided under GPL Version 2.0
166
+ or a later version. Licensor may specify additional Change Licenses without
167
+ limitation.
168
+
169
+ 2. To either: (a) specify an additional grant of rights to use that does not
170
+ impose any additional restriction on the right granted in this License, as
171
+ the Additional Use Grant; or (b) insert the text "None".
172
+
173
+ 3. To specify a Change Date.
174
+
175
+ 4. Not to modify this License in any other way.
176
+
177
+ -----------------------------------------------------------------------------
178
+
179
+ Notice
180
+
181
+ The Business Source License (this document, or the "License") is not an Open
182
+ Source license. However, the Licensed Work will eventually be made available
183
+ under an Open Source License, as stated in this License.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * @fileoverview `ContractEntity` — the SHARED subclass. Browser and server both load it, so every
3
+ * rule here runs in both places: the user sees a refusal before the round trip, and the server
4
+ * enforces the same rule regardless of what the client did.
5
+ *
6
+ * IT DOES NOT OVERRIDE `Save()`. A shared class that persisted would have to work on a provider
7
+ * that cannot open a transaction. Persistence stays with `ContractEntityServer`; the browser ships
8
+ * the whole graph in one `MJ.SaveEntityGraph` call and the server runs the same executor
9
+ * (plan §6.3). Same split as orders' `OrderHeaderEntity`.
10
+ *
11
+ * WHAT IS DELIBERATELY NOT HERE:
12
+ * · No `NewRecord()` status default. An earlier draft seeded `Status = 'Draft'`; D-19 removed the
13
+ * column. A new contract reads as `Draft` because the layered base view derives it from the
14
+ * absence of dates (ERD §4.5) — there is nothing to set, and nothing that can drift.
15
+ * · No `DeclareRelatedRecords`. CodeGen emits `Modifications` onto the generated base class from
16
+ * the `RelatedRecordCollection` metadata — edit that row, not this file.
17
+ * · No provision/template consistency check. It needs a cross-entity read, so it is server-side
18
+ * only (`ContractTemplateModificationEntityServer`); the picker prevents it in the UI.
19
+ *
20
+ * @module @mj-biz-apps/contracts-entities
21
+ */
22
+ import { ValidationResult } from '@memberjunction/core';
23
+ import { mjBizAppsContractsContractEntity } from './generated/entity_subclasses.js';
24
+ /**
25
+ * Do two contracts sit at the SAME LEVEL of the tree — i.e. may one supersede the other?
26
+ *
27
+ * The pure half of the same-level supersession rule (ruled by Marcelo, 2026-08-20). A free function
28
+ * taking plain values for the same reason `FindDuplicateProvisionIDs` is one: the decision has three
29
+ * cases and two of them are easy to get backwards, and none of them needs a database to check.
30
+ *
31
+ * · **both NULL → same level.** Two top-level agreements. This is the common case and the one a
32
+ * naive `a === b` on nullable values gets right by accident and a SQL `=` gets WRONG — hence the
33
+ * caller's `IS NULL` branch when it builds a filter.
34
+ * · **one NULL, one set → DIFFERENT levels.** A change order claiming to replace a whole order form.
35
+ * This is the case the rule exists to refuse.
36
+ * · **both set → compare case-insensitively.** MJ returns UUIDs in either casing depending on how
37
+ * the row was loaded, so a case-sensitive compare would call two siblings different levels and
38
+ * refuse a legitimate re-papering.
39
+ *
40
+ * Note this is deliberately NOT "root only": two siblings under one parent are the same level, which
41
+ * is what lets a change order supersede another change order under the same agreement.
42
+ */
43
+ export declare function IsSameContractLevel(myParentID: string | null | undefined, theirParentID: string | null | undefined): boolean;
44
+ /**
45
+ * Which provision IDs appear more than once — the pure half of R-10's staged-rows rule.
46
+ *
47
+ * A free function taking plain values so the counting is testable without a provider or a
48
+ * `RelatedRecordCollection`, the same reason `ValidateValueLists` and `IsNewlySelected` are free
49
+ * functions. Every subtlety worth getting right is in here rather than in the caller:
50
+ *
51
+ * · **case-insensitive** — MJ returns UUIDs in either casing depending on how the row was loaded, so
52
+ * a case-sensitive compare would miss a duplicate while appearing to check for one;
53
+ * · **blanks are skipped**, not grouped — several rows with no provision chosen yet are an
54
+ * incomplete edit, not "the same provision twice", and reporting them as duplicates would refuse a
55
+ * save the user is still composing;
56
+ * · **each duplicated ID is reported once**, however many times it appears, so three copies of one
57
+ * provision is one problem rather than two.
58
+ */
59
+ export declare function FindDuplicateProvisionIDs(provisionIDs: readonly unknown[]): string[];
60
+ export declare class ContractEntity extends mjBizAppsContractsContractEntity {
61
+ /**
62
+ * `HasModifications` is MONOTONIC: it must be true when modification rows exist, and it is never
63
+ * cleared automatically.
64
+ *
65
+ * WHY THE FLAG EXISTS AT ALL, given that the rows are right there to count. Because its job is to
66
+ * say "go read the PDF" *before* anyone has recorded the modifications. A derived flag would read
67
+ * false for every contract nobody has processed yet — which is exactly the population finance
68
+ * needs to be warned about. So a person asserts it, and this rule enforces the one direction that
69
+ * cannot be wrong: rows imply the flag.
70
+ *
71
+ * The other direction is deliberately unenforced. Clearing the flag after deleting every
72
+ * modification would be defensible, but it would also let a bulk delete quietly erase the warning
73
+ * on a contract whose paper really was negotiated. A human sets it false, or it stays true.
74
+ */
75
+ Validate(): ValidationResult;
76
+ /**
77
+ * R-10 — two modifications of the SAME provision, caught among the rows in hand.
78
+ *
79
+ * `UQ_ContractTemplateModification_Contract_Provision` is the floor, and it refuses this as a raw
80
+ * unique-index violation naming no field. This catches the case the browser can see for free: the
81
+ * collection is staged right here during a graph save, so a duplicate among those rows needs **no
82
+ * query at all**. The saved-rows half (a staged row colliding with one already in the table) needs
83
+ * a read and lives on the server subclass.
84
+ *
85
+ * WHY THIS IS ON `ContractEntity` AND NOT ON THE MODIFICATION. The item says "rule on the shared
86
+ * subclass" without saying which; only the CONTRACT holds the sibling rows. A modification cannot
87
+ * see its siblings, so the same rule written there could only ever be the one-query server version.
88
+ *
89
+ * Case-insensitive on the FK because MJ returns UUIDs in either casing, and a case-sensitive
90
+ * comparison would miss a duplicate while appearing to check for one.
91
+ */
92
+ private refuseDuplicateStagedModifications;
93
+ /**
94
+ * Drop generated NOT-NULL errors for fields the SAVE ITSELF fills in.
95
+ *
96
+ * `ContractNumber` is NOT NULL in metadata and is minted by `ContractEntityServer.Save()` from the
97
+ * sequence counter, under a lock. So on a record that has not been saved yet it is legitimately
98
+ * empty — and the generated check reported "Contract Number cannot be null", which the form
99
+ * surfaced as a refusal.
100
+ *
101
+ * That made the create path IMPOSSIBLE: every attempt to save a new contract through the UI was
102
+ * rejected for a field the user cannot fill and the server was about to. Measured in a browser, not
103
+ * reasoned about — the form refused with four errors and only three of them were real.
104
+ *
105
+ * After the first save the value exists, so an empty `ContractNumber` on a SAVED record is a
106
+ * genuine failure and is kept. That asymmetry is the whole rule, and it is why this cannot simply
107
+ * be "ignore ContractNumber".
108
+ *
109
+ * Same shape as orders' `IsSavePopulatedFieldError`, narrowed: contracts has exactly one
110
+ * save-populated field, because nothing here prepares child rows the way orders stamps line
111
+ * numbers and prices.
112
+ */
113
+ /**
114
+ * A hand-typed contract number may not look like a system-assigned one.
115
+ *
116
+ * WHY THIS REPLACED AN ERROR FILTER. This method sits where
117
+ * `dropSavePopulatedFieldErrors` used to: that one searched the validation result for
118
+ * `Source === 'ContractNumber'` and deleted it, so a new contract could be saved despite MJ
119
+ * correctly reporting a NOT NULL field as null. Deleting a real error because we believe
120
+ * something later will fix it is the same defect as blessing a self-reference because a
121
+ * generated validator "has it" — it converts an invalid state into a silent success the moment
122
+ * the belief stops holding. The cause is now removed instead: `V202608211000` gives the column a
123
+ * DEFAULT, which is how MJ models "NOT NULL but supplied on insert", so the error is never raised.
124
+ *
125
+ * WHAT THIS RULE IS. `Save()` honours a number the user typed, which is the right behaviour —
126
+ * migrated paper has its own references. But `CTR-<digits>` is the shape the sequence mints, so a
127
+ * hand-typed one can collide with a value the sequence has not reached yet. The collision would
128
+ * surface months later, on somebody else's save, as a unique-index violation with no explanation.
129
+ * So the namespaces are kept apart: type your own reference, or leave it blank.
130
+ *
131
+ * Note `\d+`, not `\d{6}`: `FORMAT(n,'D6')` pads to a MINIMUM of six digits and keeps growing
132
+ * past a million, so a seven-digit hand-typed number is just as collidable.
133
+ *
134
+ * ONLY ON AN UNSAVED RECORD, and only when the system did not assign it. An existing contract's
135
+ * stored number obviously matches the pattern and must not be retro-refused; and
136
+ * `ContractEntityServer.Save()` mints INTO this field before calling `super.Save()`, which
137
+ * validates — so without `NumberWasSystemAssigned` this rule would refuse the very numbers it is
138
+ * meant to protect.
139
+ */
140
+ private refuseReservedContractNumber;
141
+ /**
142
+ * Set by the server subclass when IT minted the number, so `refuseReservedContractNumber` can tell
143
+ * a system-assigned `CTR-…` from a hand-typed one. Protected rather than public: nothing outside
144
+ * the entity has any business claiming a number was system-assigned.
145
+ */
146
+ protected NumberWasSystemAssigned: boolean;
147
+ /**
148
+ * Whether modification rows are KNOWN to exist — as opposed to merely not known to be absent.
149
+ *
150
+ * The distinction is the whole subtlety of validating a collection in the browser. `Count > 0` is
151
+ * unambiguous: rows are staged or loaded, so they exist. `Count === 0` is ambiguous on a SAVED
152
+ * record whose collection was never loaded — empty there means *unknown*, and treating it as zero
153
+ * would let the flag be cleared on a contract whose modifications are sitting in the table.
154
+ *
155
+ * This method therefore only ever returns true on certainty. The unknown case is settled
156
+ * server-side, where a read is cheap and authoritative. Note `IsLoaded` alone is not the test:
157
+ * `Create()` does not mark a collection loaded, so a contract composed in the browser has
158
+ * modifications with `IsLoaded === false`. Orders' guard, same reasoning.
159
+ */
160
+ private modificationsKnownToExist;
161
+ /**
162
+ * Re-paper this contract: point it at the agreement that REPLACES it.
163
+ *
164
+ * ONE WRITE, NOT TWO. An earlier design also set `Status = 'Superseded'`; D-19 / R-18 removed the
165
+ * column precisely because the successor FK *is* the superseded state — the base view derives it
166
+ * (ERD §4.5), so there is no second fact that can disagree. The tautological
167
+ * `CK_Contract_SupersededHasSuccessor` constraint went with it.
168
+ *
169
+ * The successor is NOT saved here and neither is this record. The caller saves — normally as one
170
+ * graph — which keeps re-papering atomic: either both contracts reflect the supersession or
171
+ * neither does. Mirrors orders' `Confirm()`, which is likewise an intent-setter, not a persister.
172
+ */
173
+ Supersede(successor: ContractEntity): void;
174
+ }
175
+ /**
176
+ * Anti-tree-shake anchor. Importing this module is what fires `@RegisterClass`; a production build
177
+ * can drop an import whose class is never referenced, and a dropped registration means every rule
178
+ * above silently stops existing.
179
+ */
180
+ export declare function LoadContractEntity(): void;
181
+ //# sourceMappingURL=ContractEntity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContractEntity.d.ts","sourceRoot":"","sources":["../src/ContractEntity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAwD,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE9G,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEjF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,aAAa,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAM5H;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,yBAAyB,CAAC,YAAY,EAAE,SAAS,OAAO,EAAE,GAAG,MAAM,EAAE,CAWpF;AAED,qBACa,cAAe,SAAQ,gCAAgC;IAChE;;;;;;;;;;;;;OAaG;IACa,QAAQ,IAAI,gBAAgB;IAuB5C;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,kCAAkC;IAkB1C;;;;;;;;;;;;;;;;;;;OAmBG;IACH;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,OAAO,CAAC,4BAA4B;IAmBpC;;;;OAIG;IACH,SAAS,CAAC,uBAAuB,UAAS;IAE1C;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,yBAAyB;IAIjC;;;;;;;;;;;OAWG;IACI,SAAS,CAAC,SAAS,EAAE,cAAc,GAAG,IAAI;CAgBpD;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC"}
@@ -0,0 +1,261 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ /**
8
+ * @fileoverview `ContractEntity` — the SHARED subclass. Browser and server both load it, so every
9
+ * rule here runs in both places: the user sees a refusal before the round trip, and the server
10
+ * enforces the same rule regardless of what the client did.
11
+ *
12
+ * IT DOES NOT OVERRIDE `Save()`. A shared class that persisted would have to work on a provider
13
+ * that cannot open a transaction. Persistence stays with `ContractEntityServer`; the browser ships
14
+ * the whole graph in one `MJ.SaveEntityGraph` call and the server runs the same executor
15
+ * (plan §6.3). Same split as orders' `OrderHeaderEntity`.
16
+ *
17
+ * WHAT IS DELIBERATELY NOT HERE:
18
+ * · No `NewRecord()` status default. An earlier draft seeded `Status = 'Draft'`; D-19 removed the
19
+ * column. A new contract reads as `Draft` because the layered base view derives it from the
20
+ * absence of dates (ERD §4.5) — there is nothing to set, and nothing that can drift.
21
+ * · No `DeclareRelatedRecords`. CodeGen emits `Modifications` onto the generated base class from
22
+ * the `RelatedRecordCollection` metadata — edit that row, not this file.
23
+ * · No provision/template consistency check. It needs a cross-entity read, so it is server-side
24
+ * only (`ContractTemplateModificationEntityServer`); the picker prevents it in the UI.
25
+ *
26
+ * @module @mj-biz-apps/contracts-entities
27
+ */
28
+ import { BaseEntity, ValidationErrorInfo, ValidationErrorType } from '@memberjunction/core';
29
+ import { RegisterClass } from '@memberjunction/global';
30
+ import { mjBizAppsContractsContractEntity } from './generated/entity_subclasses.js';
31
+ /**
32
+ * Do two contracts sit at the SAME LEVEL of the tree — i.e. may one supersede the other?
33
+ *
34
+ * The pure half of the same-level supersession rule (ruled by Marcelo, 2026-08-20). A free function
35
+ * taking plain values for the same reason `FindDuplicateProvisionIDs` is one: the decision has three
36
+ * cases and two of them are easy to get backwards, and none of them needs a database to check.
37
+ *
38
+ * · **both NULL → same level.** Two top-level agreements. This is the common case and the one a
39
+ * naive `a === b` on nullable values gets right by accident and a SQL `=` gets WRONG — hence the
40
+ * caller's `IS NULL` branch when it builds a filter.
41
+ * · **one NULL, one set → DIFFERENT levels.** A change order claiming to replace a whole order form.
42
+ * This is the case the rule exists to refuse.
43
+ * · **both set → compare case-insensitively.** MJ returns UUIDs in either casing depending on how
44
+ * the row was loaded, so a case-sensitive compare would call two siblings different levels and
45
+ * refuse a legitimate re-papering.
46
+ *
47
+ * Note this is deliberately NOT "root only": two siblings under one parent are the same level, which
48
+ * is what lets a change order supersede another change order under the same agreement.
49
+ */
50
+ export function IsSameContractLevel(myParentID, theirParentID) {
51
+ const a = myParentID ?? null;
52
+ const b = theirParentID ?? null;
53
+ if (a === null && b === null)
54
+ return true;
55
+ if (a === null || b === null)
56
+ return false;
57
+ return a.toLowerCase() === b.toLowerCase();
58
+ }
59
+ /**
60
+ * Which provision IDs appear more than once — the pure half of R-10's staged-rows rule.
61
+ *
62
+ * A free function taking plain values so the counting is testable without a provider or a
63
+ * `RelatedRecordCollection`, the same reason `ValidateValueLists` and `IsNewlySelected` are free
64
+ * functions. Every subtlety worth getting right is in here rather than in the caller:
65
+ *
66
+ * · **case-insensitive** — MJ returns UUIDs in either casing depending on how the row was loaded, so
67
+ * a case-sensitive compare would miss a duplicate while appearing to check for one;
68
+ * · **blanks are skipped**, not grouped — several rows with no provision chosen yet are an
69
+ * incomplete edit, not "the same provision twice", and reporting them as duplicates would refuse a
70
+ * save the user is still composing;
71
+ * · **each duplicated ID is reported once**, however many times it appears, so three copies of one
72
+ * provision is one problem rather than two.
73
+ */
74
+ export function FindDuplicateProvisionIDs(provisionIDs) {
75
+ const counts = new Map();
76
+ const duplicates = [];
77
+ for (const raw of provisionIDs) {
78
+ const id = String(raw ?? '').trim().toLowerCase();
79
+ if (!id)
80
+ continue;
81
+ const next = (counts.get(id) ?? 0) + 1;
82
+ counts.set(id, next);
83
+ if (next === 2)
84
+ duplicates.push(id);
85
+ }
86
+ return duplicates;
87
+ }
88
+ let ContractEntity = class ContractEntity extends mjBizAppsContractsContractEntity {
89
+ constructor() {
90
+ super(...arguments);
91
+ /**
92
+ * Set by the server subclass when IT minted the number, so `refuseReservedContractNumber` can tell
93
+ * a system-assigned `CTR-…` from a hand-typed one. Protected rather than public: nothing outside
94
+ * the entity has any business claiming a number was system-assigned.
95
+ */
96
+ this.NumberWasSystemAssigned = false;
97
+ }
98
+ /**
99
+ * `HasModifications` is MONOTONIC: it must be true when modification rows exist, and it is never
100
+ * cleared automatically.
101
+ *
102
+ * WHY THE FLAG EXISTS AT ALL, given that the rows are right there to count. Because its job is to
103
+ * say "go read the PDF" *before* anyone has recorded the modifications. A derived flag would read
104
+ * false for every contract nobody has processed yet — which is exactly the population finance
105
+ * needs to be warned about. So a person asserts it, and this rule enforces the one direction that
106
+ * cannot be wrong: rows imply the flag.
107
+ *
108
+ * The other direction is deliberately unenforced. Clearing the flag after deleting every
109
+ * modification would be defensible, but it would also let a bulk delete quietly erase the warning
110
+ * on a contract whose paper really was negotiated. A human sets it false, or it stays true.
111
+ */
112
+ Validate() {
113
+ const result = super.Validate();
114
+ this.refuseReservedContractNumber(result);
115
+ if (this.HasModifications === false && this.modificationsKnownToExist()) {
116
+ result.Success = false;
117
+ result.Errors.push(new ValidationErrorInfo('HasModifications', `Contract ${this.ContractNumber ?? ''} records ${this.Modifications.Count} modification(s) to the ` +
118
+ `standard agreement, so it cannot be marked as unmodified. Remove the modifications first if ` +
119
+ `the agreement really is standard.`, this.HasModifications, ValidationErrorType.Failure));
120
+ }
121
+ this.refuseDuplicateStagedModifications(result);
122
+ return result;
123
+ }
124
+ /**
125
+ * R-10 — two modifications of the SAME provision, caught among the rows in hand.
126
+ *
127
+ * `UQ_ContractTemplateModification_Contract_Provision` is the floor, and it refuses this as a raw
128
+ * unique-index violation naming no field. This catches the case the browser can see for free: the
129
+ * collection is staged right here during a graph save, so a duplicate among those rows needs **no
130
+ * query at all**. The saved-rows half (a staged row colliding with one already in the table) needs
131
+ * a read and lives on the server subclass.
132
+ *
133
+ * WHY THIS IS ON `ContractEntity` AND NOT ON THE MODIFICATION. The item says "rule on the shared
134
+ * subclass" without saying which; only the CONTRACT holds the sibling rows. A modification cannot
135
+ * see its siblings, so the same rule written there could only ever be the one-query server version.
136
+ *
137
+ * Case-insensitive on the FK because MJ returns UUIDs in either casing, and a case-sensitive
138
+ * comparison would miss a duplicate while appearing to check for one.
139
+ */
140
+ refuseDuplicateStagedModifications(result) {
141
+ const provisionIDs = this.Modifications.Items.map((mod) => mod.Get('ContractTemplateProvisionID'));
142
+ const duplicates = FindDuplicateProvisionIDs(provisionIDs);
143
+ if (duplicates.length === 0)
144
+ return;
145
+ result.Success = false;
146
+ result.Errors.push(new ValidationErrorInfo('Modifications', `${duplicates.length === 1 ? 'A provision is' : `${duplicates.length} provisions are`} modified more ` +
147
+ `than once on this contract. A contract records ONE negotiated wording per standard clause — ` +
148
+ `combine the duplicates into a single modification.`, duplicates.length, ValidationErrorType.Failure));
149
+ }
150
+ /**
151
+ * Drop generated NOT-NULL errors for fields the SAVE ITSELF fills in.
152
+ *
153
+ * `ContractNumber` is NOT NULL in metadata and is minted by `ContractEntityServer.Save()` from the
154
+ * sequence counter, under a lock. So on a record that has not been saved yet it is legitimately
155
+ * empty — and the generated check reported "Contract Number cannot be null", which the form
156
+ * surfaced as a refusal.
157
+ *
158
+ * That made the create path IMPOSSIBLE: every attempt to save a new contract through the UI was
159
+ * rejected for a field the user cannot fill and the server was about to. Measured in a browser, not
160
+ * reasoned about — the form refused with four errors and only three of them were real.
161
+ *
162
+ * After the first save the value exists, so an empty `ContractNumber` on a SAVED record is a
163
+ * genuine failure and is kept. That asymmetry is the whole rule, and it is why this cannot simply
164
+ * be "ignore ContractNumber".
165
+ *
166
+ * Same shape as orders' `IsSavePopulatedFieldError`, narrowed: contracts has exactly one
167
+ * save-populated field, because nothing here prepares child rows the way orders stamps line
168
+ * numbers and prices.
169
+ */
170
+ /**
171
+ * A hand-typed contract number may not look like a system-assigned one.
172
+ *
173
+ * WHY THIS REPLACED AN ERROR FILTER. This method sits where
174
+ * `dropSavePopulatedFieldErrors` used to: that one searched the validation result for
175
+ * `Source === 'ContractNumber'` and deleted it, so a new contract could be saved despite MJ
176
+ * correctly reporting a NOT NULL field as null. Deleting a real error because we believe
177
+ * something later will fix it is the same defect as blessing a self-reference because a
178
+ * generated validator "has it" — it converts an invalid state into a silent success the moment
179
+ * the belief stops holding. The cause is now removed instead: `V202608211000` gives the column a
180
+ * DEFAULT, which is how MJ models "NOT NULL but supplied on insert", so the error is never raised.
181
+ *
182
+ * WHAT THIS RULE IS. `Save()` honours a number the user typed, which is the right behaviour —
183
+ * migrated paper has its own references. But `CTR-<digits>` is the shape the sequence mints, so a
184
+ * hand-typed one can collide with a value the sequence has not reached yet. The collision would
185
+ * surface months later, on somebody else's save, as a unique-index violation with no explanation.
186
+ * So the namespaces are kept apart: type your own reference, or leave it blank.
187
+ *
188
+ * Note `\d+`, not `\d{6}`: `FORMAT(n,'D6')` pads to a MINIMUM of six digits and keeps growing
189
+ * past a million, so a seven-digit hand-typed number is just as collidable.
190
+ *
191
+ * ONLY ON AN UNSAVED RECORD, and only when the system did not assign it. An existing contract's
192
+ * stored number obviously matches the pattern and must not be retro-refused; and
193
+ * `ContractEntityServer.Save()` mints INTO this field before calling `super.Save()`, which
194
+ * validates — so without `NumberWasSystemAssigned` this rule would refuse the very numbers it is
195
+ * meant to protect.
196
+ */
197
+ refuseReservedContractNumber(result) {
198
+ if (this.IsSaved || this.NumberWasSystemAssigned)
199
+ return;
200
+ const typed = (this.ContractNumber ?? '').trim();
201
+ if (!typed || !/^CTR-\d+$/i.test(typed))
202
+ return;
203
+ result.Success = false;
204
+ result.Errors.push(new ValidationErrorInfo('ContractNumber', `The CTR-#### pattern is reserved for contract numbers the system assigns, so "${typed}" cannot be ` +
205
+ `entered by hand — a number the sequence has not reached yet would collide with it later, on ` +
206
+ `somebody else's save. Leave this blank to have one assigned, or enter your own reference in a ` +
207
+ `different format.`, this.ContractNumber, ValidationErrorType.Failure));
208
+ }
209
+ /**
210
+ * Whether modification rows are KNOWN to exist — as opposed to merely not known to be absent.
211
+ *
212
+ * The distinction is the whole subtlety of validating a collection in the browser. `Count > 0` is
213
+ * unambiguous: rows are staged or loaded, so they exist. `Count === 0` is ambiguous on a SAVED
214
+ * record whose collection was never loaded — empty there means *unknown*, and treating it as zero
215
+ * would let the flag be cleared on a contract whose modifications are sitting in the table.
216
+ *
217
+ * This method therefore only ever returns true on certainty. The unknown case is settled
218
+ * server-side, where a read is cheap and authoritative. Note `IsLoaded` alone is not the test:
219
+ * `Create()` does not mark a collection loaded, so a contract composed in the browser has
220
+ * modifications with `IsLoaded === false`. Orders' guard, same reasoning.
221
+ */
222
+ modificationsKnownToExist() {
223
+ return this.Modifications.Count > 0;
224
+ }
225
+ /**
226
+ * Re-paper this contract: point it at the agreement that REPLACES it.
227
+ *
228
+ * ONE WRITE, NOT TWO. An earlier design also set `Status = 'Superseded'`; D-19 / R-18 removed the
229
+ * column precisely because the successor FK *is* the superseded state — the base view derives it
230
+ * (ERD §4.5), so there is no second fact that can disagree. The tautological
231
+ * `CK_Contract_SupersededHasSuccessor` constraint went with it.
232
+ *
233
+ * The successor is NOT saved here and neither is this record. The caller saves — normally as one
234
+ * graph — which keeps re-papering atomic: either both contracts reflect the supersession or
235
+ * neither does. Mirrors orders' `Confirm()`, which is likewise an intent-setter, not a persister.
236
+ */
237
+ Supersede(successor) {
238
+ if (!successor?.ID) {
239
+ throw new Error(`Cannot supersede contract ${this.ContractNumber ?? this.ID}: the replacement contract must be ` +
240
+ `saved first, so that its ID exists to point at.`);
241
+ }
242
+ if (successor.ID === this.ID) {
243
+ throw new Error(`Contract ${this.ContractNumber ?? this.ID} cannot supersede itself. ` +
244
+ `(CK_Contract_SupersededNotSelf would refuse the save regardless.)`);
245
+ }
246
+ this.SupersededByContractID = successor.ID;
247
+ }
248
+ };
249
+ ContractEntity = __decorate([
250
+ RegisterClass(BaseEntity, 'MJ_BizApps_Contracts: Contracts')
251
+ ], ContractEntity);
252
+ export { ContractEntity };
253
+ /**
254
+ * Anti-tree-shake anchor. Importing this module is what fires `@RegisterClass`; a production build
255
+ * can drop an import whose class is never referenced, and a dropped registration means every rule
256
+ * above silently stops existing.
257
+ */
258
+ export function LoadContractEntity() {
259
+ void ContractEntity;
260
+ }
261
+ //# sourceMappingURL=ContractEntity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ContractEntity.js","sourceRoot":"","sources":["../src/ContractEntity.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,mBAAmB,EAAoB,MAAM,sBAAsB,CAAC;AAC9G,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAEjF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,mBAAmB,CAAC,UAAqC,EAAE,aAAwC;IAC/G,MAAM,CAAC,GAAG,UAAU,IAAI,IAAI,CAAC;IAC7B,MAAM,CAAC,GAAG,aAAa,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC3C,OAAO,CAAC,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AAC/C,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,yBAAyB,CAAC,YAAgC;IACtE,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,KAAK,MAAM,GAAG,IAAI,YAAY,EAAE,CAAC;QAC7B,MAA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