@odla-ai/crm 0.9.2 → 0.10.1

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
@@ -68,6 +68,7 @@ __export(index_exports, {
68
68
  getRecordByOrigin: () => getRecordByOrigin,
69
69
  getRecordOrigin: () => getRecordOrigin,
70
70
  initialStage: () => initialStage,
71
+ isEmailTierName: () => isEmailTierName,
71
72
  linkIdentity: () => linkIdentity,
72
73
  lintTemplate: () => lintTemplate,
73
74
  listActivities: () => listActivities,
@@ -113,7 +114,8 @@ __export(index_exports, {
113
114
  updateRecord: () => updateRecord,
114
115
  updateTask: () => updateTask,
115
116
  updateView: () => updateView,
116
- upsertRecordOrigin: () => upsertRecordOrigin
117
+ upsertRecordOrigin: () => upsertRecordOrigin,
118
+ validateEmailCopy: () => validateEmailCopy
117
119
  });
118
120
  module.exports = __toCommonJS(index_exports);
119
121
 
@@ -956,7 +958,7 @@ async function listChannels(deps, recordId) {
956
958
  });
957
959
  return (result[CRM_NS.channel] ?? []).map(rowToChannel);
958
960
  }
959
- function emailChannelOps(deps, recordId, email, existing) {
961
+ function emailChannelOps(deps, recordId, email, existing, initialConsent = { state: "subscribed", source: "record-write" }) {
960
962
  const { now, newId } = resolveDeps(deps);
961
963
  const ops = [];
962
964
  const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
@@ -980,14 +982,14 @@ function emailChannelOps(deps, recordId, email, existing) {
980
982
  kind: "email",
981
983
  value: email,
982
984
  isPrimary: true,
983
- consent: "subscribed",
985
+ consent: initialConsent.state,
984
986
  consentAt: now(),
985
- consentSource: "record-write",
987
+ consentSource: initialConsent.source,
986
988
  unsubscribeToken: newId(),
987
989
  createdAt: now()
988
990
  }
989
991
  });
990
- return { ops, emailStatus: "ok" };
992
+ return { ops, emailStatus: foldEmailStatus(initialConsent.state) };
991
993
  }
