@wirecat/cli-core 0.675.0 → 0.676.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 (58) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/index.d.ts +1 -1
  6. package/dist/cli/list-query.d.ts +3 -2
  7. package/dist/cli/list-query.js +5 -2
  8. package/dist/cli/setup-command.js +9 -3
  9. package/dist/crm/cli/index.d.ts +7 -1
  10. package/dist/crm/cli/index.js +104 -20
  11. package/dist/crm/cli/pipeline-view.js +15 -1
  12. package/dist/crm/cli/records.js +11 -3
  13. package/dist/crm/cli/search-all.d.ts +5 -2
  14. package/dist/crm/cli/search-all.js +15 -3
  15. package/dist/crm/source.d.ts +3 -2
  16. package/dist/crm/stage-tasks.js +1 -1
  17. package/dist/crm/sync.js +13 -11
  18. package/dist/crm/testing/write-contract.js +5 -1
  19. package/dist/crm/viewer.d.ts +28 -0
  20. package/dist/crm/viewer.js +63 -0
  21. package/dist/crm/writer.d.ts +3 -0
  22. package/dist/crm/writes.d.ts +7 -2
  23. package/dist/crm/writes.js +24 -14
  24. package/dist/domain/crm.d.ts +9 -9
  25. package/dist/domain/moment.d.ts +2 -0
  26. package/dist/domain/moment.js +2 -0
  27. package/dist/entities/business-context.js +1 -1
  28. package/dist/entities/deal.d.ts +86 -39
  29. package/dist/entities/deal.js +45 -4
  30. package/dist/entities/index.d.ts +20 -32
  31. package/dist/errors/reasons.js +1 -0
  32. package/dist/meetings/mcp/index.d.ts +15 -15
  33. package/dist/services/search-all.d.ts +3 -1
  34. package/dist/services/search-all.js +1 -0
  35. package/dist/setup/define.d.ts +17 -2
  36. package/dist/store/exports.d.ts +1 -0
  37. package/dist/store/exports.js +1 -0
  38. package/dist/store/sqlite/copy-viewer.d.ts +16 -0
  39. package/dist/store/sqlite/copy-viewer.js +11 -0
  40. package/dist/store/sqlite/crm-activities.d.ts +7 -1
  41. package/dist/store/sqlite/crm-activities.js +32 -5
  42. package/dist/store/sqlite/crm-contacts.d.ts +5 -2
  43. package/dist/store/sqlite/crm-contacts.js +30 -14
  44. package/dist/store/sqlite/crm-rows.d.ts +7 -0
  45. package/dist/store/sqlite/crm-rows.js +37 -5
  46. package/dist/store/sqlite/crm-settings.d.ts +2 -1
  47. package/dist/store/sqlite/crm-settings.js +3 -2
  48. package/dist/store/sqlite/crm-stage-entries.d.ts +24 -4
  49. package/dist/store/sqlite/crm-stage-entries.js +77 -18
  50. package/dist/store/sqlite/crm.d.ts +14 -4
  51. package/dist/store/sqlite/crm.js +59 -7
  52. package/dist/store/sqlite/deals.d.ts +47 -29
  53. package/dist/store/sqlite/deals.js +64 -76
  54. package/dist/store/sqlite/pipeline-period.d.ts +85 -0
  55. package/dist/store/sqlite/pipeline-period.js +199 -0
  56. package/dist/store/sqlite/stage-amounts.d.ts +6 -2
  57. package/dist/store/sqlite/stage-amounts.js +8 -5
  58. package/package.json +3 -3
@@ -4,9 +4,9 @@ import { DEAL_ROLES } from "../../domain/deals.js";
4
4
  import { recordFingerprint } from "../../domain/records.js";
5
5
  import { accountPk, findAccountPk } from "./accounts.js";
6
6
  import { suggestBaseStages } from "./base-suggest.js";
7
- import { crmActivitiesOver } from "./crm-activities.js";
7
+ import { crmActivitiesOver, forgetActivitiesOn, } from "./crm-activities.js";
8
8
  import { removeCrmContacts } from "./crm-contacts.js";
9
- import { crmAccountPrefix, crmIdentityId, crmRowsOver, SOURCE, TABLES, textOf } from "./crm-rows.js";
9
+ import { crmAccountPrefix, crmIdentityId, crmRowsOver, PERSON_RECORD, SOURCE, TABLES, textOf, } from "./crm-rows.js";
10
10
  import { crmActivitiesOn, crmCompanyTypes, crmOwnUser, crmScope, crmScopeUsers, crmSettingKey, crmStageMoves, crmStageTasks, crmStageTasksSince, saveCrmSetting, saveStageMovesMark, } from "./crm-settings.js";
11
11
  import { crmStageEntriesOver } from "./crm-stage-entries.js";
