@odla-ai/crm 0.9.2 → 0.10.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/dist/index.d.cts CHANGED
@@ -764,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
764
764
  unused: string[];
765
765
  };
766
766
 
767
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
768
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
769
769
  /** Load one record by id, or null. */
770
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -781,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
781
781
  /** Create a record of `type` from custom-field input. Also creates (or
782
782
  * upserts) the primary email contact channel when the type declares an
783
783
  * `emailField`. New records rank at `now` so manual order defaults to
784
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
785
787
  declare function createRecord(deps: CrmDeps, opts: {
786
788
  type: string;
787
789
  input: Record<string, unknown>;
788
790
  ownerId?: string;
789
- stage?: string;
791
+ stage?: string | null;
790
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
791
799
  }): Promise<{
792
800
  id: string;
793
801
  duplicate: boolean;
@@ -1020,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
1020
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
1021
1029
  * the ops plus the `emailStatus` the record should fold to.
1022
1030
  */
1023
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
1024
1035
  ops: CrmOp[];
1025
1036
  emailStatus: EmailStatus;
1026
1037
  };
@@ -1350,7 +1361,7 @@ declare class CrmClient {
1350
1361
  type: string;
1351
1362
  input: Record<string, unknown>;
1352
1363
  ownerId?: string;
1353
- stage?: string;
1364
+ stage?: string | null;
1354
1365
  mutationId?: string;
1355
1366
  }): Promise<{
1356
1367
  id: string;
package/dist/index.d.ts CHANGED
@@ -764,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
764
764
  unused: string[];
765
765
  };
766
766
 
767
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
768
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
769
769
  /** Load one record by id, or null. */
770
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -781,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
781
781
  /** Create a record of `type` from custom-field input. Also creates (or
782
782
  * upserts) the primary email contact channel when the type declares an
783
783
  * `emailField`. New records rank at `now` so manual order defaults to
784
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
785
787
  declare function createRecord(deps: CrmDeps, opts: {
786
788
  type: string;
787
789
  input: Record<string, unknown>;
788
790
  ownerId?: string;
789
- stage?: string;
791
+ stage?: string | null;
790
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
791
799
  }): Promise<{
792
800
  id: string;
793
801
  duplicate: boolean;
@@ -1020,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
1020
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
1021
1029
  * the ops plus the `emailStatus` the record should fold to.
1022
1030
  */
1023
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
1024
1035
  ops: CrmOp[];
1025
1036
  emailStatus: EmailStatus;
1026
1037
  };
@@ -1350,7 +1361,7 @@ declare class CrmClient {
1350
1361
  type: string;
1351
1362
  input: Record<string, unknown>;
1352
1363
  ownerId?: string;
1353
- stage?: string;
1364
+ stage?: string | null;
1354
1365
  mutationId?: string;
1355
1366
  }): Promise<{
1356
1367
  id: string;
package/dist/index.js CHANGED
@@ -837,7 +837,7 @@ async function listChannels(deps, recordId) {
837
837
  });
838
838
  return (result[CRM_NS.channel] ?? []).map(rowToChannel);
839
839
  }
840
- function emailChannelOps(deps, recordId, email, existing) {
840
+ function emailChannelOps(deps, recordId, email, existing, initialConsent = { state: "subscribed", source: "record-write" }) {
841
841
  const { now, newId } = resolveDeps(deps);
842
842
  const ops = [];
843
843
  const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
@@ -861,14 +861,14 @@ function emailChannelOps(deps, recordId, email, existing) {
861
861
  kind: "email",
862
862
  value: email,
863
863
  isPrimary: true,
864
- consent: "subscribed",
864
+ consent: initialConsent.state,
865
865
  consentAt: now(),
866
- consentSource: "record-write",
866
+ consentSource: initialConsent.source,
867
867
  unsubscribeToken: newId(),
868
868
  createdAt: now()
869
869
  }
870
870
  });
871
- return { ops, emailStatus: "ok" };
871
+ return { ops, emailStatus: foldEmailStatus(initialConsent.state) };
872
872
  }
