@wirecat/cli-core 0.606.0 → 0.607.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 (209) hide show
  1. package/CHANGELOG.md +186 -1
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.js +3 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +61 -2
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -0,0 +1,92 @@
1
+ import { isRecordType, roleOf } from "../../domain/record-types.js";
2
+ import { requiredThing } from "./notes.js";
3
+ import { refusal } from "./record-projection.js";
4
+ import { referenceOfThing, storedThing } from "./things.js";
5
+ /** A reference a record's fields make (`fields.pipeline`, `fields.lines.product`): no role a source sends has a dot. */
6
+ export const isDerived = (role) => role.startsWith("fields.");
7
+ /** A record's relations in `record_relations`: as sent, a typed ref with the target type ref, and those its fields make. */
8
+ export const recordRelationsOver = ({ database }) => {
9
+ const sql = (text) => database.prepare(text);
10
+ const entityRef = (type, id) => type == null ? null : (referenceOfThing(database, storedThing(type, id)) ?? `${String(type)}:${String(id)}`);
11
+ const refOfThing = (ref) => {
12
+ const thing = requiredThing(database, ref);
13
+ return entityRef(thing.type, thing.id);
14
+ };
15
+ /** A pipeline CRM sync wrote for this account has no record, yet a deal of the account stands in it. */
16
+ const syncedPipeline = (recordId, row) => row.target_type === "pipeline" &&
17
+ sql("SELECT 1 FROM pipelines p JOIN records r ON r.account_id = p.account_id WHERE r.id = ? AND p.external_id = ? " +
18
+ "AND p.deleted_at IS NULL").get(recordId, String(row.target_external_id)) !== undefined;
19
+ /** What a projection needs from a record's relations: entities by role, the roles still without one, the shares. */
20
+ const relatedOf = (recordId, type) => {
21
+ const rows = sql("SELECT rr.role, rr.amount, rr.as_role, rr.target_type, rr.target_external_id, t.entity_type, t.entity_id " +
22
+ "FROM record_relations rr LEFT JOIN records t ON t.id = rr.target_id AND t.deleted_at IS NULL " +
23
+ "WHERE rr.record_id = ? ORDER BY rr.id").all(recordId);
24
+ const related = new Map();
25
+ const as = new Map();
26
+ const products = new Map();
27
+ const shares = [];
28
+ const missing = new Set();
29
+ for (const row of rows) {
30
+ const role = String(row.role);
31
+ if (isDerived(role)) {
32
+ const ref = entityRef(row.entity_type, row.entity_id);
33
+ if (ref === null) {
34
+ if (!syncedPipeline(recordId, row))
35
+ missing.add(role);
36
+ }
37
+ else if (role.endsWith(".product"))
38
+ products.set(String(row.target_external_id), ref);
39
+ continue;
40
+ }
41
+ const spec = roleOf(type, role);
42
+ if (spec === undefined || spec.kept)
43
+ continue;
44
+ const ref = row.target_type === "ref"
45
+ ? refOfThing(String(row.target_external_id))
46
+ : entityRef(row.entity_type, row.entity_id);
47
+ if (ref === null) {
48
+ missing.add(role);
49
+ continue;
50
+ }
51
+ related.set(role, [...(related.get(role) ?? []), ref]);
52
+ as.set(role, [...(as.get(role) ?? []), row.as_role == null ? null : String(row.as_role)]);
53
+ if (spec.amount)
54
+ shares.push({ invoice: ref, amount: row.amount == null ? null : String(row.amount) });
55
+ }
56
+ for (const [role, refs] of related)
57
+ if (refs.length > 1 && !roleOf(type, role)?.many)
58
+ refusal(`a record has one ${role}`, "record.relation-ambiguous");
59
+ return { related, as, shares, products, missing: [...missing] };
60
+ };
61
+ /** The relations as sent, without the references taken from fields: what a fingerprint was made of. */
62
+ const storedRelations = (recordId) => sql("SELECT role, target_type, target_external_id, as_role, amount FROM record_relations WHERE record_id = ?")
63
+ .all(recordId)
64
+ .filter((row) => !isDerived(String(row.role)))
65
+ .map((row) => ({
66
+ role: String(row.role),
67
+ ...(row.target_type === "ref"
68
+ ? { ref: String(row.target_external_id) }
69
+ : { type: String(row.target_type), external_id: String(row.target_external_id) }),
70
+ ...(row.as_role == null ? {} : { as: String(row.as_role) }),
71
+ ...(row.amount == null ? {} : { amount: String(row.amount) }),
72
+ }));
73
+ const relate = (recordId, accountId, relations, at) => {
74
+ sql("DELETE FROM record_relations WHERE record_id = ?").run(recordId);
75
+ for (const relation of relations) {
76
+ const { ref, as, amount } = relation;
77
+ const type = ref === undefined ? String(relation.type) : "ref";
78
+ const external = ref ?? String(relation.external_id);
79
+ sql("INSERT OR IGNORE INTO record_relations (record_id, role, target_type, target_external_id, target_id, " +
80
+ "created_at, amount, as_role) VALUES (?, ?, ?, ?, (SELECT id FROM records WHERE account_id = ? AND type = ? " +
81
+ "AND external_id = ?), ?, ?, ?)").run(recordId, relation.role, type, external, accountId, type, external, at, amount ?? null, as ?? null);
82
+ }
83
+ };
84
+ const missingOf = (id) => {
85
+ const row = sql("SELECT type, entity_id, deleted_at FROM records WHERE id = ?").get(id);
86
+ if (!row || row.entity_id != null || row.deleted_at != null || !isRecordType(String(row.type)))
87
+ return null;
88
+ const { missing } = relatedOf(id, row.type);
89
+ return missing.length > 0 ? missing : null;
90
+ };
91
+ return { entityRef, relatedOf, storedRelations, relate, missingOf };
92
+ };
@@ -0,0 +1,12 @@
1
+ import type { StoreContext } from "./open.js";
2
+ import type { Row } from "./record-projection.js";
3
+ interface Thing {
4
+ type: string;
5
+ id: number;
6
+ }
7
+ /** The owner's remap of a record whose entity the import made: what this account's records filled from it follows. */
8
+ export declare const recordRemapOver: ({ database, now }: StoreContext) => {
9
+ pointedAt: (type: string, id: number) => boolean;
10
+ remap: (record: Row, from: Thing, to: Thing) => void;
11
+ };
12
+ export {};
@@ -0,0 +1,92 @@
1
+ import { isRecordType, RECORD_TYPES, roleOf } from "../../domain/record-types.js";
2
+ import { pointerPairs } from "./entity-types.js";
3
+ /** The owner's remap of a record whose entity the import made: what this account's records filled from it follows. */
4
+ export const recordRemapOver = ({ database, now }) => {
5
+ /** Whether any row points at the entity: a pointer pair, a foreign key or a record; its own identities do not count. */
6
+ const pointedAt = (type, id) => {
7
+ for (const { table, pointer } of pointerPairs(database))
8
+ if (database.prepare(`SELECT 1 FROM ${table} WHERE ${pointer}_type = ? AND ${pointer}_id = ? LIMIT 1`).get(type, id))
9
+ return true;
10
+ if (!isRecordType(type))
11
+ return false;
12
+ const target = RECORD_TYPES[type].table;
13
+ const OWN = new Set(["identity_links", "identity_link_events", "organization_identities"]);
14
+ for (const { name } of database
15
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
16
+ .all()) {
17
+ if (OWN.has(name))
18
+ continue;
19
+ for (const key of database
20
+ .prepare(`SELECT "from" AS column FROM pragma_foreign_key_list(?) WHERE "table" = ?`)
21
+ .all(name, target))
22
+ if (database.prepare(`SELECT 1 FROM "${name}" WHERE "${String(key.column)}" = ? LIMIT 1`).get(id))
23
+ return true;
24
+ }
25
+ return false;
26
+ };
27
+ /** Repoints the entity columns that `record`'s dependents in its account filled from it. */
28
+ const repointDependents = (record, from, to, at) => {
29
+ const dependents = database
30
+ .prepare("SELECT rr.role, r.type, r.entity_type, r.entity_id FROM record_relations rr JOIN records r ON r.id = rr.record_id " +
31
+ "WHERE rr.target_id = ? AND r.account_id = ? AND r.entity_id IS NOT NULL")
32
+ .all(Number(record.id), Number(record.account_id));
33
+ for (const row of dependents) {
34
+ const role = roleOf(String(row.type), String(row.role));
35
+ const type = String(row.entity_type);
36
+ if (role === undefined || !isRecordType(type))
37
+ continue;
38
+ const { table } = RECORD_TYPES[type];
39
+ const entityId = Number(row.entity_id);
40
+ if (role.column !== undefined && !role.pair)
41
+ database
42
+ .prepare(`UPDATE ${table} SET ${role.column} = ?, updated_at = ? WHERE id = ? AND ${role.column} = ?`)
43
+ .run(to.id, at, entityId, from.id);
44
+ else if (role.column !== undefined)
45
+ database
46
+ .prepare(`UPDATE ${table} SET ${role.column}_type = ?, ${role.column}_id = ?, updated_at = ? WHERE id = ? ` +
47
+ `AND ${role.column}_type = ? AND ${role.column}_id = ?`)
48
+ .run(to.type, to.id, at, entityId, from.type, from.id);
49
+ // An SMS's identity link moves with the person's identities below; a call's link to the person moves here.
50
+ if (role.linked && type === "event")
51
+ database
52
+ .prepare("UPDATE OR IGNORE links SET to_id = ?, updated_at = ? WHERE from_type = 'event' AND from_id = ? " +
53
+ "AND to_type = ? AND to_id = ? AND source = 'import'")
54
+ .run(to.id, at, entityId, from.type, from.id);
55
+ }
56
+ };
57
+ /**
58
+ * Moves `record` from the entity the import made to `to`, with every record of the account linked to that entity by
59
+ * the same identifiers, what their dependents filled from them, and the identities the import gave it.
60
+ */
61
+ const remap = (record, from, to) => {
62
+ const at = now();
63
+ const moved = database
64
+ .prepare("SELECT * FROM records WHERE account_id = ? AND entity_type = ? AND entity_id = ?")
65
+ .all(Number(record.account_id), from.type, from.id);
66
+ for (const row of moved) {
67
+ repointDependents(row, from, to, at);
68
+ database
69
+ .prepare("UPDATE records SET entity_type = ?, entity_id = ?, created_entity = 0, projected_fingerprint = fingerprint " +
70
+ "WHERE id = ?")
71
+ .run(to.type, to.id, Number(row.id));
72
+ }
73
+ if (from.type === "person")
74
+ for (const link of database
75
+ .prepare("SELECT identity_id FROM identity_links WHERE person_id = ? AND method = 'import'")
76
+ .all(from.id)) {
77
+ database
78
+ .prepare("UPDATE identity_links SET person_id = ?, updated_at = ? WHERE identity_id = ?")
79
+ .run(to.id, at, Number(link.identity_id));
80
+ database
81
+ .prepare("INSERT INTO identity_link_events (identity_id, from_person_id, to_person_id, method, created_at, author) " +
82
+ "VALUES (?, ?, ?, 'owner', ?, 'owner')")
83
+ .run(Number(link.identity_id), from.id, to.id, at);
84
+ }
85
+ if (from.type === "organization")
86
+ database
87
+ .prepare("UPDATE OR IGNORE organization_identities SET organization_id = ?, updated_at = ? " +
88
+ "WHERE organization_id = ? AND method = 'import'")
89
+ .run(to.id, at, from.id);
90
+ };
91
+ return { pointedAt, remap };
92
+ };
@@ -0,0 +1,71 @@
1
+ import type { EnvelopeOptions, EnvelopeRecord, EnvelopeSource, IngestError } from "../../domain/records.js";
2
+ import type { StoreContext } from "./open.js";
3
+ import type { Flag, recordWritesOver } from "./record-writes.js";
4
+ /** One line of a run: its place in the envelope or stream, the record, and why it was refused before the store. */
5
+ export interface RunItem {
6
+ index: number;
7
+ record: EnvelopeRecord;
8
+ errors?: IngestError[];
9
+ }
10
+ export interface RunOptions {
11
+ dryRun?: boolean;
12
+ /** Records per transaction, 1000 by default. */
13
+ chunk?: number;
14
+ options?: EnvelopeOptions;
15
+ /** How many entries each list keeps, 1000 by default; counts stay exact. */
16
+ limit?: number;
17
+ /**
18
+ * Every refusal as it happens, the ones past `limit` too. It must not use the store: it runs inside the run's
19
+ * transaction, and during a dry run its statements are refused (`store.dry-run`).
20
+ */
21
+ onIssue?: (error: IngestError) => void;
22
+ }
23
+ export interface Unmatched {
24
+ index: number;
25
+ key: string;
26
+ /** `record.ambiguous`, or `record.separated` when the owner told the one match apart from these identifiers. */
27
+ reason: string;
28
+ /** The entities its identifiers point at: the owner says which one it is with `records link`. */
29
+ candidates: string[];
30
+ }
31
+ export interface FlaggedRecord extends Flag {
32
+ index: number;
33
+ key: string;
34
+ entity: string;
35
+ }
36
+ export interface RecordsRun {
37
+ created: number;
38
+ updated: number;
39
+ unchanged: number;
40
+ deleted: number;
41
+ refused: number;
42
+ errors: IngestError[];
43
+ /** Proposals this run made or changed, also for records of earlier imports it completed. */
44
+ proposed: string[];
45
+ /** Kept, with no entity yet: the roles, or `fields.<key>`, whose target is not imported or has no entity. */
46
+ waiting: {
47
+ index: number;
48
+ key: string;
49
+ missing: string[];
50
+ }[];
51
+ /** A person, organization or project whose identifiers point at more than one entity. */
52
+ unmatched: Unmatched[];
53
+ /** Changed or deleted at the source after its entity was made. */
54
+ flagged: FlaggedRecord[];
55
+ /** Values that look like identifiers and were kept as data only: a phone without `+` and no `phone_region`. */
56
+ ignored: {
57
+ index: number;
58
+ key: string;
59
+ at: (string | number)[];
60
+ reason: string;
61
+ }[];
62
+ /** A list stopped at `limit`. */
63
+ truncated: boolean;
64
+ }
65
+ /**
66
+ * Takes a stream of records per chunk, each chunk in one transaction. Duplicate keys are checked, and the receipt's
67
+ * lists collected, in TEMP tables of this run, so memory holds one chunk whatever the stream's length.
68
+ */
69
+ export declare const recordRunOver: (context: StoreContext, writes: ReturnType<typeof recordWritesOver>) => (source: EnvelopeSource, items: AsyncIterable<RunItem> | Iterable<RunItem>, { chunk, options, limit, onIssue }: RunOptions) => Promise<RecordsRun>;
70
+ /** Where a waiting record's receipt entry points: its relations, or the field that names the missing record. */
71
+ export declare const waitingPointer: (index: number, missing: string[]) => string;
@@ -0,0 +1,179 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { pointerOf } from "../../domain/records.js";
3
+ import { accountPk } from "./accounts.js";
4
+ import { codeOf } from "./record-projection.js";
5
+ import { isDerived } from "./record-relations.js";
6
+ import { outsideRehearsal, read, write } from "./transaction.js";
7
+ let runs = 0;
8
+ const PAGE = 500;
9
+ /**
10
+ * Takes a stream of records per chunk, each chunk in one transaction. Duplicate keys are checked, and the receipt's
11
+ * lists collected, in TEMP tables of this run, so memory holds one chunk whatever the stream's length.
12
+ */
13
+ export const recordRunOver = (context, writes) => {
14
+ const { database } = context;
15
+ const { writeOne, completeDependents, entityRef, missingOf } = writes;
16
+ return async (source, items, { chunk = 1000, options = {}, limit = 1000, onIssue }) => {
17
+ runs += 1;
18
+ const table = `records_run_${runs}`;
19
+ const proposedTable = `records_run_${runs}_proposed`;
20
+ database.exec(`CREATE TEMP TABLE ${table} (idx INTEGER NOT NULL, key TEXT NOT NULL UNIQUE, identity TEXT NOT NULL UNIQUE, ` +
21
+ "record_id INTEGER, flagged TEXT, unmatched TEXT, ignored TEXT)");
22
+ database.exec(`CREATE TEMP TABLE ${proposedTable} (ref TEXT PRIMARY KEY)`);
23
+ try {
24
+ let truncated = false;
25
+ const errors = [];
26
+ const counts = { created: 0, updated: 0, unchanged: 0, deleted: 0, refused: 0 };
27
+ const issue = (error) => {
28
+ if (errors.length < limit)
29
+ errors.push(error);
30
+ else
31
+ truncated = true;
32
+ if (onIssue)
33
+ outsideRehearsal(() => onIssue(error));
34
+ };
35
+ const refused = (error) => {
36
+ counts.refused += 1;
37
+ issue(error);
38
+ };
39
+ const proposed = (ref) => {
40
+ database.prepare(`INSERT OR IGNORE INTO temp.${proposedTable} (ref) VALUES (?)`).run(ref);
41
+ };
42
+ const takeChunk = (batch) => write(database, () => {
43
+ const accountId = accountPk(context, { provider: source.provider, account: source.account });
44
+ const complete = [];
45
+ for (const { index, record, errors: before } of batch) {
46
+ if (before?.length) {
47
+ counts.refused += 1;
48
+ for (const error of before)
49
+ issue(error);
50
+ continue;
51
+ }
52
+ const identity = `${record.type}\0${record.external_id}`;
53
+ if (database.prepare(`SELECT 1 FROM temp.${table} WHERE key = ?`).get(record.key)) {
54
+ refused({
55
+ pointer: pointerOf("records", index, "key"),
56
+ code: "record.duplicate-key",
57
+ message: "another record of this envelope has this key",
58
+ key: record.key,
59
+ });
60
+ continue;
61
+ }
62
+ if (database.prepare(`SELECT 1 FROM temp.${table} WHERE identity = ?`).get(identity)) {
63
+ refused({
64
+ pointer: pointerOf("records", index, "external_id"),
65
+ code: "record.duplicate",
66
+ message: `another record of this envelope is ${record.type} ${record.external_id}`,
67
+ key: record.key,
68
+ });
69
+ continue;
70
+ }
71
+ database
72
+ .prepare(`INSERT INTO temp.${table} (idx, key, identity) VALUES (?, ?, ?)`)
73
+ .run(index, record.key, identity);
74
+ try {
75
+ const done = write(database, () => writeOne(accountId, source, record, options, proposed));
76
+ counts[done.status] += 1;
77
+ database
78
+ .prepare(`UPDATE temp.${table} SET record_id = ?, flagged = ?, unmatched = ?, ignored = ? WHERE key = ?`)
79
+ .run(done.id, done.flagged === undefined ? null : JSON.stringify(done.flagged), done.unmatched === undefined ? null : JSON.stringify(done.unmatched), done.ignored?.length ? JSON.stringify(done.ignored) : null, record.key);
80
+ if (done.complete)
81
+ complete.push(done.id);
82
+ }
83
+ catch (error) {
84
+ if (!(error instanceof CliError))
85
+ throw error;
86
+ const at = error.details?.at ?? "fields";
87
+ refused({
88
+ pointer: pointerOf("records", index, ...[at].flat()),
89
+ code: codeOf(error),
90
+ message: error.message,
91
+ key: record.key,
92
+ });
93
+ }
94
+ }
95
+ for (const id of complete)
96
+ completeDependents(id, source, proposed, issue);
97
+ });
98
+ let batch = [];
99
+ for await (const item of items) {
100
+ batch.push(item);
101
+ if (batch.length >= chunk) {
102
+ takeChunk(batch);
103
+ batch = [];
104
+ }
105
+ }
106
+ if (batch.length > 0)
107
+ takeChunk(batch);
108
+ return read(database, () => {
109
+ // Read in pages by `idx` until the list is full: the driver offers no cursor, and a run may hold millions.
110
+ const listed = (from, where, of, order = "run.idx") => {
111
+ const kept = [];
112
+ for (let after = -1;;) {
113
+ const rows = database
114
+ .prepare(`${from} WHERE ${order} > ? ${where} ORDER BY ${order} LIMIT ${PAGE}`)
115
+ .all(after);
116
+ for (const row of rows) {
117
+ const item = of(row);
118
+ if (item === null)
119
+ continue;
120
+ if (kept.length === limit) {
121
+ truncated = true;
122
+ return kept;
123
+ }
124
+ kept.push(item);
125
+ }
126
+ if (rows.length < PAGE)
127
+ return kept;
128
+ after = Number(rows[rows.length - 1].position);
129
+ }
130
+ };
131
+ const runRecords = `SELECT run.*, run.idx AS position, r.entity_type, r.entity_id FROM temp.${table} run JOIN records r ON r.id = run.record_id`;
132
+ const waiting = listed(runRecords, "AND r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type NOT LIKE 'custom:%' AND run.unmatched IS NULL", (row) => {
133
+ const missing = missingOf(Number(row.record_id));
134
+ return missing === null ? null : { index: Number(row.idx), key: String(row.key), missing };
135
+ });
136
+ const unmatched = listed(runRecords, "AND run.unmatched IS NOT NULL AND r.entity_id IS NULL", (row) => ({
137
+ index: Number(row.idx),
138
+ key: String(row.key),
139
+ ...JSON.parse(String(row.unmatched)),
140
+ }));
141
+ const flagged = listed(runRecords, "AND run.flagged IS NOT NULL", (row) => ({
142
+ index: Number(row.idx),
143
+ key: String(row.key),
144
+ entity: entityRef(row.entity_type, row.entity_id),
145
+ ...JSON.parse(String(row.flagged)),
146
+ }));
147
+ const ignored = [];
148
+ for (const row of listed(runRecords, "AND run.ignored IS NOT NULL", (one) => one))
149
+ for (const one of JSON.parse(String(row.ignored)))
150
+ if (ignored.length < limit)
151
+ ignored.push({ index: Number(row.idx), key: String(row.key), ...one });
152
+ else
153
+ truncated = true;
154
+ const proposedRefs = listed(`SELECT ref, rowid AS position FROM temp.${proposedTable}`, "", (row) => String(row.ref), "rowid");
155
+ return {
156
+ ...counts,
157
+ errors: errors.sort((a, b) => a.pointer.localeCompare(b.pointer, "en", { numeric: true })),
158
+ proposed: proposedRefs,
159
+ waiting,
160
+ unmatched,
161
+ flagged,
162
+ ignored,
163
+ truncated,
164
+ };
165
+ });
166
+ }
167
+ finally {
168
+ database.exec(`DROP TABLE IF EXISTS temp.${table}`);
169
+ database.exec(`DROP TABLE IF EXISTS temp.${proposedTable}`);
170
+ }
171
+ };
172
+ };
173
+ /** Where a waiting record's receipt entry points: its relations, or the field that names the missing record. */
174
+ export const waitingPointer = (index, missing) => {
175
+ if (missing.some((role) => !isDerived(role)))
176
+ return pointerOf("records", index, "relations");
177
+ const [, key] = missing[0].split(".");
178
+ return pointerOf("records", index, "fields", key);
179
+ };
@@ -0,0 +1,9 @@
1
+ import type { EnvelopeRecord } from "../../domain/records.js";
2
+ import type { financeOperationsOver, PaymentDetail } from "./finance.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type Share } from "./record-projection.js";
5
+ /** How an imported payment settles the invoices its record names. */
6
+ export declare const recordSettlingOver: ({ database }: StoreContext, finance: ReturnType<typeof financeOperationsOver>) => {
7
+ settle: (made: PaymentDetail, shares: Share[]) => string;
8
+ checkShares: (record: EnvelopeRecord) => void;
9
+ };
@@ -0,0 +1,74 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
3
+ import { requiredThing } from "./notes.js";
4
+ import { codeOf, IMPORTER, refusal } from "./record-projection.js";
5
+ import { netPaidSql } from "./refunds.js";
6
+ /** How an imported payment settles the invoices its record names. */
7
+ export const recordSettlingOver = ({ database }, finance) => {
8
+ const sql = (text) => database.prepare(text);
9
+ /**
10
+ * What other payments leave open on an invoice. Proposed ones count too: the owner confirms them later, so payments
11
+ * of one batch would otherwise each take the whole invoice.
12
+ */
13
+ const freeOn = (invoice, payment) => {
14
+ const [target, own] = [requiredThing(database, invoice), requiredThing(database, payment)];
15
+ const row = sql(`SELECT i.total - ${netPaidSql("i.id", { counted: "pending", excluding: "?" })} AS free FROM invoices i WHERE i.id = ?`).get(own.id, target.id);
16
+ return Number(row?.free ?? 0);
17
+ };
18
+ /** A payment settles each invoice it names by the amount the source gives, then the rest as far as both allow. */
19
+ const settle = (made, shares) => {
20
+ const units = (amount) => minorUnits(amount, made.currency);
21
+ let left = units(made.unallocated);
22
+ const given = shares.filter((one) => one.amount !== null);
23
+ for (const { invoice, amount } of [...given, ...shares.filter((one) => one.amount === null)]) {
24
+ const share = amount === null ? Math.min(left, freeOn(invoice, made.ref)) : units(amount);
25
+ if (share <= 0)
26
+ continue;
27
+ finance.allocate({
28
+ payment: made.ref,
29
+ invoice,
30
+ amount: formatDecimal(share, scaleOf(made.currency)),
31
+ by: IMPORTER,
32
+ });
33
+ left -= share;
34
+ }
35
+ return made.ref;
36
+ };
37
+ /** The settles amounts a payment record gives, refused at the first one that is not money or goes past the payment. */
38
+ const checkShares = (record) => {
39
+ const relations = record.relations ?? [];
40
+ if (!relations.some((relation) => relation.amount !== undefined))
41
+ return;
42
+ const fields = record.fields ?? {};
43
+ if (typeof fields.currency !== "string")
44
+ return;
45
+ const currency = fields.currency;
46
+ let left;
47
+ try {
48
+ left = minorUnits(fields.amount, currency);
49
+ }
50
+ catch {
51
+ return;
52
+ }
53
+ for (const [index, { amount }] of relations.entries()) {
54
+ if (amount === undefined)
55
+ continue;
56
+ const at = ["relations", index, "amount"];
57
+ let units = 0;
58
+ try {
59
+ units = minorUnits(amount, currency, "a settles amount");
60
+ }
61
+ catch (error) {
62
+ if (!(error instanceof CliError))
63
+ throw error;
64
+ refusal(error.message, codeOf(error), at);
65
+ }
66
+ if (units <= 0)
67
+ refusal("a settles amount is more than 0", "money.amount", at);
68
+ left -= units;
69
+ if (left < 0)
70
+ refusal(`the settles amounts add up to more than the payment's ${String(fields.amount)} ${currency}`, "record.over-payment", at);
71
+ }
72
+ };
73
+ return { settle, checkShares };
74
+ };
@@ -0,0 +1,13 @@
1
+ import { type RecordType } from "../../domain/record-types.js";
2
+ import type { StoreContext } from "./open.js";
3
+ /**
4
+ * What the import last wrote of a proposal it may re-propose: a digest of the row and its parts, kept in the row's
5
+ * metadata. An owner may edit a proposal (its lines, its splits) without deciding it, and his edit is never
6
+ * overwritten: the import changes the proposal only while the digest still matches.
7
+ */
8
+ export declare const importStampsOver: ({ database }: StoreContext) => {
9
+ stamp: (type: RecordType, id: number) => {
10
+ changes: number;
11
+ };
12
+ untouched: (type: RecordType, id: number) => boolean;
13
+ };
@@ -0,0 +1,30 @@
1
+ import { createHash } from "node:crypto";
2
+ import { nestedOf, RECORD_TYPES } from "../../domain/record-types.js";
3
+ const VOLATILE = new Set(["id", "created_at", "updated_at", "metadata"]);
4
+ const content = (row) => row === undefined ? null : Object.fromEntries(Object.entries(row).filter(([column]) => !VOLATILE.has(column)));
5
+ /**
6
+ * What the import last wrote of a proposal it may re-propose: a digest of the row and its parts, kept in the row's
7
+ * metadata. An owner may edit a proposal (its lines, its splits) without deciding it, and his edit is never
8
+ * overwritten: the import changes the proposal only while the digest still matches.
9
+ */
10
+ export const importStampsOver = ({ database }) => {
11
+ const stateOf = (type, id) => {
12
+ const { table } = RECORD_TYPES[type];
13
+ const parts = nestedOf(type).map(([, nested]) => database
14
+ .prepare(`SELECT * FROM ${nested.table} WHERE ${nested.parent} = ? ORDER BY id`)
15
+ .all(id)
16
+ .map((row) => content(row)));
17
+ const row = database.prepare(`SELECT * FROM ${table} WHERE id = ?`).get(id);
18
+ return createHash("sha256")
19
+ .update(JSON.stringify([content(row), parts]))
20
+ .digest("hex");
21
+ };
22
+ const stamp = (type, id) => database
23
+ .prepare(`UPDATE ${RECORD_TYPES[type].table} SET metadata = json_set(coalesce(metadata, '{}'), '$.imported', ?) ` +
24
+ "WHERE id = ?")
25
+ .run(stateOf(type, id), id);
26
+ const untouched = (type, id) => database
27
+ .prepare(`SELECT json_extract(metadata, '$.imported') AS stamp FROM ${RECORD_TYPES[type].table} WHERE id = ?`)
28
+ .get(id)?.stamp === stateOf(type, id);
29
+ return { stamp, untouched };
30
+ };
@@ -0,0 +1,43 @@
1
+ import { type EnvelopeOptions, type EnvelopeRecord, type EnvelopeSource, type IngestError } from "../../domain/records.js";
2
+ import type { StoreContext } from "./open.js";
3
+ import { type Row } from "./record-projection.js";
4
+ /** Why a changed record's entity was left alone, beyond the source having changed it. */
5
+ export interface Flag {
6
+ reason?: string;
7
+ candidates?: string[];
8
+ }
9
+ export interface Unresolved {
10
+ reason: string;
11
+ candidates: string[];
12
+ }
13
+ /** A value of the record that looks like an identifier and was kept as data only. */
14
+ export interface Ignored {
15
+ at: (string | number)[];
16
+ reason: string;
17
+ }
18
+ export interface WriteOutcome {
19
+ status: "created" | "updated" | "unchanged" | "deleted";
20
+ id: number;
21
+ ignored?: Ignored[];
22
+ flagged?: Flag;
23
+ /** It now has an entity, so the records waiting on it may get theirs. */
24
+ complete?: boolean;
25
+ unmatched?: Unresolved;
26
+ }
27
+ interface Projected {
28
+ ignored?: Ignored[];
29
+ made?: string;
30
+ /** Made as a proposal. */
31
+ proposed?: string;
32
+ missing: string[];
33
+ unmatched?: Unresolved;
34
+ }
35
+ /** One record into the store and into its entity, as its type's registry entry says. */
36
+ export declare const recordWritesOver: (context: StoreContext) => {
37
+ writeOne: (accountId: number, source: EnvelopeSource, record: EnvelopeRecord, options: EnvelopeOptions, proposed: (ref: string) => void) => WriteOutcome;
38
+ project: (row: Row, source: EnvelopeSource, options?: EnvelopeOptions) => Projected;
39
+ completeDependents: (target: number, source: EnvelopeSource, proposed: (ref: string) => void, laterError: (error: IngestError) => void) => void;
40
+ entityRef: (type: unknown, id: unknown) => string | null;
41
+ missingOf: (id: number) => string[] | null;
42
+ };
43
+ export {};