@wirecat/cli-core 0.606.0 → 0.608.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.
- package/CHANGELOG.md +196 -0
- package/dist/calendar/index.d.ts +1 -0
- package/dist/calendar/index.js +1 -0
- package/dist/calendar/reads.js +5 -0
- package/dist/cli/app-mcp-command.d.ts +6 -2
- package/dist/cli/app-mcp-command.js +11 -2
- package/dist/cli/csv.d.ts +10 -0
- package/dist/cli/csv.js +22 -0
- package/dist/cli/early-refusal.d.ts +10 -0
- package/dist/cli/early-refusal.js +19 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.js +3 -0
- package/dist/cli/profile-token.d.ts +29 -0
- package/dist/cli/profile-token.js +65 -0
- package/dist/cli/program.js +4 -2
- package/dist/crm/cli/csv.d.ts +23 -0
- package/dist/crm/cli/csv.js +135 -0
- package/dist/crm/cli/index.d.ts +1 -1
- package/dist/crm/cli/index.js +33 -21
- package/dist/crm/cli/pipeline-view.d.ts +3 -0
- package/dist/crm/cli/pipeline-view.js +36 -0
- package/dist/crm/writes.d.ts +6 -4
- package/dist/crm/writes.js +17 -13
- package/dist/documents.d.ts +2 -0
- package/dist/documents.js +2 -0
- package/dist/domain/business.d.ts +79 -0
- package/dist/domain/business.js +42 -0
- package/dist/domain/finance.d.ts +2 -0
- package/dist/domain/finance.js +2 -2
- package/dist/domain/google-documents.d.ts +2 -0
- package/dist/domain/google-documents.js +3 -1
- package/dist/domain/money.d.ts +2 -0
- package/dist/domain/money.js +11 -3
- package/dist/domain/providers.d.ts +36 -1
- package/dist/domain/providers.js +69 -7
- package/dist/domain/record-fields.d.ts +42 -0
- package/dist/domain/record-fields.js +122 -0
- package/dist/domain/record-types.d.ts +489 -16
- package/dist/domain/record-types.js +374 -7
- package/dist/domain/records.d.ts +96 -5
- package/dist/domain/records.js +178 -32
- package/dist/domain/ref-summaries.js +5 -0
- package/dist/domain/references.d.ts +1 -1
- package/dist/domain/references.js +5 -0
- package/dist/domain/vcard.d.ts +25 -0
- package/dist/domain/vcard.js +267 -0
- package/dist/entities/deal.d.ts +14 -0
- package/dist/entities/deal.js +3 -0
- package/dist/entities/index.d.ts +12 -0
- package/dist/errors/reasons.js +63 -4
- package/dist/fetch/addresses.d.ts +5 -0
- package/dist/fetch/addresses.js +76 -0
- package/dist/fetch/page.d.ts +64 -0
- package/dist/fetch/page.js +256 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +5 -3
- package/dist/meetings/calendar-text.d.ts +1 -1
- package/dist/meetings/calendar-text.js +4 -0
- package/dist/meetings/event-store.d.ts +2 -2
- package/dist/search/account-list.d.ts +4 -0
- package/dist/search/account-list.js +19 -8
- package/dist/search/query.js +2 -2
- package/dist/services/events-search.js +2 -2
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/ingest.d.ts +56 -8
- package/dist/services/ingest.js +95 -61
- package/dist/services/messages-search.js +3 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/notes-search.js +1 -0
- package/dist/services/proposals/kinds/contracts.d.ts +4 -0
- package/dist/services/proposals/kinds/contracts.js +9 -0
- package/dist/services/proposals/kinds/finance.d.ts +4 -0
- package/dist/services/proposals/kinds/finance.js +14 -35
- package/dist/services/proposals/kinds/orders.js +7 -30
- package/dist/services/proposals/kinds/shared.d.ts +27 -1
- package/dist/services/proposals/kinds/shared.js +34 -0
- package/dist/services/proposals/kinds/source-review.d.ts +4 -0
- package/dist/services/proposals/kinds/source-review.js +45 -0
- package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
- package/dist/services/proposals/kinds/subscriptions.js +24 -0
- package/dist/services/proposals/kinds/transactions.d.ts +4 -0
- package/dist/services/proposals/kinds/transactions.js +10 -0
- package/dist/services/proposals/registry.js +9 -0
- package/dist/services/search-all-meetings.js +2 -2
- package/dist/services/search-all.js +4 -3
- package/dist/services/search-kind.js +3 -3
- package/dist/store/decisions.js +5 -1
- package/dist/store/index.d.ts +14 -3
- package/dist/store/index.js +3 -0
- package/dist/store/people.js +1 -1
- package/dist/store/source-review.d.ts +64 -0
- package/dist/store/source-review.js +7 -0
- package/dist/store/sqlite/accounts.d.ts +1 -1
- package/dist/store/sqlite/accounts.js +24 -1
- package/dist/store/sqlite/added-sources.d.ts +82 -0
- package/dist/store/sqlite/added-sources.js +237 -0
- package/dist/store/sqlite/business-contracts.d.ts +90 -0
- package/dist/store/sqlite/business-contracts.js +182 -0
- package/dist/store/sqlite/calendar-events.js +7 -3
- package/dist/store/sqlite/calendar-forget.js +3 -0
- package/dist/store/sqlite/calendar.d.ts +21 -1
- package/dist/store/sqlite/calendar.js +27 -7
- package/dist/store/sqlite/chat-rekey.js +7 -0
- package/dist/store/sqlite/chats.d.ts +3 -1
- package/dist/store/sqlite/chats.js +15 -1
- package/dist/store/sqlite/crm-rows.d.ts +44 -0
- package/dist/store/sqlite/crm-rows.js +195 -0
- package/dist/store/sqlite/crm.d.ts +2 -11
- package/dist/store/sqlite/crm.js +11 -166
- package/dist/store/sqlite/deals.d.ts +4 -8
- package/dist/store/sqlite/deals.js +5 -3
- package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
- package/dist/store/sqlite/emails.js +2 -0
- package/dist/store/sqlite/entity-types.d.ts +14 -9
- package/dist/store/sqlite/entity-types.js +4 -10
- package/dist/store/sqlite/evidence-signature.d.ts +114 -0
- package/dist/store/sqlite/evidence-signature.js +349 -0
- package/dist/store/sqlite/evidence-sources.d.ts +2 -1
- package/dist/store/sqlite/evidence-sources.js +7 -3
- package/dist/store/sqlite/facts.d.ts +7 -2
- package/dist/store/sqlite/facts.js +21 -5
- package/dist/store/sqlite/finance.d.ts +18 -105
- package/dist/store/sqlite/finance.js +100 -219
- package/dist/store/sqlite/knowledge.d.ts +8 -2
- package/dist/store/sqlite/knowledge.js +65 -71
- package/dist/store/sqlite/labelled.d.ts +3 -0
- package/dist/store/sqlite/labelled.js +11 -0
- package/dist/store/sqlite/link-kinds.d.ts +2 -0
- package/dist/store/sqlite/link-kinds.js +2 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/memories.d.ts +23 -9
- package/dist/store/sqlite/memories.js +41 -13
- package/dist/store/sqlite/messages.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +103 -0
- package/dist/store/sqlite/money-lines.d.ts +48 -0
- package/dist/store/sqlite/money-lines.js +76 -0
- package/dist/store/sqlite/money-transactions.d.ts +132 -0
- package/dist/store/sqlite/money-transactions.js +295 -0
- package/dist/store/sqlite/notes.d.ts +11 -2
- package/dist/store/sqlite/notes.js +20 -25
- package/dist/store/sqlite/orders.d.ts +36 -6
- package/dist/store/sqlite/orders.js +126 -46
- package/dist/store/sqlite/payment-facts.js +1 -1
- package/dist/store/sqlite/private-people.js +2 -0
- package/dist/store/sqlite/products.d.ts +78 -0
- package/dist/store/sqlite/products.js +131 -0
- package/dist/store/sqlite/project-transfer/records.js +26 -1
- package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
- package/dist/store/sqlite/proposed-actions.d.ts +1 -1
- package/dist/store/sqlite/proposed-actions.js +24 -7
- package/dist/store/sqlite/providers.d.ts +0 -4
- package/dist/store/sqlite/providers.js +20 -2
- package/dist/store/sqlite/record-matching.d.ts +80 -0
- package/dist/store/sqlite/record-matching.js +264 -0
- package/dist/store/sqlite/record-projection.d.ts +89 -0
- package/dist/store/sqlite/record-projection.js +50 -0
- package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
- package/dist/store/sqlite/record-projectors-direct.js +125 -0
- package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
- package/dist/store/sqlite/record-projectors-money.js +214 -0
- package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
- package/dist/store/sqlite/record-projectors-phone.js +212 -0
- package/dist/store/sqlite/record-projectors.d.ts +3 -44
- package/dist/store/sqlite/record-projectors.js +7 -67
- package/dist/store/sqlite/record-relations.d.ts +24 -0
- package/dist/store/sqlite/record-relations.js +92 -0
- package/dist/store/sqlite/record-remap.d.ts +12 -0
- package/dist/store/sqlite/record-remap.js +92 -0
- package/dist/store/sqlite/record-run.d.ts +71 -0
- package/dist/store/sqlite/record-run.js +179 -0
- package/dist/store/sqlite/record-settling.d.ts +9 -0
- package/dist/store/sqlite/record-settling.js +74 -0
- package/dist/store/sqlite/record-stamps.d.ts +13 -0
- package/dist/store/sqlite/record-stamps.js +30 -0
- package/dist/store/sqlite/record-writes.d.ts +43 -0
- package/dist/store/sqlite/record-writes.js +307 -0
- package/dist/store/sqlite/records.d.ts +52 -42
- package/dist/store/sqlite/records.js +123 -353
- package/dist/store/sqlite/ref-summaries.d.ts +6 -5
- package/dist/store/sqlite/ref-summaries.js +60 -8
- package/dist/store/sqlite/refunds.d.ts +31 -0
- package/dist/store/sqlite/refunds.js +112 -0
- package/dist/store/sqlite/reviewed.d.ts +109 -0
- package/dist/store/sqlite/reviewed.js +173 -0
- package/dist/store/sqlite/schema.d.ts +2840 -83
- package/dist/store/sqlite/schema.js +256 -1
- package/dist/store/sqlite/source-review-marks.d.ts +54 -0
- package/dist/store/sqlite/source-review-marks.js +143 -0
- package/dist/store/sqlite/source-review.d.ts +54 -0
- package/dist/store/sqlite/source-review.js +221 -0
- package/dist/store/sqlite/stage-amounts.d.ts +14 -0
- package/dist/store/sqlite/stage-amounts.js +23 -0
- package/dist/store/sqlite/subscriptions.d.ts +135 -0
- package/dist/store/sqlite/subscriptions.js +294 -0
- package/dist/store/sqlite/text-input.d.ts +3 -0
- package/dist/store/sqlite/text-input.js +13 -0
- package/dist/store/sqlite/things.js +2 -9
- package/dist/store/sqlite/transaction.d.ts +15 -0
- package/dist/store/sqlite/transaction.js +57 -0
- package/dist/store/sqlite/wallets.d.ts +88 -0
- package/dist/store/sqlite/wallets.js +143 -0
- package/dist/store/store-errors.d.ts +1 -0
- package/dist/store/store-errors.js +45 -0
- package/dist/store/store.d.ts +16 -1
- package/dist/store/store.js +30 -6
- package/package.json +5 -2
- package/schemas/examples/records-business.jsonl +11 -0
- package/schemas/records-envelope.v1.schema.json +1160 -5
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
import { type EventStore } from "../../meetings/index.js";
|
|
1
|
+
import { type CalendarInput, type EntryInput, type EventStore, type StoredCalendar, type StoredEntry } from "../../meetings/index.js";
|
|
2
2
|
import type { StoreContext } from "./open.js";
|
|
3
|
+
type Row = Record<string, unknown>;
|
|
4
|
+
/** The entry writes behind the calendar store, run inside the caller's transaction: the records import shares them. */
|
|
5
|
+
export declare const calendarWritesOver: (context: StoreContext) => {
|
|
6
|
+
entryRow: (id: number) => Row;
|
|
7
|
+
saveCalendar: (accountId: number, one: CalendarInput, now: number) => StoredCalendar;
|
|
8
|
+
calendarRow: (id: number) => Record<string, unknown>;
|
|
9
|
+
setEntity: (entry: StoredEntry, to: number, method: string, author: string, now: number) => void;
|
|
10
|
+
newEntity: (entry: StoredEntry, now: number) => number;
|
|
11
|
+
refreshEvent: (eventId: number, now: number) => void;
|
|
12
|
+
refreshSeries: (seriesId: number, now: number) => void;
|
|
13
|
+
refreshAround: (entryIds: number[], now: number) => void;
|
|
14
|
+
saveAll: (calendarId: number, entries: EntryInput[], now: number) => StoredEntry[];
|
|
15
|
+
removeAll: (calendarId: number, externalIds: string[], now: number) => number;
|
|
16
|
+
putCursor: (calendarId: number, value: string | null, now: number) => void;
|
|
17
|
+
slotRows: (calendarId: number, series: string, window: {
|
|
18
|
+
from: number;
|
|
19
|
+
to: number;
|
|
20
|
+
}) => Record<string, unknown>[];
|
|
21
|
+
};
|
|
3
22
|
export declare const eventStoreOver: (context: StoreContext) => EventStore;
|
|
23
|
+
export {};
|
|
@@ -136,7 +136,8 @@ const spanOf = (entry) => {
|
|
|
136
136
|
const start = entry.startsAt ?? 0;
|
|
137
137
|
return { start, end: Math.max(entry.endsAt ?? start, start + 1) };
|
|
138
138
|
};
|
|
139
|
-
|
|
139
|
+
/** The entry writes behind the calendar store, run inside the caller's transaction: the records import shares them. */
|
|
140
|
+
export const calendarWritesOver = (context) => {
|
|
140
141
|
const { database } = context;
|
|
141
142
|
const entryRow = (id) => database.prepare("SELECT * FROM calendar_entries WHERE id = ?").get(id);
|
|
142
143
|
const calendarRow = (id) => {
|
|
@@ -505,16 +506,35 @@ export const eventStoreOver = (context) => {
|
|
|
505
506
|
.prepare(`SELECT * FROM calendar_entries WHERE calendar_id = ? AND kind = 'occurrence' AND series_external_id = ?
|
|
506
507
|
AND original_starts_at >= ? AND original_starts_at < ? AND deleted_at IS NULL ORDER BY original_starts_at`)
|
|
507
508
|
.all(calendarId, series, window.from, window.to);
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
509
|
+
/** One calendar as a provider lists it; one the owner forgot comes back, as a list naming it again does. */
|
|
510
|
+
const saveCalendar = (accountId, one, now) => calendarOf(database
|
|
511
|
+
.prepare(`INSERT INTO calendars (account_id, external_id, title, timezone, access_role, primary_calendar, synced, seen_at,
|
|
511
512
|
created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
512
513
|
ON CONFLICT (account_id, external_id) DO UPDATE SET title = excluded.title, timezone = excluded.timezone,
|
|
513
514
|
access_role = excluded.access_role, primary_calendar = excluded.primary_calendar, seen_at = excluded.seen_at,
|
|
514
515
|
deleted_at = NULL, updated_at = excluded.updated_at
|
|
515
|
-
RETURNING *`)
|
|
516
|
-
|
|
517
|
-
|
|
516
|
+
RETURNING *`)
|
|
517
|
+
.get(accountId, one.externalId, one.title, one.timezone, one.accessRole, flag(one.primary), flag(one.syncByDefault), now, now, now));
|
|
518
|
+
return {
|
|
519
|
+
entryRow,
|
|
520
|
+
saveCalendar,
|
|
521
|
+
calendarRow,
|
|
522
|
+
setEntity,
|
|
523
|
+
newEntity,
|
|
524
|
+
refreshEvent,
|
|
525
|
+
refreshSeries,
|
|
526
|
+
refreshAround,
|
|
527
|
+
saveAll,
|
|
528
|
+
removeAll,
|
|
529
|
+
putCursor,
|
|
530
|
+
slotRows,
|
|
531
|
+
};
|
|
532
|
+
};
|
|
533
|
+
export const eventStoreOver = (context) => {
|
|
534
|
+
const { database } = context;
|
|
535
|
+
const { entryRow, calendarRow, setEntity, newEntity, refreshEvent, refreshSeries, refreshAround, saveAll, removeAll, putCursor, slotRows, saveCalendar, } = calendarWritesOver(context);
|
|
536
|
+
return {
|
|
537
|
+
saveCalendars: async (accountId, calendars, now) => write(database, () => calendars.map((one) => saveCalendar(accountId, one, now))),
|
|
518
538
|
calendars: async (accountId) => database
|
|
519
539
|
.prepare("SELECT * FROM calendars WHERE account_id = ? ORDER BY primary_calendar DESC, title, id")
|
|
520
540
|
.all(accountId)
|
|
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
|
|
|
2
2
|
import { formatLocator } from "../../domain/locator.js";
|
|
3
3
|
import { purgeChats, revisedBy, stricterPrivacy } from "./chats.js";
|
|
4
4
|
import { pointerPairs } from "./entity-types.js";
|
|
5
|
+
import { evidenceSignature, resignEvidence, storedEvidenceMetadata } from "./evidence-signature.js";
|
|
5
6
|
import { tombstone, writeDerivedReactions } from "./messages.js";
|
|
6
7
|
import { targetKey } from "./notes.js";
|
|
7
8
|
import { write } from "./transaction.js";
|
|
@@ -20,11 +21,17 @@ const pointerMover = (context, type) => {
|
|
|
20
21
|
context.database.prepare(`DELETE FROM ${table} ${where}`),
|
|
21
22
|
];
|
|
22
23
|
});
|
|
24
|
+
const cited = context.database.prepare("SELECT id, metadata FROM links WHERE kind = 'evidence' AND to_type = ? AND to_id = ?");
|
|
23
25
|
return (from, to) => {
|
|
26
|
+
const evidence = cited.all(type, from);
|
|
24
27
|
for (const [move, drop] of statements) {
|
|
25
28
|
move.run(to, from);
|
|
26
29
|
drop.run(from);
|
|
27
30
|
}
|
|
31
|
+
// The kept row is the same source under another id; signed as it is, the next check sees no change.
|
|
32
|
+
const signature = evidenceSignature(context.database, { type, id: to });
|
|
33
|
+
for (const link of evidence)
|
|
34
|
+
resignEvidence(context.database, Number(link.id), signature, context.now(), storedEvidenceMetadata(link.metadata));
|
|
28
35
|
};
|
|
29
36
|
};
|
|
30
37
|
const renameText = (context, key, accountKey, from, to) => {
|
|
@@ -37,6 +37,8 @@ export declare const stricterPrivacy: ({ database }: StoreContext, accountKey: n
|
|
|
37
37
|
*/
|
|
38
38
|
export declare const answeredChatPk: (context: StoreContext, accountKey: number, chatId: Id, typed: Id) => number;
|
|
39
39
|
export declare const upsertChat: (context: StoreContext, accountKey: number, chat: ChatUpdate) => void;
|
|
40
|
+
/** Moves a chat's newest-message time forward only: messages imported out of order never move it back. */
|
|
41
|
+
export declare const raiseLastMessageAt: ({ orm }: StoreContext, chatKey: number, at: number) => void;
|
|
40
42
|
/** Replaces who is in the chat, whole. */
|
|
41
43
|
export declare const writeMembers: (context: StoreContext, key: AccountKey, accountKey: number, chatId: Id, memberIds: Id[]) => void;
|
|
42
44
|
export declare const members: ({ orm }: StoreContext, chatKey: number) => Member[];
|
|
@@ -60,7 +62,7 @@ export declare const leftChats: ({ orm }: StoreContext, accountKey: number) => {
|
|
|
60
62
|
messages: number;
|
|
61
63
|
};
|
|
62
64
|
/** These chats and everything under them, children before parents: the foreign keys are enforced. */
|
|
63
|
-
export declare const purgeChats: ({ orm, database }: StoreContext, pks: number[]) => void;
|
|
65
|
+
export declare const purgeChats: ({ orm, database, now }: StoreContext, pks: number[]) => void;
|
|
64
66
|
export declare const chatsWith: ({ orm, now }: StoreContext, accountKey: number, key: AccountKey, memberId: Id) => Chat[];
|
|
65
67
|
/**
|
|
66
68
|
* How the store answers a chat list's query. `title:` goes through the trigram index, so it matches part of a
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { CliError } from "@wirecat/cli-base";
|
|
2
2
|
import { and, eq, inArray, or, sql } from "./drizzle/core.js";
|
|
3
|
+
import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
|
|
3
4
|
import { folded } from "./folded.js";
|
|
4
5
|
import { withoutHistory } from "./history-skips.js";
|
|
5
6
|
import { identityPk } from "./identities.js";
|
|
@@ -174,6 +175,14 @@ export const upsertChat = (context, accountKey, chat) => {
|
|
|
174
175
|
})
|
|
175
176
|
.run();
|
|
176
177
|
};
|
|
178
|
+
/** Moves a chat's newest-message time forward only: messages imported out of order never move it back. */
|
|
179
|
+
export const raiseLastMessageAt = ({ orm }, chatKey, at) => {
|
|
180
|
+
orm
|
|
181
|
+
.update(chats)
|
|
182
|
+
.set({ lastMessageAt: sql `max(coalesce(${chats.lastMessageAt}, 0), ${at})` })
|
|
183
|
+
.where(eq(chats.id, chatKey))
|
|
184
|
+
.run();
|
|
185
|
+
};
|
|
177
186
|
const bit = (value) => (value === undefined ? null : value ? 1 : 0);
|
|
178
187
|
/**
|
|
179
188
|
* The count is taken as of the chat's newest message where the update names it, else as of now: a message the store
|
|
@@ -277,9 +286,13 @@ export const leftChats = ({ orm }, accountKey) => {
|
|
|
277
286
|
return { pks, chats: left, messages: left.reduce((sum, chat) => sum + chat.messages, 0) };
|
|
278
287
|
};
|
|
279
288
|
/** These chats and everything under them, children before parents: the foreign keys are enforced. */
|
|
280
|
-
export const purgeChats = ({ orm, database }, pks) => {
|
|
289
|
+
export const purgeChats = ({ orm, database, now }, pks) => {
|
|
281
290
|
if (pks.length === 0)
|
|
282
291
|
return;
|
|
292
|
+
const at = now();
|
|
293
|
+
const chatIds = { sql: "SELECT value FROM json_each(?)", params: [JSON.stringify(pks)] };
|
|
294
|
+
forgetEvidenceTo(database, "message", { ...chatIds, sql: `SELECT id FROM messages WHERE chat_id IN (${chatIds.sql})` }, at);
|
|
295
|
+
forgetEvidenceTo(database, "chat", chatIds, at);
|
|
283
296
|
const messagesOf = orm.select({ pk: messages.id }).from(messages).where(inArray(messages.chatId, pks));
|
|
284
297
|
const chatPks = sql `(SELECT value FROM json_each(${JSON.stringify(pks)}))`;
|
|
285
298
|
const released = orm
|
|
@@ -319,6 +332,7 @@ export const purgeChats = ({ orm, database }, pks) => {
|
|
|
319
332
|
orm.delete(messageRevisions).where(inArray(messageRevisions.messageId, messagesOf)).run();
|
|
320
333
|
orm.delete(messages).where(inArray(messages.chatId, pks)).run();
|
|
321
334
|
orm.delete(chats).where(inArray(chats.id, pks)).run();
|
|
335
|
+
forgetDanglingEvidence(database, at);
|
|
322
336
|
dropUnusedVectors(database, released.map(({ hash }) => hash));
|
|
323
337
|
};
|
|
324
338
|
export const chatsWith = ({ orm, now }, accountKey, key, memberId) => {
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { CrmItem, CrmPipeline } from "../../domain/crm.js";
|
|
2
|
+
import { type DealKind } from "../../domain/deals.js";
|
|
3
|
+
import type { AccountKey } from "../types.js";
|
|
4
|
+
import type { StoreContext } from "./open.js";
|
|
5
|
+
/** What the store could not keep, and why: an item whose stage is not stored or whose field it refuses, or a pipeline. */
|
|
6
|
+
export interface CrmSkipped {
|
|
7
|
+
externalId: string;
|
|
8
|
+
reason: "crm.stage-unknown" | "crm.item-invalid";
|
|
9
|
+
message: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const TABLES: {
|
|
12
|
+
readonly deal: "deals";
|
|
13
|
+
readonly lead: "leads";
|
|
14
|
+
};
|
|
15
|
+
/** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
|
|
16
|
+
export declare const SOURCE = "crm";
|
|
17
|
+
/**
|
|
18
|
+
* A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
|
|
19
|
+
* `contact:` references percent-encode it, so the `/` stays one part.
|
|
20
|
+
*/
|
|
21
|
+
export declare const crmIdentityId: (key: AccountKey, externalId: string, type?: "contact" | "user") => string;
|
|
22
|
+
/** What every contact identity of the account starts with. */
|
|
23
|
+
export declare const crmAccountPrefix: (key: AccountKey) => string;
|
|
24
|
+
export declare const day: (value: unknown, what: string) => string | null;
|
|
25
|
+
export declare const epoch: (value: unknown, fallback: number) => number;
|
|
26
|
+
export declare const textOf: (value: unknown, most: number) => string | null;
|
|
27
|
+
/** What another writer than CRM sync resolved for an item: given ids win over the CRM's own lookups by external id. */
|
|
28
|
+
export interface ItemWriter {
|
|
29
|
+
organization?: number | null;
|
|
30
|
+
deal?: number | null;
|
|
31
|
+
project?: number | null;
|
|
32
|
+
author?: {
|
|
33
|
+
type: string;
|
|
34
|
+
id: number;
|
|
35
|
+
};
|
|
36
|
+
source?: string;
|
|
37
|
+
}
|
|
38
|
+
/** The single-row writes CRM sync and the records envelope share, so both land on one `(account, external id)` row. */
|
|
39
|
+
export declare const crmRowsOver: (context: StoreContext) => {
|
|
40
|
+
savePipeline: (accountId: number, kind: DealKind, pipeline: CrmPipeline, at: number) => number;
|
|
41
|
+
saveItemRow: (key: AccountKey, accountId: number, kind: DealKind, item: CrmItem, at: number, writer?: ItemWriter) => CrmSkipped | {
|
|
42
|
+
id: number;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { STAGE_OUTCOMES } from "../../domain/deals.js";
|
|
3
|
+
import { currencyOf, minorUnits } from "../../domain/money.js";
|
|
4
|
+
import { fold } from "../normalize.js";
|
|
5
|
+
import { authorActor } from "./memories.js";
|
|
6
|
+
export const TABLES = { deal: "deals", lead: "leads" };
|
|
7
|
+
/** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
|
|
8
|
+
export const SOURCE = "crm";
|
|
9
|
+
/**
|
|
10
|
+
* A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
|
|
11
|
+
* `contact:` references percent-encode it, so the `/` stays one part.
|
|
12
|
+
*/
|
|
13
|
+
export const crmIdentityId = (key, externalId, type = "contact") => `${idPart(key.account)}/${type}/${idPart(externalId)}`;
|
|
14
|
+
/**
|
|
15
|
+
* A `/` inside an account or an id would let `a` + `b/contact/c` and `a/contact/b` + `c` name one contact, so it is
|
|
16
|
+
* escaped, with the `%` that escapes it; an id with neither, every CRM's so far, is written as before.
|
|
17
|
+
*/
|
|
18
|
+
const idPart = (value) => value.replaceAll("%", "%25").replaceAll("/", "%2F");
|
|
19
|
+
/** What every contact identity of the account starts with. */
|
|
20
|
+
export const crmAccountPrefix = (key) => `${idPart(key.account)}/`;
|
|
21
|
+
export const day = (value, what) => {
|
|
22
|
+
if (value === undefined || value === null || value === "")
|
|
23
|
+
return null;
|
|
24
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value) || Number.isNaN(Date.parse(value)))
|
|
25
|
+
throw new CliError("validation_error", `${what} is YYYY-MM-DD, not ${JSON.stringify(value)}`);
|
|
26
|
+
return value;
|
|
27
|
+
};
|
|
28
|
+
export const epoch = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback;
|
|
29
|
+
export const textOf = (value, most) => {
|
|
30
|
+
if (typeof value !== "string")
|
|
31
|
+
return null;
|
|
32
|
+
const kept = value.trim().slice(0, most);
|
|
33
|
+
return kept || null;
|
|
34
|
+
};
|
|
35
|
+
/** The single-row writes CRM sync and the records envelope share, so both land on one `(account, external id)` row. */
|
|
36
|
+
export const crmRowsOver = (context) => {
|
|
37
|
+
const { database } = context;
|
|
38
|
+
const author = (key) => authorActor(context, { bot: key.provider, kind: "rule" }).actor;
|
|
39
|
+
const pipelineOf = (accountId, kind, externalId) => database
|
|
40
|
+
.prepare("SELECT * FROM pipelines WHERE account_id = ? AND kind = ? AND external_id = ?")
|
|
41
|
+
.get(accountId, kind, externalId);
|
|
42
|
+
/** One pipeline and its stages, by the source's ids; the rest of the account's pipelines stay as they are. */
|
|
43
|
+
const savePipeline = (accountId, kind, pipeline, at) => {
|
|
44
|
+
const name = textOf(pipeline.name, 80) ?? pipeline.externalId;
|
|
45
|
+
const held = pipelineOf(accountId, kind, pipeline.externalId);
|
|
46
|
+
const id = held
|
|
47
|
+
? Number(held.id)
|
|
48
|
+
: Number(database
|
|
49
|
+
.prepare("INSERT INTO pipelines (account_id, external_id, kind, name, name_folded, created_at, updated_at) " +
|
|
50
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id")
|
|
51
|
+
.get(accountId, pipeline.externalId, kind, name, fold(name), at, at)?.id);
|
|
52
|
+
if (held && (held.name !== name || held.deleted_at != null))
|
|
53
|
+
database
|
|
54
|
+
.prepare("UPDATE pipelines SET name = ?, name_folded = ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
|
|
55
|
+
.run(name, fold(name), at, id);
|
|
56
|
+
saveStages(id, pipeline, at);
|
|
57
|
+
saveStages(id, pipeline, at);
|
|
58
|
+
return id;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Stage names are unique in a pipeline, but a CRM may swap two, or give two stages one name: listed stages first
|
|
62
|
+
* take a name no stage has, then their own, and a name used twice keeps the stage's id beside it.
|
|
63
|
+
*/
|
|
64
|
+
const saveStages = (pipelineId, pipeline, at) => {
|
|
65
|
+
const ordered = [...pipeline.stages].sort((a, b) => a.position - b.position);
|
|
66
|
+
const counts = new Map();
|
|
67
|
+
for (const stage of ordered)
|
|
68
|
+
counts.set(fold(stage.name), (counts.get(fold(stage.name)) ?? 0) + 1);
|
|
69
|
+
const wanted = ordered.map((stage, index) => {
|
|
70
|
+
const name = textOf(stage.name, 80) ?? stage.externalId;
|
|
71
|
+
const folded = (counts.get(fold(stage.name)) ?? 0) > 1 ? `${fold(name)} (${stage.externalId})` : fold(name);
|
|
72
|
+
if (!STAGE_OUTCOMES.includes(stage.outcome))
|
|
73
|
+
throw new CliError("invalid_response", `stage ${stage.externalId} has no known outcome: ${stage.outcome}`);
|
|
74
|
+
return { ...stage, name, folded, position: index + 1 };
|
|
75
|
+
});
|
|
76
|
+
const held = database.prepare("SELECT * FROM pipeline_stages WHERE pipeline_id = ?").all(pipelineId);
|
|
77
|
+
const listed = new Set(wanted.map(({ externalId }) => externalId));
|
|
78
|
+
const taken = new Set(wanted.map(({ folded }) => folded));
|
|
79
|
+
const rename = database.prepare("UPDATE pipeline_stages SET name_folded = ? WHERE id = ?");
|
|
80
|
+
const gone = database.prepare("UPDATE pipeline_stages SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL");
|
|
81
|
+
for (const row of held) {
|
|
82
|
+
const kept = row.external_id != null && listed.has(String(row.external_id));
|
|
83
|
+
if (kept)
|
|
84
|
+
rename.run(`\u0000${row.id}`, Number(row.id));
|
|
85
|
+
else if (taken.has(String(row.name_folded)))
|
|
86
|
+
rename.run(`${row.name_folded} (${row.external_id ?? row.id})`, Number(row.id));
|
|
87
|
+
if (!kept)
|
|
88
|
+
gone.run(at, Number(row.id));
|
|
89
|
+
}
|
|
90
|
+
const byId = new Map(held.map((row) => [String(row.external_id), row]));
|
|
91
|
+
for (const stage of wanted) {
|
|
92
|
+
const row = byId.get(stage.externalId);
|
|
93
|
+
if (row)
|
|
94
|
+
database
|
|
95
|
+
.prepare("UPDATE pipeline_stages SET name = ?, name_folded = ?, position = ?, outcome = ?, updated_at = ?, " +
|
|
96
|
+
"deleted_at = NULL WHERE id = ?")
|
|
97
|
+
.run(stage.name, stage.folded, stage.position, stage.outcome, at, Number(row.id));
|
|
98
|
+
else
|
|
99
|
+
database
|
|
100
|
+
.prepare("INSERT INTO pipeline_stages (pipeline_id, name, name_folded, position, outcome, external_id, created_at, " +
|
|
101
|
+
"updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
|
102
|
+
.run(pipelineId, stage.name, stage.folded, stage.position, stage.outcome, stage.externalId, at, at);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const organizationIdOf = (accountId, externalId) => {
|
|
106
|
+
const row = database
|
|
107
|
+
.prepare("SELECT entity_id FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ? " +
|
|
108
|
+
"AND entity_type = 'organization'")
|
|
109
|
+
.get(accountId, externalId);
|
|
110
|
+
return row?.entity_id == null ? null : Number(row.entity_id);
|
|
111
|
+
};
|
|
112
|
+
/** The deal or lead row of `(account, external id)`; `writer` gives what another writer than CRM sync resolved. */
|
|
113
|
+
const saveItemRow = (key, accountId, kind, item, at, writer = {}) => {
|
|
114
|
+
const pipeline = pipelineOf(accountId, kind, item.pipeline);
|
|
115
|
+
const stage = pipeline &&
|
|
116
|
+
database
|
|
117
|
+
.prepare("SELECT id, outcome FROM pipeline_stages WHERE pipeline_id = ? AND external_id = ?")
|
|
118
|
+
.get(Number(pipeline.id), item.stage);
|
|
119
|
+
if (!pipeline || !stage)
|
|
120
|
+
return {
|
|
121
|
+
externalId: item.externalId,
|
|
122
|
+
reason: "crm.stage-unknown",
|
|
123
|
+
message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
|
|
124
|
+
};
|
|
125
|
+
const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
|
|
126
|
+
const given = item.amount != null && item.currency != null;
|
|
127
|
+
const currency = given ? currencyOf(item.currency) : null;
|
|
128
|
+
const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
|
|
129
|
+
if (amount !== null && amount < 0)
|
|
130
|
+
throw new CliError("validation_error", "an amount is 0 or more");
|
|
131
|
+
if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
|
|
132
|
+
throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
|
|
133
|
+
const status = item.status ?? String(stage.outcome);
|
|
134
|
+
const closed = status === "open"
|
|
135
|
+
? null
|
|
136
|
+
: (day(item.closedDate, "a closed day") ?? new Date(epoch(item.updatedAt, at)).toISOString().slice(0, 10));
|
|
137
|
+
const deal = writer.deal !== undefined
|
|
138
|
+
? writer.deal === null
|
|
139
|
+
? undefined
|
|
140
|
+
: { id: writer.deal }
|
|
141
|
+
: kind === "lead" && item.deal
|
|
142
|
+
? database.prepare("SELECT id FROM deals WHERE account_id = ? AND external_id = ?").get(accountId, item.deal)
|
|
143
|
+
: undefined;
|
|
144
|
+
const metadata = {
|
|
145
|
+
...(item.metadata ?? {}),
|
|
146
|
+
...(item.url ? { url: item.url } : {}),
|
|
147
|
+
...(item.assignee ? { assignee: crmIdentityId(key, item.assignee, "user") } : {}),
|
|
148
|
+
...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
|
|
149
|
+
};
|
|
150
|
+
const values = {
|
|
151
|
+
title,
|
|
152
|
+
organization: writer.organization !== undefined
|
|
153
|
+
? writer.organization
|
|
154
|
+
: item.organization
|
|
155
|
+
? organizationIdOf(accountId, item.organization)
|
|
156
|
+
: null,
|
|
157
|
+
stage: Number(stage.id),
|
|
158
|
+
status,
|
|
159
|
+
currency,
|
|
160
|
+
amount,
|
|
161
|
+
close: day(item.closeDate, "an expected close day"),
|
|
162
|
+
closed,
|
|
163
|
+
metadata: Object.keys(metadata).length ? JSON.stringify(metadata) : null,
|
|
164
|
+
created: epoch(item.createdAt, at),
|
|
165
|
+
updated: epoch(item.updatedAt, at),
|
|
166
|
+
};
|
|
167
|
+
const table = TABLES[kind];
|
|
168
|
+
const held = database
|
|
169
|
+
.prepare(`SELECT id FROM ${table} WHERE account_id = ? AND external_id = ?`)
|
|
170
|
+
.get(accountId, item.externalId);
|
|
171
|
+
let id;
|
|
172
|
+
if (held) {
|
|
173
|
+
id = Number(held.id);
|
|
174
|
+
database
|
|
175
|
+
.prepare(`UPDATE ${table} SET title = ?, organization_id = ?, stage_id = ?, status = ?, currency = ?, amount = ?, ` +
|
|
176
|
+
"close_date = ?, closed_date = ?, metadata = ?, updated_at = ?, deleted_at = NULL" +
|
|
177
|
+
(kind === "lead" ? ", deal_id = coalesce(?, deal_id)" : "") +
|
|
178
|
+
" WHERE id = ?")
|
|
179
|
+
.run(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, values.metadata, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []), id);
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
const actor = writer.author ?? author(key);
|
|
183
|
+
id = Number(database
|
|
184
|
+
.prepare(`INSERT INTO ${table} (title, organization_id, stage_id, status, currency, amount, close_date, closed_date, ` +
|
|
185
|
+
`account_id, external_id, author_type, author_id, source, metadata, created_at, updated_at` +
|
|
186
|
+
(kind === "lead" ? ", deal_id" : "") +
|
|
187
|
+
`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?${kind === "lead" ? ", ?" : ""}) RETURNING id`)
|
|
188
|
+
.get(values.title, values.organization, values.stage, values.status, values.currency, values.amount, values.close, values.closed, accountId, item.externalId, actor.type, actor.id, writer.source ?? SOURCE, values.metadata, values.created, values.updated, ...(kind === "lead" ? [deal ? Number(deal.id) : null] : []))?.id);
|
|
189
|
+
}
|
|
190
|
+
if (writer.project !== undefined)
|
|
191
|
+
database.prepare(`UPDATE ${table} SET project_id = ? WHERE id = ?`).run(writer.project, id);
|
|
192
|
+
return { id };
|
|
193
|
+
};
|
|
194
|
+
return { savePipeline, saveItemRow };
|
|
195
|
+
};
|
|
@@ -2,13 +2,8 @@ import { type CrmDepartment, type CrmField, type CrmItem, type CrmKind, type Crm
|
|
|
2
2
|
import { type DealKind } from "../../domain/deals.js";
|
|
3
3
|
import type { AccountPeople } from "../people.js";
|
|
4
4
|
import type { AccountKey } from "../types.js";
|
|
5
|
+
import { type CrmSkipped } from "./crm-rows.js";
|
|
5
6
|
import type { StoreContext } from "./open.js";
|
|
6
|
-
/** What the store could not keep, and why: an item whose stage is not stored or whose field it refuses, or a pipeline. */
|
|
7
|
-
export interface CrmSkipped {
|
|
8
|
-
externalId: string;
|
|
9
|
-
reason: "crm.stage-unknown" | "crm.item-invalid";
|
|
10
|
-
message: string;
|
|
11
|
-
}
|
|
12
7
|
/**
|
|
13
8
|
* A relationship the CRM reported that the store did not write: a contact, company or user not synced yet (tried
|
|
14
9
|
* again on the next sync), ends the registry refuses, an own company it does not know yet, or an email two people
|
|
@@ -86,9 +81,5 @@ export interface CrmCopies {
|
|
|
86
81
|
/** The stored copy's `deal:<id>` or `lead:<id>`, deleted or not; `null` when the store holds none. */
|
|
87
82
|
refOf(key: AccountKey, kind: DealKind, externalId: string): Promise<string | null>;
|
|
88
83
|
}
|
|
89
|
-
|
|
90
|
-
* A contact's identity id: identities are unique per provider, and two portals of one CRM both have a contact 5.
|
|
91
|
-
* `contact:` references percent-encode it, so the `/` stays one part.
|
|
92
|
-
*/
|
|
93
|
-
export declare const crmIdentityId: (key: AccountKey, externalId: string, type?: "contact" | "user") => string;
|
|
84
|
+
export { type CrmSkipped, crmIdentityId, crmRowsOver, type ItemWriter } from "./crm-rows.js";
|
|
94
85
|
export declare const crmCopiesOver: (context: StoreContext, people: AccountPeople) => CrmCopies;
|