@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,26 @@
1
+ import { type Projection } from "./record-projection.js";
2
+ export declare const MONEY_PROJECTORS: {
3
+ readonly invoice: {
4
+ readonly create: (projection: Projection, { finance }: import("./record-projection.js").ProjectionTools) => string;
5
+ };
6
+ readonly payment: {
7
+ readonly create: (projection: Projection, { finance, settle }: import("./record-projection.js").ProjectionTools) => string;
8
+ readonly update: (ref: string, projection: Projection, { finance, settle, context }: import("./record-projection.js").ProjectionTools) => boolean;
9
+ };
10
+ readonly order: {
11
+ readonly create: (projection: Projection, { orders }: import("./record-projection.js").ProjectionTools) => string;
12
+ readonly update: (ref: string, projection: Projection, { orders }: import("./record-projection.js").ProjectionTools) => boolean;
13
+ };
14
+ readonly contract: {
15
+ readonly create: (projection: Projection, { contracts }: import("./record-projection.js").ProjectionTools) => string;
16
+ readonly update: (ref: string, projection: Projection, { contracts }: import("./record-projection.js").ProjectionTools) => boolean;
17
+ };
18
+ readonly subscription: {
19
+ readonly create: (projection: Projection, { subscriptions }: import("./record-projection.js").ProjectionTools) => string;
20
+ readonly update: (ref: string, projection: Projection, { subscriptions }: import("./record-projection.js").ProjectionTools) => boolean;
21
+ };
22
+ readonly transaction: {
23
+ readonly create: (projection: Projection, { transactions }: import("./record-projection.js").ProjectionTools) => string;
24
+ readonly update: (ref: string, projection: Projection, { transactions }: import("./record-projection.js").ProjectionTools) => boolean;
25
+ };
26
+ };
@@ -0,0 +1,214 @@
1
+ import { authorActor } from "./memories.js";
2
+ import { requiredThing } from "./notes.js";
3
+ import { entityOf, given, IMPORTER, importedBy, importersProposal, moneyLinesOf, refusal, stringField, } from "./record-projection.js";
4
+ const allocatedByOthers = (context, paymentId) => {
5
+ const importer = authorActor(context, IMPORTER).actor;
6
+ return (context.database
7
+ .prepare("SELECT 1 FROM payment_allocations WHERE payment_id = ? AND NOT (author_type = ? AND author_id = ?) LIMIT 1")
8
+ .get(paymentId, importer.type, importer.id) !== undefined);
9
+ };
10
+ /** v1's single roles, which `fields.<role>` may also name as a store ref; roles added later come from relations only. */
11
+ const v1Role = (projection, role) => entityOf(projection, role) ?? stringField(projection.fields, role);
12
+ const invoiceOf = (projection) => {
13
+ const { fields, source } = projection;
14
+ if (!Array.isArray(fields.lines) || fields.lines.some((line) => typeof line !== "object" || line === null))
15
+ return refusal("an invoice's fields.lines is a list of lines", "record.invalid");
16
+ return {
17
+ ...importedBy(source),
18
+ direction: fields.direction,
19
+ number: stringField(fields, "number"),
20
+ issuer: v1Role(projection, "issuer"),
21
+ counterparty: v1Role(projection, "counterparty"),
22
+ project: v1Role(projection, "project"),
23
+ contract: entityOf(projection, "contract"),
24
+ subscription: entityOf(projection, "subscription"),
25
+ currency: fields.currency,
26
+ issueDate: stringField(fields, "issue_date"),
27
+ dueDate: stringField(fields, "due_date"),
28
+ total: fields.total,
29
+ lines: moneyLinesOf(projection, fields.lines),
30
+ };
31
+ };
32
+ const paymentOf = (projection) => {
33
+ const { fields, source } = projection;
34
+ return {
35
+ ...importedBy(source),
36
+ direction: fields.direction,
37
+ payer: v1Role(projection, "payer"),
38
+ payee: v1Role(projection, "payee"),
39
+ project: v1Role(projection, "project"),
40
+ refundOf: entityOf(projection, "refund_of"),
41
+ subscription: entityOf(projection, "subscription"),
42
+ amount: fields.amount,
43
+ currency: fields.currency,
44
+ date: fields.date,
45
+ reference: stringField(fields, "reference"),
46
+ };
47
+ };
48
+ const orderOf = (projection) => {
49
+ const { fields, source } = projection;
50
+ return {
51
+ ...importedBy(source),
52
+ customer: entityOf(projection, "customer"),
53
+ supplier: entityOf(projection, "supplier"),
54
+ project: entityOf(projection, "project"),
55
+ contract: entityOf(projection, "contract"),
56
+ deal: entityOf(projection, "deal"),
57
+ invoice: entityOf(projection, "invoice"),
58
+ payment: entityOf(projection, "payment"),
59
+ purpose: given(fields, "purpose") ?? "business",
60
+ direction: given(fields, "direction"),
61
+ status: given(fields, "status"),
62
+ supplierName: given(fields, "supplier_name"),
63
+ number: given(fields, "number"),
64
+ orderDate: given(fields, "order_date"),
65
+ fulfilledDate: given(fields, "fulfilled_date"),
66
+ currency: given(fields, "currency"),
67
+ total: given(fields, "total"),
68
+ sourceUrl: given(fields, "source_url"),
69
+ ...(Array.isArray(fields.lines) ? { lines: moneyLinesOf(projection, fields.lines) } : {}),
70
+ };
71
+ };
72
+ const contractFields = (projection) => {
73
+ const { fields } = projection;
74
+ return {
75
+ name: given(fields, "name"),
76
+ kind: given(fields, "kind"),
77
+ number: given(fields, "number"),
78
+ status: given(fields, "status"),
79
+ signedDate: given(fields, "signed_date"),
80
+ effectiveDate: given(fields, "effective_date"),
81
+ expirationDate: given(fields, "expiration_date"),
82
+ autoRenew: given(fields, "auto_renew"),
83
+ renewal: given(fields, "renewal"),
84
+ noticeDays: given(fields, "notice_days"),
85
+ terms: given(fields, "terms"),
86
+ value: given(fields, "value"),
87
+ currency: given(fields, "currency"),
88
+ deal: entityOf(projection, "deal"),
89
+ };
90
+ };
91
+ const subscriptionFields = (projection) => {
92
+ const { fields } = projection;
93
+ return {
94
+ name: given(fields, "name"),
95
+ direction: given(fields, "direction"),
96
+ supplier: entityOf(projection, "supplier"),
97
+ customer: entityOf(projection, "customer"),
98
+ product: entityOf(projection, "product"),
99
+ contract: entityOf(projection, "contract"),
100
+ status: given(fields, "status"),
101
+ every: given(fields, "interval"),
102
+ startDate: given(fields, "start_date"),
103
+ trialEndDate: given(fields, "trial_end_date"),
104
+ nextRenewalDate: given(fields, "next_renewal_date"),
105
+ cancelledDate: given(fields, "cancelled_date"),
106
+ endDate: given(fields, "end_date"),
107
+ };
108
+ };
109
+ const pricesOf = (projection) => (Array.isArray(projection.fields.prices) ? projection.fields.prices : []).map((price) => ({
110
+ amount: price.amount,
111
+ currency: price.currency,
112
+ ...(typeof price.effective_from === "string" ? { effectiveFrom: price.effective_from } : {}),
113
+ }));
114
+ const transactionFields = (projection) => {
115
+ const { fields } = projection;
116
+ return {
117
+ direction: fields.direction,
118
+ amount: fields.amount,
119
+ status: given(fields, "status"),
120
+ statementDate: fields.date,
121
+ bookedDate: given(fields, "booked_date"),
122
+ description: given(fields, "description"),
123
+ counterpartyName: given(fields, "counterparty_name"),
124
+ counterparty: entityOf(projection, "counterparty"),
125
+ reference: given(fields, "reference"),
126
+ payment: entityOf(projection, "payment"),
127
+ };
128
+ };
129
+ const splitsOf = (projection) => (Array.isArray(projection.fields.splits) ? projection.fields.splits : []).map((split) => ({
130
+ amount: split.amount,
131
+ category: split.category,
132
+ ...(typeof split.note === "string" ? { note: split.note } : {}),
133
+ }));
134
+ export const MONEY_PROJECTORS = {
135
+ invoice: { create: (projection, { finance }) => finance.addInvoice(invoiceOf(projection)).ref },
136
+ payment: {
137
+ create: (projection, { finance, settle }) => settle(finance.addPayment(paymentOf(projection)), projection.shares),
138
+ // Only the import's own allocations are taken back: one the owner made on its proposal leaves the change flagged.
139
+ update: (ref, projection, { finance, settle, context }) => {
140
+ const payment = finance.payment(ref);
141
+ if (!importersProposal(payment) || allocatedByOthers(context, requiredThing(context.database, ref).id))
142
+ return false;
143
+ for (const { invoice } of payment.allocations)
144
+ finance.unallocate({ payment: ref, invoice, by: IMPORTER });
145
+ settle(finance.payment(ref), projection.shares);
146
+ return true;
147
+ },
148
+ },
149
+ order: {
150
+ create: (projection, { orders }) => orders.add(orderOf(projection)).ref,
151
+ update: (ref, projection, { orders }) => {
152
+ if (!importersProposal(orders.get(ref)))
153
+ return false;
154
+ orders.revise(ref, orderOf(projection));
155
+ return true;
156
+ },
157
+ },
158
+ contract: {
159
+ create: (projection, { contracts }) => contracts.add({
160
+ ...importedBy(projection.source),
161
+ ...contractFields(projection),
162
+ project: entityOf(projection, "project"),
163
+ }).ref,
164
+ update: (ref, projection, { contracts }) => {
165
+ if (!importersProposal(contracts.get(ref)))
166
+ return false;
167
+ contracts.update(ref, { by: importedBy(projection.source).by, ...contractFields(projection) });
168
+ return true;
169
+ },
170
+ },
171
+ subscription: {
172
+ create: (projection, { subscriptions }) => subscriptions.add({
173
+ ...importedBy(projection.source),
174
+ ...subscriptionFields(projection),
175
+ project: entityOf(projection, "project"),
176
+ prices: pricesOf(projection),
177
+ }).ref,
178
+ update: (ref, projection, { subscriptions }) => {
179
+ const held = subscriptions.get(ref);
180
+ if (!importersProposal(held))
181
+ return false;
182
+ const { by, source, reason } = importedBy(projection.source);
183
+ subscriptions.update(ref, { by, ...subscriptionFields(projection) });
184
+ const kept = new Set(held.prices.filter((one) => one.review !== "rejected").map((one) => one.effectiveFrom));
185
+ const start = given(projection.fields, "start_date");
186
+ for (const price of pricesOf(projection))
187
+ if (!kept.has(price.effectiveFrom ?? start))
188
+ subscriptions.addPrice(ref, { ...price, by, source, reason });
189
+ return true;
190
+ },
191
+ },
192
+ transaction: {
193
+ create: (projection, { transactions }) => transactions.add({
194
+ ...importedBy(projection.source),
195
+ ...transactionFields(projection),
196
+ wallet: entityOf(projection, "wallet"),
197
+ currency: given(projection.fields, "currency"),
198
+ project: entityOf(projection, "project"),
199
+ splits: splitsOf(projection),
200
+ }).ref,
201
+ update: (ref, projection, { transactions }) => {
202
+ const held = transactions.get(ref);
203
+ if (!importersProposal(held))
204
+ return false;
205
+ const { by } = importedBy(projection.source);
206
+ for (const { position } of held.splits)
207
+ transactions.removeSplit(ref, { position, by });
208
+ transactions.update(ref, { by, ...transactionFields(projection) });
209
+ for (const split of splitsOf(projection))
210
+ transactions.addSplit(ref, { ...split, by });
211
+ return true;
212
+ },
213
+ },
214
+ };
@@ -0,0 +1,28 @@
1
+ import type { EnvelopeSource } from "../../domain/records.js";
2
+ import { type Projection, type ProjectionTools } from "./record-projection.js";
3
+ /**
4
+ * A messenger's or a calendar's account is its sync's: an SMS or a call written there would land in a real chat or
5
+ * calendar. Only a provider marked import-only (`imported`, as the seeded `phone`) takes them.
6
+ */
7
+ export declare const importOnly: (source: EnvelopeSource, type: string) => void;
8
+ declare const updateSms: (ref: string, projection: Projection, tools: ProjectionTools) => boolean;
9
+ declare const saveCall: (projection: Projection, tools: ProjectionTools) => string;
10
+ /** A deleted record's SMS or call goes as a messenger's deleted message goes: the copy is a tombstone. */
11
+ declare const removeSms: (ref: string, { context }: ProjectionTools) => void;
12
+ declare const removeCall: (ref: string, { context }: ProjectionTools) => void;
13
+ declare const restoreCall: (_ref: string, projection: Projection, tools: ProjectionTools) => void;
14
+ export declare const PHONE_PROJECTORS: {
15
+ readonly message: {
16
+ readonly create: (projection: Projection, tools: ProjectionTools) => string;
17
+ readonly update: typeof updateSms;
18
+ readonly remove: typeof removeSms;
19
+ readonly restore: (ref: string, projection: Projection, tools: ProjectionTools) => void;
20
+ };
21
+ readonly event: {
22
+ readonly create: typeof saveCall;
23
+ readonly update: (_ref: string, projection: Projection, tools: ProjectionTools) => true;
24
+ readonly remove: typeof removeCall;
25
+ readonly restore: typeof restoreCall;
26
+ };
27
+ };
28
+ export {};
@@ -0,0 +1,212 @@
1
+ import { isImportedProvider } from "../../domain/providers.js";
2
+ import { article } from "../../domain/record-types.js";
3
+ import { formatReference, parseReference } from "../../domain/references.js";
4
+ import { calendarWritesOver } from "./calendar.js";
5
+ import { chatPkFor, findChatPk, raiseLastMessageAt, upsertChat, writeMembers } from "./chats.js";
6
+ import { seenIdentity } from "./identities.js";
7
+ import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
8
+ import { tombstone, upsertMessage } from "./messages.js";
9
+ import { requiredThing } from "./notes.js";
10
+ import { e164Of, importedIdentity, linkToPerson } from "./record-matching.js";
11
+ import { entityOf, given, importedBy, refusal, } from "./record-projection.js";
12
+ const CALLS_CALENDAR = "calls";
13
+ /**
14
+ * A messenger's or a calendar's account is its sync's: an SMS or a call written there would land in a real chat or
15
+ * calendar. Only a provider marked import-only (`imported`, as the seeded `phone`) takes them.
16
+ */
17
+ export const importOnly = (source, type) => {
18
+ if (!isImportedProvider(source.provider))
19
+ refusal(`${article(type)} ${type} is imported only under an import-only provider such as phone; ${source.provider} is not one`, "record.provider-not-imported", "type");
20
+ };
21
+ /** E.164 as a person record's phone reads, so the thread and the person agree; as written otherwise (a short code). */
22
+ const numberOf = ({ options }, typed) => e164Of(typed, options.phone_region?.toLowerCase()) ?? typed.trim();
23
+ /** The import's own account holds its SMS and calls too, so one `provider:account` in a group reaches all of it. */
24
+ const sourceAccount = ({ source, accountId }) => ({
25
+ provider: source.provider,
26
+ account: source.account,
27
+ pk: accountId,
28
+ });
29
+ const counterpartOf = (projection, { context }) => {
30
+ const ref = entityOf(projection, "counterpart");
31
+ return ref === undefined ? undefined : requiredThing(context.database, ref).id;
32
+ };
33
+ /** The schema checks the shape only: a 13th month passes it, and must refuse this record, not the run. */
34
+ const millis = (fields, name) => {
35
+ const at = Date.parse(String(fields[name]));
36
+ return Number.isNaN(at) ? refusal(`fields.${name} is no moment`, "record.invalid", ["fields", name]) : at;
37
+ };
38
+ const threadOf = (projection) => given(projection.fields, "thread") ?? numberOf(projection, String(projection.fields.phone));
39
+ const saveSms = (projection, tools, revive = false) => {
40
+ importOnly(projection.source, "message");
41
+ const { context } = tools;
42
+ const { fields, externalId, source } = projection;
43
+ const sentAt = millis(fields, "sent_at");
44
+ const account = sourceAccount(projection);
45
+ const phone = numberOf(projection, String(fields.phone));
46
+ const name = given(fields, "name") ?? null;
47
+ const incoming = fields.direction === "in";
48
+ const chatId = threadOf(projection);
49
+ const held = findChatPk(context, account.pk, chatId);
50
+ const membership = held === undefined
51
+ ? undefined
52
+ : context.database.prepare("SELECT membership_state FROM chats WHERE id = ?").get(held);
53
+ if (membership !== undefined && membership.membership_state !== "imported")
54
+ refusal(`chat ${chatId} of ${account.provider}:${account.account} is not an imported one`, "record.chat", [
55
+ "fields",
56
+ "thread",
57
+ ]);
58
+ const identity = importedIdentity(context, {
59
+ provider: account.provider,
60
+ externalId: phone,
61
+ name,
62
+ ...(phone.startsWith("+") ? { phone } : {}),
63
+ });
64
+ const person = counterpartOf(projection, tools);
65
+ // Linked before the identity is seen: the messenger path gives an identity with no person one of its own.
66
+ if (person !== undefined)
67
+ linkToPerson(context, person, identity, source);
68
+ seenIdentity(context, account.pk, account.provider, phone, name);
69
+ upsertChat(context, account.pk, { id: chatId, kind: "dialog", title: name ?? phone, membershipState: "imported" });
70
+ writeMembers(context, account, account.pk, chatId, [phone]);
71
+ const chatKey = chatPkFor(context, account.pk, chatId);
72
+ const read = given(fields, "read");
73
+ const message = {
74
+ id: externalId,
75
+ chatId,
76
+ senderId: incoming ? phone : null,
77
+ senderName: incoming ? name : null,
78
+ timestamp: new Date(sentAt).toISOString(),
79
+ editedAt: null,
80
+ text: String(fields.body),
81
+ outgoing: !incoming,
82
+ attachments: [],
83
+ replyTo: null,
84
+ forwardedFrom: null,
85
+ reactions: null,
86
+ ...(read === undefined ? {} : { providerMetadata: { read } }),
87
+ };
88
+ // Seen after its tombstone, the messenger path takes a deleted message back, its text with it.
89
+ upsertMessage(context, account, account.pk, chatKey, message, importedBy(source).source, revive ? context.now() + 1 : undefined);
90
+ raiseLastMessageAt(context, chatKey, sentAt);
91
+ return formatReference({
92
+ type: "message",
93
+ provider: account.provider,
94
+ account: account.account,
95
+ chat: chatId,
96
+ message: externalId,
97
+ });
98
+ };
99
+ /** A changed thread or number would make a second message: the one stored stays where it is. */
100
+ const staysInThread = (ref, projection) => {
101
+ const stored = parseReference(ref);
102
+ if (stored.type === "message" && stored.chat !== threadOf(projection))
103
+ refusal(`an SMS stays in its thread (${stored.chat}): delete it and send it again under a new external_id`, "record.moved", ["fields", "thread"]);
104
+ };
105
+ const updateSms = (ref, projection, tools) => {
106
+ staysInThread(ref, projection);
107
+ saveSms(projection, tools);
108
+ return true;
109
+ };
110
+ const DESCRIPTIONS = {
111
+ in: "incoming call",
112
+ out: "outgoing call",
113
+ missed: "missed call",
114
+ };
115
+ /** The account's calls calendar, made on its first call; looked up by its account each time, never by a held id. */
116
+ const callsCalendar = (context, account) => {
117
+ const row = context.database
118
+ .prepare("SELECT id FROM calendars WHERE account_id = ? AND external_id = ?")
119
+ .get(account.pk, CALLS_CALENDAR);
120
+ return row !== undefined
121
+ ? Number(row.id)
122
+ : calendarWritesOver(context).saveCalendar(account.pk, {
123
+ externalId: CALLS_CALENDAR,
124
+ title: "Calls",
125
+ timezone: null,
126
+ accessRole: "owner",
127
+ primary: true,
128
+ syncByDefault: false,
129
+ }, context.now()).id;
130
+ };
131
+ const relinkCounterpart = (context, eventId, person) => {
132
+ const at = context.now();
133
+ context.database
134
+ .prepare(`DELETE FROM links WHERE from_type = 'event' AND from_id = ? AND to_type = 'person' AND kind = ${linkKind("related-to")}
135
+ AND role = ? AND source = 'import'`)
136
+ .run(eventId, COUNTERPART_ROLE);
137
+ if (person !== undefined)
138
+ context.database
139
+ .prepare(`INSERT INTO links (from_type, from_id, to_type, to_id, kind, role, source, confirmed, created_at, author,
140
+ updated_at) VALUES ('event', ?, 'person', ?, ${linkKind("related-to")}, ?, 'import', 1, ?, 'import', ?)`)
141
+ .run(eventId, person, COUNTERPART_ROLE, at, at);
142
+ };
143
+ const saveCall = (projection, tools) => {
144
+ importOnly(projection.source, "event");
145
+ const { context } = tools;
146
+ const { fields, externalId } = projection;
147
+ const startsAt = millis(fields, "started_at");
148
+ const calendarId = callsCalendar(context, sourceAccount(projection));
149
+ const phone = numberOf(projection, String(fields.phone));
150
+ const direction = fields.direction;
151
+ const seconds = given(fields, "duration") ?? 0;
152
+ const entry = {
153
+ externalId,
154
+ kind: "single",
155
+ status: "confirmed",
156
+ title: given(fields, "name") ?? phone,
157
+ description: DESCRIPTIONS[direction],
158
+ startsAt,
159
+ endsAt: startsAt + seconds * 1000,
160
+ allDay: false,
161
+ eventType: "call",
162
+ // A call never makes the owner busy in a plan or overlaps a meeting: it is history, not a booking.
163
+ transparency: "transparent",
164
+ participants: [],
165
+ metadata: { callDirection: direction, callSeconds: seconds, callNumber: phone },
166
+ };
167
+ const [saved] = calendarWritesOver(context).saveAll(calendarId, [entry], context.now());
168
+ const eventId = Number(saved?.eventId);
169
+ relinkCounterpart(context, eventId, counterpartOf(projection, tools));
170
+ return `event:${eventId}`;
171
+ };
172
+ /** A deleted record's SMS or call goes as a messenger's deleted message goes: the copy is a tombstone. */
173
+ const removeSms = (ref, { context }) => {
174
+ tombstone(context, requiredThing(context.database, ref).id);
175
+ };
176
+ const removeCall = (ref, { context }) => {
177
+ const eventId = requiredThing(context.database, ref).id;
178
+ const writes = calendarWritesOver(context);
179
+ for (const row of context.database
180
+ .prepare("SELECT calendar_id, external_id FROM calendar_entries WHERE event_id = ? AND event_type = 'call'")
181
+ .all(eventId))
182
+ writes.removeAll(Number(row.calendar_id), [String(row.external_id)], context.now());
183
+ context.database
184
+ .prepare("UPDATE events SET deleted_at = coalesce(deleted_at, ?), updated_at = ? WHERE id = ?")
185
+ .run(context.now(), context.now(), eventId);
186
+ };
187
+ const restoreCall = (_ref, projection, tools) => {
188
+ const eventId = requiredThing(tools.context.database, saveCall(projection, tools)).id;
189
+ tools.context.database
190
+ .prepare("UPDATE events SET deleted_at = NULL, updated_at = ? WHERE id = ?")
191
+ .run(tools.context.now(), eventId);
192
+ };
193
+ export const PHONE_PROJECTORS = {
194
+ message: {
195
+ create: (projection, tools) => saveSms(projection, tools),
196
+ update: updateSms,
197
+ remove: removeSms,
198
+ restore: (ref, projection, tools) => {
199
+ staysInThread(ref, projection);
200
+ saveSms(projection, tools, true);
201
+ },
202
+ },
203
+ event: {
204
+ create: saveCall,
205
+ update: (_ref, projection, tools) => {
206
+ saveCall(projection, tools);
207
+ return true;
208
+ },
209
+ remove: removeCall,
210
+ restore: restoreCall,
211
+ },
212
+ };
@@ -1,44 +1,3 @@
1
- import { type RecordEntityType } from "../../domain/record-types.js";
2
- import type { EnvelopeSource } from "../../domain/records.js";
3
- import type { financeOperationsOver, PaymentDetail } from "./finance.js";
4
- export type Row = Record<string, unknown>;
5
- export interface Share {
6
- invoice: string;
7
- /** As the source gave it; `null` settles as far as both allow. */
8
- amount: string | null;
9
- }
10
- /** The entities a record's relations resolved to, by role, and what each invoice a payment settles gets. */
11
- export interface Related {
12
- related: Map<string, string[]>;
13
- shares: Share[];
14
- }
15
- export interface ProjectionTools {
16
- finance: ReturnType<typeof financeOperationsOver>;
17
- settle: (made: PaymentDetail, shares: Share[]) => string;
18
- }
19
- /** Makes the proposal a record stands for and returns its ref. */
20
- export type Projector = (fields: Row, related: Related, source: EnvelopeSource, tools: ProjectionTools) => string;
21
- export declare const IMPORTER: {
22
- readonly bot: "import";
23
- };
24
- /** `at` names the record's member at fault; a refused entity is the fields' fault. */
25
- export declare const refusal: (message: string, code: string, at?: string | (string | number)[]) => never;
26
- export declare const stringField: (fields: Row, name: string) => string | undefined;
27
- /** `null` for a type whose entity only the owner's `map` gives. */
28
- export declare const RECORD_PROJECTORS: {
29
- readonly invoice: (fields: Row, { related }: Related, source: EnvelopeSource, { finance }: ProjectionTools) => string;
30
- readonly payment: (fields: Row, { related, shares }: Related, source: EnvelopeSource, { finance, settle }: ProjectionTools) => string;
31
- readonly person: null;
32
- readonly organization: null;
33
- readonly project: null;
34
- };
35
- export type ProjectedType = {
36
- [K in RecordEntityType]: (typeof RECORD_PROJECTORS)[K] extends null ? never : K;
37
- }[RecordEntityType];
38
- export declare const PROJECTED_TYPES: ProjectedType[];
39
- export declare const isProjected: (type: unknown) => type is ProjectedType;
40
- /**
41
- * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
42
- * whose `fields.payer` is not text is refused, as before the registry.
43
- */
44
- export declare const FIELD_REFERENCE_ROLES: string[];
1
+ import type { RecordProjectors } from "./record-projection.js";
2
+ /** One projector per registered type; `null` for the types whose entity is matched or made from identifiers. */
3
+ export declare const RECORD_PROJECTORS: RecordProjectors;
@@ -1,72 +1,12 @@
1
- import { CliError } from "@wirecat/cli-base";
2
- import { RECORD_ENTITY_TYPES, roleNames } from "../../domain/record-types.js";
3
- export const IMPORTER = { bot: "import" };
4
- /** `at` names the record's member at fault; a refused entity is the fields' fault. */
5
- export const refusal = (message, code, at) => {
6
- throw new CliError("validation_error", message, { reason: code, ...(at === undefined ? {} : { at }) });
7
- };
8
- export const stringField = (fields, name) => {
9
- const value = fields[name];
10
- if (value === undefined || value === null)
11
- return undefined;
12
- if (typeof value !== "string")
13
- return refusal(`fields.${name} is text`, "record.invalid");
14
- return value;
15
- };
16
- const written = (source) => ({
17
- by: IMPORTER,
18
- source: `import:${source.provider}`,
19
- reason: `imported from ${source.provider} account ${source.account}, batch ${source.batch_id}`,
20
- });
21
- const invoiceOf = (fields, related, source) => {
22
- if (!Array.isArray(fields.lines) || fields.lines.some((line) => typeof line !== "object" || line === null))
23
- return refusal("an invoice's fields.lines is a list of lines", "record.invalid");
24
- const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
25
- return {
26
- ...written(source),
27
- direction: fields.direction,
28
- number: stringField(fields, "number"),
29
- issuer: one("issuer"),
30
- counterparty: one("counterparty"),
31
- project: one("project"),
32
- currency: fields.currency,
33
- issueDate: stringField(fields, "issue_date"),
34
- dueDate: stringField(fields, "due_date"),
35
- total: fields.total,
36
- lines: fields.lines.map((line) => ({
37
- description: line.description,
38
- quantity: line.quantity,
39
- unitPrice: line.unit_price,
40
- amount: line.amount,
41
- })),
42
- };
43
- };
44
- const paymentOf = (fields, related, source) => {
45
- const one = (role) => related.get(role)?.[0] ?? stringField(fields, role);
46
- return {
47
- ...written(source),
48
- direction: fields.direction,
49
- payer: one("payer"),
50
- payee: one("payee"),
51
- project: one("project"),
52
- amount: fields.amount,
53
- currency: fields.currency,
54
- date: fields.date,
55
- reference: stringField(fields, "reference"),
56
- };
57
- };
58
- /** `null` for a type whose entity only the owner's `map` gives. */
1
+ import { DIRECT_PROJECTORS } from "./record-projectors-direct.js";
2
+ import { MONEY_PROJECTORS } from "./record-projectors-money.js";
3
+ import { PHONE_PROJECTORS } from "./record-projectors-phone.js";
4
+ /** One projector per registered type; `null` for the types whose entity is matched or made from identifiers. */
59
5
  export const RECORD_PROJECTORS = {
60
- invoice: (fields, { related }, source, { finance }) => finance.addInvoice(invoiceOf(fields, related, source)).ref,
61
- payment: (fields, { related, shares }, source, { finance, settle }) => settle(finance.addPayment(paymentOf(fields, related, source)), shares),
6
+ ...MONEY_PROJECTORS,
7
+ ...DIRECT_PROJECTORS,
8
+ ...PHONE_PROJECTORS,
62
9
  person: null,
63
10
  organization: null,
64
11
  project: null,
65
12
  };