992
994
  async function applyConsent(deps, opts) {
993
995
  const { db, now } = resolveDeps(deps);
@@ -1043,7 +1045,7 @@ function applyPatch(base, patch, alsoClear = []) {
1043
1045
 
1044
1046
  // src/records.ts
1045
1047
  function rowToRecord(row) {
1046
- const record = row;
1048
+ const record = rowAsWritten(CRM_NS.record, row);
1047
1049
  return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
1048
1050
  }
1049
1051
  async function getRecord(deps, id) {
@@ -1093,9 +1095,9 @@ async function createRecord(deps, opts) {
1093
1095
  const { crm, db, now, newId } = resolveDeps(deps);
1094
1096
  const prepared = crm.prepare(opts.type, opts.input);
1095
1097
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
1096
- const id = newId();
1098
+ const id = opts.id ?? newId();
1097
1099
  const at = now();
1098
- const stage = opts.stage ?? crm.initialStage(opts.type);
1100
+ const stage = opts.stage === void 0 ? crm.initialStage(opts.type) : opts.stage;
1099
1101
  const attrs = {
1100
1102
  id,
1101
1103
  // mirror the entity id as an attr so `where: { id }` reads can find it
@@ -1115,7 +1117,7 @@ async function createRecord(deps, opts) {
1115
1117
  const ops = [];
1116
1118
  const email = prepared.attrs["primaryEmail"] ?? null;
1117
1119
  if (crm.type(opts.type).emailField) {
1118
- const channel = emailChannelOps(deps, id, email, []);
1120
+ const channel = emailChannelOps(deps, id, email, [], opts.emailConsent);
1119
1121
  attrs.emailStatus = channel.emailStatus;
1120
1122
  ops.push(...channel.ops);
1121
1123
  } else {
@@ -1125,7 +1127,9 @@ async function createRecord(deps, opts) {
1125
1127
  const score = scoreOf(deps, opts.type, candidate);
1126
1128
  if (score !== void 0) attrs.score = score;
1127
1129
  ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
1128
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1130
+ const guards = [...opts.guards ?? [], ...opts.id ? [{ ns: CRM_NS.record, id, exists: false }] : []];
1131
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId, ...guards.length ? { guards } : {} });
1132
+ if (duplicate && opts.id) return { id, duplicate, record: await mustGetRecord(deps, id) };
1129
1133
  return { id, duplicate, record: { id, ...attrs } };
1130
1134
  }
1131
1135
  async function updateRecord(deps, opts) {
@@ -1778,6 +1782,43 @@ async function saveConfig(deps, patch, opts = {}) {
1778
1782
  return { config: merged, duplicate };
1779
1783
  }
1780
1784
 
1785
+ // src/email-validation.ts
1786
+ function isEmailTierName(value, id) {
1787
+ return typeof value === "string" && !!value.trim() && value.trim() !== id && !/^(?:unknown|undefined|null|n\/a|(?:sku|price|tier|prod)_[\w-]+|[0-9a-f]{8}-[0-9a-f-]{27,})$/i.test(value.trim()) && !/[{}\r\n]/.test(value);
1788
+ }
1789
+ function validateEmailCopy(copy, options = {}) {
1790
+ const issues = [];
1791
+ const subject = typeof copy.subject === "string" ? copy.subject : "";
1792
+ const text = typeof copy.text === "string" ? copy.text : "";
1793
+ if (!subject.trim()) issues.push({ code: "subject-missing", message: "Add an email subject." });
1794
+ if (!text.trim()) issues.push({ code: "body-missing", message: "Add an email body." });
1795
+ if (/[\r\n]/.test(subject) || subject.length > 200) issues.push({ code: "subject-invalid", message: "Use a single-line subject of at most 200 characters." });
1796
+ if (text.length > 1e4) issues.push({ code: "body-invalid", message: "Keep the email body within 10,000 characters." });
1797
+ const combined = `${subject}
1798
+ ${text}`;
1799
+ if (/^\s*(?:\(\s*unused\s*:|Unused\.\s*Switched off\b|(?:TODO|TBD|PLACEHOLDER)\s*:|DRAFT\s*[-:]|\[\s*(?:draft|placeholder)\s*\]|do not (?:send|use) this (?:email|template))/im.test(combined)) {
1800
+ issues.push({ code: "internal-copy", message: "Replace internal draft or retirement notes with recipient-facing copy." });
1801
+ }
1802
+ const tokens = [...new Set([...combined.matchAll(/\{\{(\w+)\}\}/g)].map((match) => match[1]))];
1803
+ if (/[{}]/.test(combined.replace(/\{\{\w+\}\}/g, ""))) issues.push({ code: "placeholder-invalid", message: "Fix malformed placeholders; use {{variableName}}." });
1804
+ for (const variable of tokens) {
1805
+ if (options.allowedVariables && !options.allowedVariables.includes(variable)) issues.push({ code: "variable-unknown", variable, message: `This event does not supply {{${variable}}}.` });
1806
+ }
1807
+ if (options.values) {
1808
+ for (const variable of /* @__PURE__ */ new Set([...tokens, ...options.requiredVariables ?? []])) {
1809
+ const value = options.values[variable];
1810
+ if (typeof value !== "string" || !value.trim() && !options.optionalVariables?.includes(variable)) {
1811
+ issues.push({ code: "value-missing", variable, message: `Missing event value: ${variable}.` });
1812
+ } else if ((variable === "tierName" || variable === "tier") && !isEmailTierName(value, options.tierId)) {
1813
+ issues.push({ code: "tier-name-invalid", variable, message: "Resolve the membership tier's display name before sending." });
1814
+ } else if (/\{\{|\}\}/.test(value)) {
1815
+ issues.push({ code: "value-invalid", variable, message: `Unresolved placeholder in ${variable}.` });
1816
+ }
1817
+ }
1818
+ }
1819
+ return issues;
1820
+ }
1821
+
1781
1822
  // src/email.ts
1782
1823
  async function sendTemplatedEmail(deps, opts) {
1783
1824
  const { crm, db, now, newId } = resolveDeps(deps);
@@ -1786,7 +1827,8 @@ async function sendTemplatedEmail(deps, opts) {
1786
1827
  const config = await getConfig(deps);
1787
1828
  const stored = config?.emailTemplates[opts.templateId] ?? null;
1788
1829
  if (!stored || !stored.subject && !stored.text) return { sent: false, reason: "no_template_copy" };
1789
- if (!stored.enabled && !opts.force) return { sent: false, reason: "disabled" };
1830
+ if (typeof stored.enabled !== "boolean") return { sent: false, reason: "template-invalid" };
1831
+ if (stored.enabled !== true && !opts.force) return { sent: false, reason: "disabled" };
1790
1832
  const record = await mustGetRecord(deps, opts.recordId);
1791
1833
  const channels = await listChannels(deps, record.id);
1792
1834
  const channel = opts.channelId ? channels.find((c) => c.id === opts.channelId) : channels.find((c) => c.kind === "email" && c.isPrimary);
@@ -1805,8 +1847,10 @@ async function sendTemplatedEmail(deps, opts) {
1805
1847
  headers["List-Unsubscribe"] = `<${unsubscribeUrl}>`;
1806
1848
  headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
1807
1849
  }
1850
+ if (validateEmailCopy(stored, { allowedVariables: spec.vars, values: vars }).length) return { sent: false, reason: "template-invalid" };
1808
1851
  let subject = renderTemplate(stored.subject, vars);
1809
1852
  const text = renderTemplate(stored.text, vars);
1853
+ if (validateEmailCopy({ subject, text }, { allowedVariables: [] }).length) return { sent: false, reason: "template-invalid" };
1810
1854
  let to = channel.value;
1811
1855
  let redirected = false;
1812
1856
  let logOnly = !deps.sender;
@@ -1885,10 +1929,12 @@ async function recordCanEmail(deps, recordId, cls) {
1885
1929
  async function linkIdentity(deps, opts) {
1886
1930
  const { db, now } = resolveDeps(deps);
1887
1931
  const record = await mustGetRecord(deps, opts.recordId);
1932
+ if (record.clerkUserId) return { linked: true, clerkUserId: record.clerkUserId };
1888
1933
  const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1889
1934
  if (!email) throw new CrmInputError("record has no email to match on");
1890
- const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1891
- const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1935
+ const result = await db.query({ $users: { $: { where: { email }, limit: 2 } } });
1936
+ const users = result["$users"] ?? [];
1937
+ const user = users.length === 1 && !users[0]["deleted"] ? users[0] : void 0;
1892
1938
  if (!user) return { linked: false };
1893
1939
  const { duplicate } = await db.transact(
1894
1940
  [
@@ -1899,7 +1945,24 @@ async function linkIdentity(deps, opts) {
1899
1945
  attrs: { clerkUserId: user.id, updatedAt: now() }
1900
1946
  }
1901
1947
  ],
1902
- { mutationId: opts.mutationId }
1948
+ { mutationId: opts.mutationId, guards: [
1949
+ {
1950
+ ns: "$users",
1951
+ id: user.id,
1952
+ exists: true,
1953
+ equals: {
1954
+ email,
1955
+ ...user["deleted"] !== void 0 ? { deleted: user["deleted"] } : {}
1956
+ },
1957
+ ...user["deleted"] === void 0 ? { absent: ["deleted"] } : {}
1958
+ },
1959
+ {
1960
+ ns: CRM_NS.record,
1961
+ id: record.id,
1962
+ exists: true,
1963
+ ...record.clerkUserId === null ? { equals: { clerkUserId: null } } : { absent: ["clerkUserId"] }
1964
+ }
1965
+ ] }
1903
1966
  );
1904
1967
  return { linked: true, clerkUserId: user.id, duplicate };
1905
1968
  }
@@ -2240,7 +2303,7 @@ async function handleRecordsRoot(ctx, req, url) {
2240
2303
  type: str(body, "type"),
2241
2304
  input: obj(body, "input"),
2242
2305
  ownerId: optStr(body, "ownerId"),
2243
- stage: optStr(body, "stage"),
2306
+ stage: nullableStr(body, "stage"),
2244
2307
  mutationId: optStr(body, "mutationId")
2245
2308
  });
2246
2309
  return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);