@odla-ai/crm 0.9.1 → 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.cjs CHANGED
@@ -956,7 +956,7 @@ async function listChannels(deps, recordId) {
956
956
  });
957
957
  return (result[CRM_NS.channel] ?? []).map(rowToChannel);
958
958
  }
959
- function emailChannelOps(deps, recordId, email, existing) {
959
+ function emailChannelOps(deps, recordId, email, existing, initialConsent = { state: "subscribed", source: "record-write" }) {
960
960
  const { now, newId } = resolveDeps(deps);
961
961
  const ops = [];
962
962
  const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
@@ -980,14 +980,14 @@ function emailChannelOps(deps, recordId, email, existing) {
980
980
  kind: "email",
981
981
  value: email,
982
982
  isPrimary: true,
983
- consent: "subscribed",
983
+ consent: initialConsent.state,
984
984
  consentAt: now(),
985
- consentSource: "record-write",
985
+ consentSource: initialConsent.source,
986
986
  unsubscribeToken: newId(),
987
987
  createdAt: now()
988
988
  }
989
989
  });
990
- return { ops, emailStatus: "ok" };
990
+ return { ops, emailStatus: foldEmailStatus(initialConsent.state) };
991
991
  }
992
992
  async function applyConsent(deps, opts) {
993
993
  const { db, now } = resolveDeps(deps);
@@ -1043,7 +1043,7 @@ function applyPatch(base, patch, alsoClear = []) {
1043
1043
 
1044
1044
  // src/records.ts
1045
1045
  function rowToRecord(row) {
1046
- const record = row;
1046
+ const record = rowAsWritten(CRM_NS.record, row);
1047
1047
  return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
1048
1048
  }
1049
1049
  async function getRecord(deps, id) {
@@ -1093,9 +1093,9 @@ async function createRecord(deps, opts) {
1093
1093
  const { crm, db, now, newId } = resolveDeps(deps);
1094
1094
  const prepared = crm.prepare(opts.type, opts.input);
1095
1095
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
1096
- const id = newId();
1096
+ const id = opts.id ?? newId();
1097
1097
  const at = now();
1098
- const stage = opts.stage ?? crm.initialStage(opts.type);
1098
+ const stage = opts.stage === void 0 ? crm.initialStage(opts.type) : opts.stage;
1099
1099
  const attrs = {
1100
1100
  id,
1101
1101
  // mirror the entity id as an attr so `where: { id }` reads can find it
@@ -1115,7 +1115,7 @@ async function createRecord(deps, opts) {
1115
1115
  const ops = [];
1116
1116
  const email = prepared.attrs["primaryEmail"] ?? null;
1117
1117
  if (crm.type(opts.type).emailField) {
1118
- const channel = emailChannelOps(deps, id, email, []);
1118
+ const channel = emailChannelOps(deps, id, email, [], opts.emailConsent);
1119
1119
  attrs.emailStatus = channel.emailStatus;
1120
1120
  ops.push(...channel.ops);
1121
1121
  } else {
@@ -1125,11 +1125,13 @@ async function createRecord(deps, opts) {
1125
1125
  const score = scoreOf(deps, opts.type, candidate);
1126
1126
  if (score !== void 0) attrs.score = score;
1127
1127
  ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
1128
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1128
+ const guards = [...opts.guards ?? [], ...opts.id ? [{ ns: CRM_NS.record, id, exists: false }] : []];
1129
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId, ...guards.length ? { guards } : {} });
1130
+ if (duplicate && opts.id) return { id, duplicate, record: await mustGetRecord(deps, id) };
1129
1131
  return { id, duplicate, record: { id, ...attrs } };
1130
1132
  }
1131
1133
  async function updateRecord(deps, opts) {
1132
- const { crm, db, now } = resolveDeps(deps);
1134
+ const { crm, db, now, newId } = resolveDeps(deps);
1133
1135
  const existing = await mustGetRecord(deps, opts.id);
1134
1136
  const prepared = crm.prepare(existing.type, opts.input, existing);
1135
1137
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
@@ -1148,8 +1150,33 @@ async function updateRecord(deps, opts) {
1148
1150
  const score = scoreOf(deps, existing.type, candidate);
1149
1151
  if (score !== void 0) patch.score = score;
1150
1152
  const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];
1151
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1152
- return { record: applyPatch(existing, patch, prepared.retract), duplicate };
1153
+ if (opts.audit) {
1154
+ const body = opts.audit.body.trim();
1155
+ if (!body) throw new CrmInputError("audit body is required");
1156
+ const id = opts.audit.id ?? newId();
1157
+ ops.push({
1158
+ t: "update",
1159
+ ns: CRM_NS.activity,
1160
+ id,
1161
+ attrs: {
1162
+ id,
1163
+ recordId: existing.id,
1164
+ kind: "note",
1165
+ body,
1166
+ authorId: opts.audit.authorId,
1167
+ createdAt: now(),
1168
+ ...opts.audit.meta ? { meta: opts.audit.meta } : {}
1169
+ }
1170
+ });
1171
+ }
1172
+ const { duplicate } = await db.transact(ops, {
1173
+ mutationId: opts.mutationId,
1174
+ ...opts.expectedUpdatedAt === void 0 ? {} : { guards: [{ ns: CRM_NS.record, id: existing.id, exists: true, equals: { updatedAt: opts.expectedUpdatedAt } }] }
1175
+ });
1176
+ return {
1177
+ record: duplicate ? await mustGetRecord(deps, existing.id) : applyPatch(existing, patch, prepared.retract),
1178
+ duplicate
1179
+ };
1153
1180
  }
1154
1181
  async function setArchived(deps, opts) {
1155
1182
  const { db, now } = resolveDeps(deps);
@@ -1176,7 +1203,7 @@ async function setStage(deps, opts) {
1176
1203
  stageChangedAt: at,
1177
1204
  updatedAt: at
1178
1205
  };
1179
- const activityId = newId();
1206
+ const activityId = opts.activityId ?? newId();
1180
1207
  const ops = [
1181
1208
  { t: "update", ns: CRM_NS.record, id: record.id, attrs },
1182
1209
  {
@@ -1188,14 +1215,30 @@ async function setStage(deps, opts) {
1188
1215
  // mirror the entity id so the activity is readable by id
1189
1216
  recordId: record.id,
1190
1217
  kind: "stage_change",
1191
- body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1218
+ body: opts.activityBody ?? `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1192
1219
  authorId: opts.authorId,
1193
- createdAt: at
1220
+ createdAt: at,
1221
+ ...opts.activityMeta ? { meta: opts.activityMeta } : {}
1194
1222
  }
1195
1223
  }
1196
1224
  ];
1197
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1198
- const updated = { ...record, ...attrs };
1225
+ const equals = {};
1226
+ if (opts.expectedUpdatedAt !== void 0) equals.updatedAt = opts.expectedUpdatedAt;
1227
+ if (typeof opts.expectedStage === "string") equals.stage = opts.expectedStage;
1228
+ const guarded = opts.expectedUpdatedAt !== void 0 || opts.expectedStage !== void 0;
1229
+ const { duplicate } = await db.transact(ops, {
1230
+ mutationId: opts.mutationId,
1231
+ ...guarded ? {
1232
+ guards: [{
1233
+ ns: CRM_NS.record,
1234
+ id: record.id,
1235
+ exists: true,
1236
+ ...Object.keys(equals).length ? { equals } : {},
1237
+ ...opts.expectedStage === null ? { absent: ["stage"] } : {}
1238
+ }]
1239
+ } : {}
1240
+ });
1241
+ const updated = duplicate ? await mustGetRecord(deps, record.id) : { ...record, ...attrs };
1199
1242
  return {
1200
1243
  record: updated,
1201
1244
  from: record.stage ?? null,
@@ -1844,10 +1887,12 @@ async function recordCanEmail(deps, recordId, cls) {
1844
1887
  async function linkIdentity(deps, opts) {
1845
1888
  const { db, now } = resolveDeps(deps);
1846
1889
  const record = await mustGetRecord(deps, opts.recordId);
1890
+ if (record.clerkUserId) return { linked: true, clerkUserId: record.clerkUserId };
1847
1891
  const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1848
1892
  if (!email) throw new CrmInputError("record has no email to match on");
1849
- const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1850
- const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1893
+ const result = await db.query({ $users: { $: { where: { email }, limit: 2 } } });
1894
+ const users = result["$users"] ?? [];
1895
+ const user = users.length === 1 && !users[0]["deleted"] ? users[0] : void 0;
1851
1896
  if (!user) return { linked: false };
1852
1897
  const { duplicate } = await db.transact(
1853
1898
  [
@@ -1858,7 +1903,24 @@ async function linkIdentity(deps, opts) {
1858
1903
  attrs: { clerkUserId: user.id, updatedAt: now() }
1859
1904
  }
1860
1905
  ],
1861
- { mutationId: opts.mutationId }
1906
+ { mutationId: opts.mutationId, guards: [
1907
+ {
1908
+ ns: "$users",
1909
+ id: user.id,
1910
+ exists: true,
1911
+ equals: {
1912
+ email,
1913
+ ...user["deleted"] !== void 0 ? { deleted: user["deleted"] } : {}
1914
+ },
1915
+ ...user["deleted"] === void 0 ? { absent: ["deleted"] } : {}
1916
+ },
1917
+ {
1918
+ ns: CRM_NS.record,
1919
+ id: record.id,
1920
+ exists: true,
1921
+ ...record.clerkUserId === null ? { equals: { clerkUserId: null } } : { absent: ["clerkUserId"] }
1922
+ }
1923
+ ] }
1862
1924
  );
1863
1925
  return { linked: true, clerkUserId: user.id, duplicate };
1864
1926
  }
@@ -2199,7 +2261,7 @@ async function handleRecordsRoot(ctx, req, url) {
2199
2261
  type: str(body, "type"),
2200
2262
  input: obj(body, "input"),
2201
2263
  ownerId: optStr(body, "ownerId"),
2202
- stage: optStr(body, "stage"),
2264
+ stage: nullableStr(body, "stage"),
2203
2265
  mutationId: optStr(body, "mutationId")
2204
2266
  });
2205
2267
  return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);