66
- export const PROJECTED_TYPES = RECORD_ENTITY_TYPES.filter((type) => RECORD_PROJECTORS[type] !== null);
67
- export const isProjected = (type) => PROJECTED_TYPES.includes(type);
68
- /**
69
- * Single roles a record may also name in `fields.<role>`. Pooled across the projected types on purpose: an invoice
70
- * whose `fields.payer` is not text is refused, as before the registry.
71
- */
72
- export const FIELD_REFERENCE_ROLES = roleNames(PROJECTED_TYPES, (role) => !role.many);
@@ -0,0 +1,24 @@
1
+ import { type RecordType } from "../../domain/record-types.js";
2
+ import type { RecordRelation } from "../../domain/records.js";
3
+ import type { StoreContext } from "./open.js";
4
+ import { type Share } from "./record-projection.js";
5
+ /** A reference a record's fields make (`fields.pipeline`, `fields.lines.product`): no role a source sends has a dot. */
6
+ export declare const isDerived: (role: string) => boolean;
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 declare const recordRelationsOver: ({ database }: StoreContext) => {
9
+ entityRef: (type: unknown, id: unknown) => string | null;
10
+ relatedOf: (recordId: number, type: RecordType) => {
11
+ related: Map<string, string[]>;
12
+ as: Map<string, (string | null)[]>;
13
+ shares: Share[];
14
+ products: Map<string, string>;
15
+ missing: string[];
16
+ };
17
+ storedRelations: (recordId: number) => RecordRelation[];
18
+ relate: (recordId: number, accountId: number, relations: (RecordRelation | {
19
+ role: string;
20
+ type: string;
21
+ external_id: string;
22
+ })[], at: number) => void;
23
+ missingOf: (id: number) => string[] | null;
24
+ };