12
12
  import { syncReportedIn } from "./reported-relations.js";
@@ -23,6 +23,8 @@ const relationNotes = ({ issues, skippedOwnerRejected, unlistedUsers, droppedPen
23
23
  ...(unlistedUsers ? { unlistedUsers } : {}),
24
24
  ...(droppedPending ? { droppedPending } : {}),
25
25
  });
26
+ /** The fields of a contact's record that are not its custom values. */
27
+ const PERSON_FIELDS = new Set(["name", "assignee", "created_at", "updated_at", "url"]);
26
28
  /** At most this many of a contact's phones or addresses: a CRM field holds what people typed into it. */
27
29
  const MOST_CONTACTS = 20;
28
30
  const listOf = (values, most) => values.flatMap((value) => textOf(value, most) ?? []).slice(0, MOST_CONTACTS);
@@ -322,6 +324,46 @@ export const crmCopiesOver = (context, people) => {
322
324
  "WHERE provider = ? AND external_id = ? AND json_extract(metadata, '$.assignee') IS NOT ?")
323
325
  .run(user, user, key.provider, crmIdentityId(key, externalId), user);
324
326
  };
327
+ /** Owner and times as the CRM gave them; one left out keeps what was stored. */
328
+ const ownerAndTimes = (key, previous, record) => {
329
+ const given = {
330
+ ...(record.assignee === undefined
331
+ ? {}
332
+ : { assignee: record.assignee ? crmIdentityId(key, normalCrmUserId(record.assignee), "user") : null }),
333
+ ...(record.createdAt == null ? {} : { created_at: record.createdAt }),
334
+ ...(record.updatedAt == null ? {} : { updated_at: record.updatedAt }),
335
+ };
336
+ return Object.fromEntries(["assignee", "created_at", "updated_at"].flatMap((field) => field in given
337
+ ? [[field, given[field]]]
338
+ : field in previous
339
+ ? [[field, previous[field]]]
340
+ : []));
341
+ };
342
+ /** The contact's record beside its identity: a custom value list given replaces the stored one whole. */
343
+ const savePersonRecord = (key, accountId, contact, at) => {
344
+ const held = database
345
+ .prepare("SELECT id, fields FROM records WHERE account_id = ? AND type = ? AND external_id = ?")
346
+ .get(accountId, PERSON_RECORD, contact.externalId);
347
+ const previous = held ? JSON.parse(String(held.fields)) : {};
348
+ const url = contact.url === undefined ? previous.url : contact.url;
349
+ const custom = contact.metadata ?? Object.fromEntries(Object.entries(previous).filter(([field]) => !PERSON_FIELDS.has(field)));
350
+ const fields = {
351
+ name: textOf(contact.name, 200),
352
+ ...ownerAndTimes(key, previous, contact),
353
+ ...(url ? { url } : {}),
354
+ ...custom,
355
+ };
356
+ const fingerprint = recordFingerprint(fields, []);
357
+ if (held)
358
+ database
359
+ .prepare("UPDATE records SET fields = ?, fingerprint = ?, updated_at = ?, deleted_at = NULL WHERE id = ?")
360
+ .run(JSON.stringify(fields), fingerprint, at, Number(held.id));
361
+ else
362
+ database
363
+ .prepare("INSERT INTO records (account_id, type, external_id, fields, fingerprint, batch_id, created_at, updated_at) " +
364
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
365
+ .run(accountId, PERSON_RECORD, contact.externalId, JSON.stringify(fields), fingerprint, SOURCE, at, at);
366
+ };
325
367
  const saveItems = (key, kind, items, users) => write(database, () => {
326
368
  const accountId = account(key);
327
369
  const at = now();
@@ -347,18 +389,19 @@ export const crmCopiesOver = (context, people) => {
347
389
  const at = now();
348
390
  for (const organization of organizations) {
349
391
  const name = textOf(organization.name, 200) ?? `${key.provider} company ${organization.externalId}`;
392
+ const held = database
393
+ .prepare("SELECT * FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ?")
394
+ .get(accountId, organization.externalId);
395
+ const previous = held ? JSON.parse(String(held.fields)) : {};
350
396
  const fields = {
351
397
  name,
352
398
  ...(organization.url ? { url: organization.url } : {}),
353
399
  ...(organization.own ? { own: true } : {}),
354
400
  ...(organization.type === undefined ? {} : { type: organization.type }),
401
+ ...ownerAndTimes(key, previous, organization),
355
402
  ...(organization.metadata ?? {}),
356
403
  };
357
404
  const fingerprint = recordFingerprint(fields, []);
358
- const held = database
359
- .prepare("SELECT * FROM records WHERE account_id = ? AND type = 'organization' AND external_id = ?")
360
- .get(accountId, organization.externalId);
361
- const previous = held ? JSON.parse(String(held.fields)) : {};
362
405
  const before = previous.name;
363
406
  let entity = held?.entity_type === "organization" && held.entity_id != null ? Number(held.entity_id) : null;
364
407
  if (entity === null)
@@ -519,6 +562,8 @@ export const crmCopiesOver = (context, people) => {
519
562
  for (const row of rows)
520
563
  mark.run(at, Number(row.id));
521
564
  const accountId = findAccountPk(context, key);
565
+ if (kind === "organization" && accountId !== undefined)
566
+ forgetActivitiesOn(database, accountId, kind, rows.map((row) => String(row.external_id)), at);
522
567
  if (isItemKind(kind) && accountId !== undefined && rows.length) {
523
568
  const pending = pendingBook(accountId);
524
569
  for (const row of rows)
@@ -543,9 +588,11 @@ export const crmCopiesOver = (context, people) => {
543
588
  const accountId = account(key);
544
589
  const tally = tallied();
545
590
  const pending = pendingBook(accountId);
591
+ const at = now();
546
592
  for (const contact of contacts) {
547
593
  if (contact.assignee !== undefined)
548
594
  assignContact(key, contact.externalId, contact.assignee);
595
+ savePersonRecord(key, accountId, contact, at);
549
596
  const person = nameUnnamed(key, contact.externalId, "contact", textOf(contact.name, 200));
550
597
  const email = textOf(contact.email, 320)?.toLowerCase();
551
598
  const sharing = email ? peopleSharing(key, contact.externalId, email) : 0;
@@ -614,8 +661,12 @@ export const crmCopiesOver = (context, people) => {
614
661
  markStageMoves: async (key, through) => saveStageMovesMark(database, key, through, now()),
615
662
  stageTasksSince: async (key) => crmStageTasksSince(database, key),
616
663
  saveStageEntries: async (key, entries) => stageEntryStore.save(key, entries),
617
- stageEntries: async (key) => stageEntryStore.pending(key),
664
+ stageEntries: async (key, at) => {
665
+ const since = crmStageTasksSince(database, key);
666
+ return since === null ? [] : stageEntryStore.pending(key, since, at);
667
+ },
618
668
  handleStageEntries: async (ids) => stageEntryStore.handled(ids),
669
+ expireStageEntries: async (key) => stageEntryStore.expire(key),
619
670
  activitiesOn: async (key) => crmActivitiesOn(database, key),
620
671
  saveActivities: async (key, activities) => activityStore.save(key, activities),
621
672
  activitiesOf: async (key, kind, externalId, limit) => activityStore.of(key, kind, externalId, limit),
@@ -635,6 +686,7 @@ export const crmCopiesOver = (context, people) => {
635
686
  ...options,
636
687
  users: options.users ?? crmScopeUsers(database, key).map(normalCrmUserId),
637
688
  }),
689
+ removeContact: async (key, externalId) => removeCrmContacts(context, key, { before: now(), only: [externalId] }),
638
690
  count: async (key, kind) => kind === "person"
639
691
  ? Number(database
640
692
  .prepare("SELECT count(*) AS n FROM identities WHERE provider = ? AND substr(external_id, 1, ?) = ?")
@@ -3,10 +3,11 @@ import type { CrmValue } from "../../domain/crm.js";
3
3
  import { type DealKind, type DealRole, type DealStatus, type StageOutcome } from "../../domain/deals.js";
4
4
  import type { AccountKey } from "../types.js";
5
5
  import { type ProposedByFilter } from "./actors.js";
6
+ import { type CopyViewer } from "./copy-viewer.js";
6
7
  import { type Author } from "./memories.js";
7
8
  import type { StoreContext } from "./open.js";
9
+ import { type FunnelCounts, type PipelinePeriod } from "./pipeline-period.js";
8
10
  import { type AuthorInfo, type Party } from "./reviewed.js";
9
- import { type StageAmounts } from "./stage-amounts.js";
10
11
  export interface PipelineStage {
11
12
  name: string;
12
13
  position: number;
@@ -29,32 +30,30 @@ export interface Pipeline {
29
30
  stages: PipelineStage[];
30
31
  createdAt: string;
31
32
  }
32
- export interface FunnelStage extends PipelineStage, StageAmounts {
33
- /** Rows that got this far: entered this stage or a later one that is not lost, or were won. */
34
- reached: number;
35
- /** `reached` of the next stage that is not lost over this stage's, 0–1; `null` for the last or an empty one. */
36
- conversion: number | null;
33
+ export interface FunnelStage extends PipelineStage, FunnelCounts {
37
34
  }
38
- /** A pipeline with its funnel, counted from `pipeline_stage_changes`. */
39
- export interface PipelineReport extends Omit<Pipeline, "stages"> {
35
+ /** A pipeline with its funnel and outcomes over a window (`pipelinePeriod`). */
36
+ export interface PipelineReport extends Omit<Pipeline, "stages">, Omit<PipelinePeriod, "stages"> {
40
37
  stages: FunnelStage[];
41
- totals: {
42
- items: number;
43
- open: number;
44
- won: number;
45
- lost: number;
46
- winRate: number | null;
38
+ /** The window's bounds as ISO times; `null` is open. */
39
+ window: {
40
+ since: string | null;
41
+ until: string | null;
47
42
  };
48
- /** `YYYY-MM-DD`: only rows made since that day are counted; `null` for all. */
43
+ /** `YYYY-MM-DD`: the UTC day `window.since` falls on; `null` for all. */
49
44
  since: string | null;
50
45
  }
51
- /** One stage a deal or a lead entered, as the store saw it: a CRM copy's change is dated by the sync that saw it. */
46
+ /**
47
+ * One stage a deal or a lead entered: from the CRM's own history (`exact`), else as the store saw it, a CRM copy's
48
+ * change dated by the sync that saw it.
49
+ */
52
50
  export interface StageChange {
53
- /** `null` for the stage it started in. */
51
+ /** `null` for the stage it started in, or the first the CRM's history names. */
54
52
  from: string | null;
55
53
  to: string;
56
54
  pipeline: string;
57
55
  at: string;
56
+ exact: boolean;
58
57
  }
59
58
  export interface DealPerson extends Party {
60
59
  role: DealRole;
@@ -142,8 +141,20 @@ export interface DealInput {
142
141
  reason?: string;
143
142
  evidence?: string[];
144
143
  }
144
+ export interface PipelineOptions {
145
+ kind?: DealKind;
146
+ since?: string;
147
+ until?: string;
148
+ zone?: string;
149
+ account?: DealScope;
150
+ viewer?: CopyViewer;
151
+ }
145
152
  /** Whose pipelines: the owner's own, one CRM account's copies, or, left out, every one. */
146
153
  export type DealScope = "own" | AccountKey;
154
+ export interface TimeBounds {
155
+ since?: number;
156
+ until?: number;
157
+ }
147
158
  export interface DealFilter {
148
159
  /** `deal` when left out. */
149
160
  kind?: DealKind;
@@ -159,6 +170,15 @@ export interface DealFilter {
159
170
  project?: string;
160
171
  organization?: string;
161
172
  proposedBy?: ProposedByFilter;
173
+ /** A CRM copy's assignee as the identity `<account>/user/<id>`; `null` is none. */
174
+ owner?: string | null;
175
+ /** Epoch ms bounds, inclusive, on when the CRM changed or made it. */
176
+ updated?: TimeBounds;
177
+ created?: TimeBounds;
178
+ /** On the day it was won or lost, the bounds' days in `zone` (the system's when left out). */
179
+ closed?: TimeBounds;
180
+ zone?: string;
181
+ viewer?: CopyViewer;
162
182
  /** 1–500, 100 by default; newest written first. */
163
183
  limit?: number;
164
184
  /** Rows to skip before the first one answered, for the next page. */
@@ -178,6 +198,7 @@ export interface DealSearch {
178
198
  accounts?: AccountKey[];
179
199
  /** Only these kinds; absent, deals and leads. */
180
200
  kinds?: readonly DealKind[];
201
+ viewers?: CopyViewer[];
181
202
  /** 1–500, 100 by default. */
182
203
  limit?: number;
183
204
  offset?: number;
@@ -214,13 +235,13 @@ export interface DealsStore {
214
235
  pipelines(filter?: {
215
236
  kind?: DealKind;
216
237
  account?: DealScope;
238
+ viewer?: CopyViewer;
217
239
  }): Promise<Pipeline[]>;
218
- /** One pipeline by `pipeline:<id>` or a name only one pipeline has, with its funnel. */
219
- pipeline(reference: string, options?: {
220
- kind?: DealKind;
221
- since?: string;
222
- account?: DealScope;
223
- }): Promise<PipelineReport>;
240
+ /**
241
+ * One pipeline by `pipeline:<id>` or a name only one pipeline has, with its funnel and outcomes over the window:
242
+ * `since` and `until` are a `YYYY-MM-DD` day or an ISO time, `zone` the owner's for closed days.
243
+ */
244
+ pipeline(reference: string, options?: PipelineOptions): Promise<PipelineReport>;
224
245
  add(input: DealInput): Promise<Deal>;
225
246
  /** `deal:<id>` or `lead:<id>`; a bare id is a deal. */
226
247
  get(reference: string): Promise<Deal>;
@@ -257,15 +278,12 @@ export interface DealsStore {
257
278
  }
258
279
  export declare const dealOperationsOver: (context: StoreContext) => {
259
280
  addPipeline: ({ name, kind, stages, by }: PipelineInput) => Pipeline;
260
- pipelines: (filter?: {
281
+ pipelines: ({ kind, account, viewer }?: {
261
282
  kind?: DealKind;
262
283
  account?: DealScope;
284
+ viewer?: CopyViewer;
263
285
  }) => Pipeline[];
264
- pipeline: (reference: string, options?: {
265
- kind?: DealKind;
266
- since?: string;
267
- account?: DealScope;
268
- }) => PipelineReport;
286
+ pipeline: (reference: string, options?: PipelineOptions) => PipelineReport;
269
287
  add: (input: DealInput) => Deal;
270
288
  get: (reference: string) => Deal;
271
289
  stages: (reference: string) => StageChange[];
@@ -1,5 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
+ import { timezoneOf } from "@wirecat/cli-base/query";
2
3
  import { DEAL_KINDS, DEAL_ROLES, DEAL_STATUSES, dealLine, STAGE_OUTCOMES, } from "../../domain/deals.js";
4
+ import { dayIn } from "../../domain/moment.js";
3
5
  import { currencyOf, formatDecimal, minorUnits, scaleOf } from "../../domain/money.js";
4
6
  import { notOverriddenSql } from "../../domain/relations.js";
5
7
  import { correctWords } from "../../search/correct.js";
@@ -7,14 +9,16 @@ import { createStemmer, DEFAULT_STEMMERS } from "../../search/stem.js";
7
9
  import { fold } from "../normalize.js";
8
10
  import { proposedBySql } from "./actors.js";
9
11
  import { suggestBaseStages } from "./base-suggest.js";
12
+ import { seenBy, viewerSql } from "./copy-viewer.js";
10
13
  import { activityTexts } from "./crm-activities.js";
11
14
  import { crmAccountPrefix } from "./crm-rows.js";
15
+ import { stageEntriesOf } from "./crm-stage-entries.js";
12
16
  import { linkKind } from "./link-kinds.js";
13
17
  import { authorActor, authorOf, evidenceOf, linkEvidence, projectId, projectOf } from "./memories.js";
14
18
  import { requiredThing } from "./notes.js";
19
+ import { bounded, boundOf, openPerStage, pipelinePeriod, } from "./pipeline-period.js";
15
20
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text } from "./reviewed.js";
16
21
  import { pageOfRows } from "./rows-page.js";
17
- import { stageAmountsOf } from "./stage-amounts.js";
18
22
  import { write } from "./transaction.js";
19
23
  const TABLES = { deal: "deals", lead: "leads" };
20
24
  const itemsSql = (kind) => "SELECT d.*, s.name AS stage_name, s.pipeline_id, p.name AS pipeline_name, b.name AS author_name, " +
@@ -183,14 +187,9 @@ export const dealOperationsOver = (context) => {
183
187
  return refuse(`more than one pipeline is named ${named}: ${rows.map(label).join(", ")}; name one by its reference`, "pipeline.ambiguous");
184
188
  return rows[0];
185
189
  };
186
- const stagesOf = (pipelineIds) => database
187
- .prepare("SELECT s.*, (SELECT count(*) FROM deals d WHERE d.stage_id = s.id AND d.status = 'open' AND d.deleted_at IS NULL) + " +
188
- "(SELECT count(*) FROM leads l WHERE l.stage_id = s.id AND l.status = 'open' AND l.deleted_at IS NULL) AS open " +
189
- `FROM pipeline_stages s WHERE s.pipeline_id IN (${pipelineIds.map(() => "?").join(", ") || "NULL"}) ` +
190
- "ORDER BY s.pipeline_id, s.position, s.id")
191
- .all(...pipelineIds);
192
- const pipelinesOf = (rows) => {
193
- const stages = stagesOf(rows.map((row) => Number(row.id)));
190
+ const pipelinesOf = (rows, viewer) => {
191
+ const ids = rows.map((row) => Number(row.id));
192
+ const stages = openPerStage(database, ids, viewer);
194
193
  return rows.map((row) => ({
195
194
  id: String(row.id),
196
195
  ref: `pipeline:${row.id}`,
@@ -235,57 +234,20 @@ export const dealOperationsOver = (context) => {
235
234
  .get(Number(pipelines[0]?.id));
236
235
  return row ?? refuse("the pipeline has no stages", "deal.stage");
237
236
  };
238
- const funnelOf = (pipeline, since) => {
239
- const kind = pipeline.kind;
240
- const cutoff = since === null ? null : Date.parse(`${since}T00:00:00Z`);
241
- const items = database
242
- .prepare(`SELECT d.id, d.status, d.stage_id FROM ${TABLES[kind]} d JOIN pipeline_stages s ON s.id = d.stage_id ` +
243
- "WHERE s.pipeline_id = ? AND d.deleted_at IS NULL AND (? IS NULL OR d.created_at >= ?)")
244
- .all(Number(pipeline.id), cutoff, cutoff);
245
- const stages = database
246
- .prepare("SELECT id, position, outcome FROM pipeline_stages WHERE pipeline_id = ? ORDER BY position, id")
247
- .all(Number(pipeline.id));
248
- const order = new Map(stages.map((stage, at) => [Number(stage.id), at]));
249
- const standing = stageAmountsOf(context, kind, stages.map((stage) => Number(stage.id)), cutoff);
250
- const lostStage = new Set(stages.filter((stage) => stage.outcome === "lost").map((stage) => Number(stage.id)));
251
- const entered = new Map();
252
- for (const change of database
253
- .prepare("SELECT item_id, to_stage_id FROM pipeline_stage_changes WHERE item_type = ? AND pipeline_id = ?")
254
- .all(kind, Number(pipeline.id))) {
255
- const list = entered.get(Number(change.item_id)) ?? [];
256
- list.push(Number(change.to_stage_id));
257
- entered.set(Number(change.item_id), list);
258
- }
259
- const furthest = items.map((item) => {
260
- if (item.status === "won")
261
- return Number.POSITIVE_INFINITY;
262
- const reached = [...(entered.get(Number(item.id)) ?? []), Number(item.stage_id)]
263
- .filter((stage) => !lostStage.has(stage))
264
- .map((stage) => order.get(stage) ?? -1);
265
- return Math.max(-1, ...reached);
266
- });
267
- const lost = items.filter((item) => item.status === "lost").length;
268
- const reachedAt = (at) => lostStage.has(Number(stages[at]?.id)) ? lost : furthest.filter((far) => far >= at).length;
269
- const funnel = pipeline.stages.map((stage, at) => {
270
- const reached = reachedAt(at);
271
- const next = stages.findIndex((one, after) => after > at && !lostStage.has(Number(one.id)));
272
- const conversion = lostStage.has(Number(stages[at]?.id)) || next === -1 || reached === 0
273
- ? null
274
- : Math.round((reachedAt(next) / reached) * 1000) / 1000;
275
- return { ...stage, reached, conversion, ...standing[at] };
276
- });
277
- const won = items.filter((item) => item.status === "won").length;
237
+ const funnelOf = (pipeline, options) => {
238
+ const { since, until, zone = timezoneOf(), viewer } = options;
239
+ const window = {
240
+ since: boundOf(since, "the first day counted", zone),
241
+ until: boundOf(until, "the last day counted", zone, true),
242
+ };
243
+ const { stages, ...period } = pipelinePeriod(context, pipeline, window, zone, viewer);
244
+ const at = (bound) => (bound === null ? null : new Date(bound).toISOString());
278
245
  return {
279
246
  ...pipeline,
280
- stages: funnel,
281
- totals: {
282
- items: items.length,
283
- open: items.length - won - lost,
284
- won,
285
- lost,
286
- winRate: won + lost === 0 ? null : Math.round((won / (won + lost)) * 1000) / 1000,
287
- },
288
- since,
247
+ ...period,
248
+ stages: pipeline.stages.map((stage, index) => ({ ...stage, ...stages[index] })),
249
+ window: { since: at(window.since), until: at(window.until) },
250
+ since: at(window.since)?.slice(0, 10) ?? null,
289
251
  };
290
252
  };
291
253
  /** Sets the stage and, from its outcome, the status; a stage that ends the row closes it today. */
@@ -336,11 +298,11 @@ export const dealOperationsOver = (context) => {
336
298
  });
337
299
  return pipelinesOf(pipelineRows(pipelineKind, undefined, { deleted: true }).filter((row) => Number(row.id) === id))[0];
338
300
  },
339
- pipelines: (filter = {}) => pipelinesOf(pipelineRows(filter.kind === undefined ? undefined : kindOf(filter.kind), filter.account)),
301
+ pipelines: ({ kind, account, viewer } = {}) => pipelinesOf(pipelineRows(kind === undefined ? undefined : kindOf(kind), account), viewer),
340
302
  pipeline: (reference, options = {}) => {
341
303
  const kind = options.kind === undefined ? undefined : kindOf(options.kind);
342
- const since = isoDate(options.since, "the first day counted");
343
- return funnelOf(pipelinesOf([pipelineRow(reference, kind, options.account)])[0], since);
304
+ const [found] = pipelinesOf([pipelineRow(reference, kind, options.account)], options.viewer);
305
+ return funnelOf(found, options);
344
306
  },
345
307
  add: (input) => {
346
308
  const kind = kindOf(input.kind);
@@ -399,17 +361,22 @@ export const dealOperationsOver = (context) => {
399
361
  get: (reference) => read(reference),
400
362
  stages: (reference) => {
401
363
  const { kind, row } = rowOf(reference);
402
- return database
403
- .prepare("SELECT c.pipeline_id, c.changed_at, f.name AS from_name, t.name AS to_name FROM pipeline_stage_changes c " +
404
- "LEFT JOIN pipeline_stages f ON f.id = c.from_stage_id JOIN pipeline_stages t ON t.id = c.to_stage_id " +
405
- "WHERE c.item_type = ? AND c.item_id = ? ORDER BY c.id")
406
- .all(kind, Number(row.id))
407
- .map((change) => ({
408
- from: change.from_name == null ? null : String(change.from_name),
409
- to: String(change.to_name),
410
- pipeline: `pipeline:${change.pipeline_id}`,
411
- at: iso(change.changed_at),
412
- }));
364
+ const own = stageEntriesOf(database, kind, { item: Number(row.id) });
365
+ const stages = new Map(database
366
+ .prepare(`SELECT id, name, pipeline_id FROM pipeline_stages WHERE id IN (${own.map(() => "?").join(", ") || "NULL"})`)
367
+ .all(...own.map(({ toStageId }) => toStageId))
368
+ .map((stage) => [Number(stage.id), stage]));
369
+ return own.map((entry, at) => {
370
+ const stage = stages.get(entry.toStageId);
371
+ const before = at === 0 ? undefined : stages.get(own[at - 1].toStageId);
372
+ return {
373
+ from: before === undefined ? null : String(before.name),
374
+ to: String(stage.name),
375
+ pipeline: `pipeline:${stage.pipeline_id}`,
376
+ at: iso(entry.at),
377
+ exact: entry.exact,
378
+ };
379
+ });
413
380
  },
414
381
  list: (filter = {}) => {
415
382
  const kind = kindOf(filter.kind);
@@ -429,18 +396,37 @@ export const dealOperationsOver = (context) => {
429
396
  ? ""
430
397
  : `AND (d.account_id IS NULL OR a.provider || ':' || a.external_id IN (${keys.map(() => "?").join(", ") || "NULL"})) `;
431
398
  const offset = Math.max(0, Math.trunc(filter.offset ?? 0));
399
+ const zone = filter.zone ?? timezoneOf();
400
+ const days = {
401
+ since: filter.closed?.since === undefined ? undefined : dayIn(filter.closed.since, zone),
402
+ until: filter.closed?.until === undefined ? undefined : dayIn(filter.closed.until, zone),
403
+ };
404
+ const within = [
405
+ ...(filter.viewer ? [viewerSql("d", filter.viewer)] : []),
406
+ ...bounded("d.updated_at", filter.updated),
407
+ ...bounded("d.closed_date", filter.closed && days),
408
+ ...bounded("d.created_at", filter.created),
409
+ ...(filter.owner === undefined
410
+ ? []
411
+ : [
412
+ filter.owner === null
413
+ ? { sql: "json_extract(d.metadata, '$.assignee') IS NULL", params: [] }
414
+ : { sql: "json_extract(d.metadata, '$.assignee') = ?", params: [filter.owner] },
415
+ ]),
416
+ ];
432
417
  const rows = database
433
- .prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL AND (? IS NULL OR d.status = ?) ` +
418
+ .prepare(`${itemsSql(kind)} WHERE d.deleted_at IS NULL ${within.map(({ sql }) => `AND ${sql} `).join("")}` +
419
+ "AND (? IS NULL OR d.status = ?) " +
434
420
  "AND (? IS NULL OR d.project_id = ?) AND (? IS NULL OR s.name_folded = ?) AND (? IS NULL OR p.id = ?) " +
435
421
  "AND (? IS NULL OR d.organization_id = ?) AND (? = 0 OR d.account_id IS NULL) " +
436
422
  `AND (? IS NULL OR (a.provider = ? AND a.external_id = ?)) ${inAccounts}AND ${by.sql} ` +
437
423
  "ORDER BY d.created_at DESC, d.id DESC LIMIT ? OFFSET ?")
438
- .all(status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit + 1, offset)
424
+ .all(...within.flatMap(({ params }) => params), status, status, project, project, stage, stage, pipeline, pipeline, organization?.id ?? null, organization?.id ?? null, own, provider, provider, account, ...(keys ?? []), ...by.params, limit + 1, offset)
439
425
  .map(itemOf(kind));
440
426
  return pageOfRows(rows, limit, offset);
441
427
  },
442
428
  find: async (wanted) => {
443
- const { words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit, offset = 0 } = wanted;
429
+ const { words, anyWord, exact = false, accounts, kinds = DEAL_KINDS, limit, offset = 0, viewers = [] } = wanted;
444
430
  const seen = new Set();
445
431
  const clauses = words
446
432
  .map((word) => tokensOf(word).filter((token) => fold(token)))
@@ -502,11 +488,13 @@ export const dealOperationsOver = (context) => {
502
488
  return database
503
489
  .prepare(`SELECT d.id, d.account_id, d.external_id, d.title, d.updated_at, a.provider, a.external_id AS account, o.name AS company, ` +
504
490
  "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.company_name') END AS own_company, " +
505
- "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact " +
491
+ "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.contact_name') END AS own_contact, " +
492
+ "CASE WHEN json_valid(d.metadata) THEN json_extract(d.metadata, '$.assignee') END AS assignee " +
506
493
  `FROM ${TABLES[kind]} d LEFT JOIN accounts a ON a.id = d.account_id ` +
507
494
  "LEFT JOIN organizations o ON o.id = d.organization_id WHERE d.deleted_at IS NULL")
508
495
  .all()
509
496
  .filter((row) => within === undefined || within.includes(`${row.provider}\u0000${row.account}`))
497
+ .filter((row) => viewers.every((viewer) => seenBy(viewer, row)))
510
498
  .map((row) => ({
511
499
  kind,
512
500
  row,
@@ -0,0 +1,85 @@
1
+ import type { DealKind } from "../../domain/deals.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import { type CopyViewer } from "./copy-viewer.js";
4
+ import type { StoreContext } from "./open.js";
5
+ import { type StageAmount, type StageAmounts } from "./stage-amounts.js";
6
+ /** A column between the bounds, each inclusive; no bound, no condition. */
7
+ export declare const bounded: (column: string, bounds: {
8
+ since?: number | string;
9
+ until?: number | string;
10
+ } | undefined) => {
11
+ sql: string;
12
+ params: (number | string)[];
13
+ }[];
14
+ /** A window's bound, a `YYYY-MM-DD` day in `zone` (its start, or its end for `end`) or an ISO time, as epoch ms. */
15
+ export declare const boundOf: (value: string | undefined, what: string, zone: string, end?: boolean) => number | null;
16
+ /** A stage the CRM removed stays in a pipeline only while a row stands in it (BUG-7). */
17
+ export declare const SHOWN_STAGE: string;
18
+ /** Each stage of these pipelines that is shown, with how many open deals and leads the viewer may read stand in it. */
19
+ export declare const openPerStage: (database: CacheDatabase, pipelineIds: number[], viewer?: CopyViewer) => Record<string, unknown>[];
20
+ /** Epoch ms bounds, both inclusive; `null` is open. */
21
+ export interface PeriodWindow {
22
+ since: number | null;
23
+ until: number | null;
24
+ }
25
+ export interface FunnelCounts extends StageAmounts {
26
+ /** Rows of the cohort that got this far: entered this stage or a later one that is not lost, or were won. */
27
+ reached: number;
28
+ /** `reached` of the next stage that is not lost over this stage's, 0–1; `null` for the last or an empty one. */
29
+ conversion: number | null;
30
+ /** The median days a cohort row stayed in the stage before it entered another; `null` when none left it. */
31
+ medianDays: number | null;
32
+ }
33
+ export interface PipelinePeriod {
34
+ stages: FunnelCounts[];
35
+ /** The cohort: rows made in the window. */
36
+ totals: {
37
+ items: number;
38
+ open: number;
39
+ won: number;
40
+ lost: number;
41
+ winRate: number | null;
42
+ };
43
+ /** Rows closed on a day in the window, in the owner's zone. */
44
+ closed: {
45
+ won: number;
46
+ lost: number;
47
+ winRate: number | null;
48
+ wonAmounts: StageAmount[];
49
+ };
50
+ /** Days from made to won, for rows won in the window: the CRM's entry into the won stage, else the closed day. */
51
+ cycle: {
52
+ medianDays: number | null;
53
+ items: number;
54
+ };
55
+ /** The cohort by its CRM assignee. */
56
+ owners: {
57
+ assignee: string | null;
58
+ name: string | null;
59
+ open: number;
60
+ won: number;
61
+ lost: number;
62
+ winRate: number | null;
63
+ }[];
64
+ /** Why rows closed lost in the window were lost, the most common first. */
65
+ lostReasons: {
66
+ reason: string;
67
+ items: number;
68
+ }[];
69
+ /** Rows whose stages came from the CRM's own history, and from the copy's diffs between syncs. */
70
+ history: {
71
+ exact: number;
72
+ copy: number;
73
+ };
74
+ }
75
+ /**
76
+ * One pipeline's funnel and outcomes over a window: the funnel counts the cohort made in it, `closed`, `cycle` and
77
+ * `lostReasons` the rows closed in it. Each row's stages come from the CRM's history where it has one, else the copy's.
78
+ */
79
+ export declare const pipelinePeriod: (context: StoreContext, pipeline: {
80
+ id: string;
81
+ kind: DealKind;
82
+ account: {
83
+ provider: string;
84
+ } | null;
85
+ }, window: PeriodWindow, zone: string, viewer?: CopyViewer) => PipelinePeriod;