873
873
  async function applyConsent(deps, opts) {
874
874
  const { db, now } = resolveDeps(deps);
@@ -924,7 +924,7 @@ function applyPatch(base, patch, alsoClear = []) {
924
924
 
925
925
  // src/records.ts
926
926
  function rowToRecord(row) {
927
- const record = row;
927
+ const record = rowAsWritten(CRM_NS.record, row);
928
928
  return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
929
929
  }
930
930
  async function getRecord(deps, id) {
@@ -974,9 +974,9 @@ async function createRecord(deps, opts) {
974
974
  const { crm, db, now, newId } = resolveDeps(deps);
975
975
  const prepared = crm.prepare(opts.type, opts.input);
976
976
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
977
- const id = newId();
977
+ const id = opts.id ?? newId();
978
978
  const at = now();
979
- const stage = opts.stage ?? crm.initialStage(opts.type);
979
+ const stage = opts.stage === void 0 ? crm.initialStage(opts.type) : opts.stage;
980
980
  const attrs = {
981
981
  id,
982
982
  // mirror the entity id as an attr so `where: { id }` reads can find it
@@ -996,7 +996,7 @@ async function createRecord(deps, opts) {
996
996
  const ops = [];
997
997
  const email = prepared.attrs["primaryEmail"] ?? null;
998
998
  if (crm.type(opts.type).emailField) {
999
- const channel = emailChannelOps(deps, id, email, []);
999
+ const channel = emailChannelOps(deps, id, email, [], opts.emailConsent);
1000
1000
  attrs.emailStatus = channel.emailStatus;
1001
1001
  ops.push(...channel.ops);
1002
1002
  } else {
@@ -1006,7 +1006,9 @@ async function createRecord(deps, opts) {
1006
1006
  const score = scoreOf(deps, opts.type, candidate);
1007
1007
  if (score !== void 0) attrs.score = score;
1008
1008
  ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
1009
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1009
+ const guards = [...opts.guards ?? [], ...opts.id ? [{ ns: CRM_NS.record, id, exists: false }] : []];
1010
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId, ...guards.length ? { guards } : {} });
1011
+ if (duplicate && opts.id) return { id, duplicate, record: await mustGetRecord(deps, id) };
1010
1012
  return { id, duplicate, record: { id, ...attrs } };
1011
1013
  }
1012
1014
  async function updateRecord(deps, opts) {
@@ -1766,10 +1768,12 @@ async function recordCanEmail(deps, recordId, cls) {
1766
1768
  async function linkIdentity(deps, opts) {
1767
1769
  const { db, now } = resolveDeps(deps);
1768
1770
  const record = await mustGetRecord(deps, opts.recordId);
1771
+ if (record.clerkUserId) return { linked: true, clerkUserId: record.clerkUserId };
1769
1772
  const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1770
1773
  if (!email) throw new CrmInputError("record has no email to match on");
1771
- const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1772
- const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1774
+ const result = await db.query({ $users: { $: { where: { email }, limit: 2 } } });
1775
+ const users = result["$users"] ?? [];
1776
+ const user = users.length === 1 && !users[0]["deleted"] ? users[0] : void 0;
1773
1777
  if (!user) return { linked: false };
1774
1778
  const { duplicate } = await db.transact(
1775
1779
  [
@@ -1780,7 +1784,24 @@ async function linkIdentity(deps, opts) {
1780
1784
  attrs: { clerkUserId: user.id, updatedAt: now() }
1781
1785
  }
1782
1786
  ],
1783
- { mutationId: opts.mutationId }
1787
+ { mutationId: opts.mutationId, guards: [
1788
+ {
1789
+ ns: "$users",
1790
+ id: user.id,
1791
+ exists: true,
1792
+ equals: {
1793
+ email,
1794
+ ...user["deleted"] !== void 0 ? { deleted: user["deleted"] } : {}
1795
+ },
1796
+ ...user["deleted"] === void 0 ? { absent: ["deleted"] } : {}
1797
+ },
1798
+ {
1799
+ ns: CRM_NS.record,
1800
+ id: record.id,
1801
+ exists: true,
1802
+ ...record.clerkUserId === null ? { equals: { clerkUserId: null } } : { absent: ["clerkUserId"] }
1803
+ }
1804
+ ] }
1784
1805
  );
1785
1806
  return { linked: true, clerkUserId: user.id, duplicate };
1786
1807
  }
@@ -2121,7 +2142,7 @@ async function handleRecordsRoot(ctx, req, url) {
2121
2142
  type: str(body, "type"),
2122
2143
  input: obj(body, "input"),
2123
2144
  ownerId: optStr(body, "ownerId"),
2124
- stage: optStr(body, "stage"),
2145
+ stage: nullableStr(body, "stage"),
2125
2146
  mutationId: optStr(body, "mutationId")
2126
2147
  });
2127
2148
  return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);