@odla-ai/crm 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -24,7 +24,7 @@ The CRM is a **schema + deny-all rules + a route factory + an admin UI kit** —
24
24
  import { defineCrm, createCrmRoutes } from "@odla-ai/crm";
25
25
  import { init } from "@odla-ai/db";
26
26
 
27
- const crm = defineCrm({
27
+ export const crm = defineCrm({
28
28
  types: {
29
29
  person: {
30
30
  label: "Person",
@@ -53,10 +53,6 @@ const crm = defineCrm({
53
53
  },
54
54
  });
55
55
 
56
- // Provision once (the odla CLI automates this):
57
- // POST crm.schema → /app/:id/schema
58
- // crm.rules → /app/:id/admin/rules
59
-
60
56
  const db = init({ appId, adminToken, endpoint }); // @odla-ai/db admin client
61
57
  const crmRoutes = createCrmRoutes({
62
58
  crm,
@@ -75,6 +71,31 @@ export default {
75
71
  };
76
72
  ```
77
73
 
74
+ Put the resolved CRM in an app module both the Worker and checked-in odla
75
+ config can import, then declare the project-specific integration:
76
+
77
+ ```ts
78
+ // odla.config.mjs
79
+ import { createCrmIntegration } from "@odla-ai/crm";
80
+ import { crm } from "./src/crm.js";
81
+
82
+ export default {
83
+ app: { id: "my-app", name: "My App" },
84
+ services: ["db"],
85
+ integrations: [createCrmIntegration(crm, {
86
+ basePath: "/api/crm",
87
+ notificationEmail: "owner@example.com",
88
+ })],
89
+ links: { dev: "https://dev.example.com" },
90
+ };
91
+ ```
92
+
93
+ `odla-ai provision` collision-checks and merges the CRM schema/rules, then
94
+ creates `crm_config` only when absent. `odla-ai doctor` checks the composed
95
+ namespaces/rules/seed contract offline; `odla-ai smoke` uses `links.<env>` to
96
+ verify the mounted records route returns `401` without credentials. Mounting
97
+ `createCrmRoutes` and supplying `authorize` remain app-owned source work.
98
+
78
99
  And the admin surface, from `@odla-ai/crm/ui` (React or Preact via compat, `--ui-*` app-tier styling):
79
100
 
80
101
  ```tsx
@@ -100,7 +121,7 @@ function People() {
100
121
  | Types, pipelines, gates, scorers, template contracts | Code — `defineCrm` (validated at boot) |
101
122
  | Template copy, enable flags, destination addresses | Data — the `crm_config` row (owner-editable) |
102
123
  | Records, tags, links, activities, channels, send audit, views | odla-db (`CRM_SCHEMA` namespaces) |
103
- | Money | Nowhere here — `BillingProvider` is a declared port; the `@odla-ai/stripe` adapter is the next milestone. The record carries cache columns only. |
124
+ | Money | Nowhere here — `BillingProvider` is an optional port an app-owned client or reusable provider package may implement. The record carries cache columns only. |
104
125
  | Meetings/scheduling | `@odla-ai/calendar` |
105
126
  | Clerk role changes | Your `onTransition` hooks (via `@odla-ai/auth-clerk`) |
106
127
 
package/dist/index.cjs CHANGED
@@ -46,6 +46,7 @@ __export(index_exports, {
46
46
  canTransition: () => canTransition,
47
47
  channelKey: () => channelKey,
48
48
  compileList: () => compileList,
49
+ createCrmIntegration: () => createCrmIntegration,
49
50
  createCrmRoutes: () => createCrmRoutes,
50
51
  createRecord: () => createRecord,
51
52
  crmIntegration: () => crmIntegration,
@@ -171,6 +172,10 @@ var CRM_SCHEMA = {
171
172
  entities: {
172
173
  [CRM_NS.record]: {
173
174
  attrs: {
175
+ // Entity ids are not attributes in odla-db, so `where: { id }` matches
176
+ // nothing unless the id is mirrored as a written attr — the getRecord /
177
+ // tag-filter / neighbor reads all filter by id. Mirror it as unique.
178
+ id: uniq("string"),
174
179
  type: idx("string"),
175
180
  name: idx("string"),
176
181
  primaryEmail: idx("string", true),
@@ -225,6 +230,8 @@ var CRM_SCHEMA = {
225
230
  },
226
231
  [CRM_NS.activity]: {
227
232
  attrs: {
233
+ id: uniq("string"),
234
+ // mirrored so updateTask can read one by id
228
235
  recordId: idx("string"),
229
236
  kind: idx("string"),
230
237
  body: a("string"),
@@ -274,6 +281,8 @@ var CRM_SCHEMA = {
274
281
  },
275
282
  [CRM_NS.view]: {
276
283
  attrs: {
284
+ id: uniq("string"),
285
+ // mirrored so getView/updateView can read one by id
277
286
  name: a("string"),
278
287
  type: idx("string"),
279
288
  ownerId: idx("string", true),
@@ -360,6 +369,25 @@ function canTransition(def, record, to) {
360
369
  return null;
361
370
  }
362
371
 
372
+ // src/template.ts
373
+ var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
374
+ function renderTemplate(template, vars) {
375
+ return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
376
+ }
377
+ function templateVars(template) {
378
+ const seen = /* @__PURE__ */ new Set();
379
+ for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
380
+ return [...seen];
381
+ }
382
+ function lintTemplate(template, knownVars) {
383
+ const used = templateVars(template);
384
+ const known = new Set(knownVars);
385
+ return {
386
+ unknown: used.filter((v) => !known.has(v)),
387
+ unused: knownVars.filter((v) => !used.includes(v))
388
+ };
389
+ }
390
+
363
391
  // src/validate.ts
364
392
  var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
365
393
  var STRINGISH = /* @__PURE__ */ new Set(["string", "email", "url", "enum"]);
@@ -450,10 +478,21 @@ function prepare(def, input, existing) {
450
478
  fields,
451
479
  searchText: searchTextFor(def, name, primaryEmail, fields)
452
480
  };
453
- if (def.emailField) attrs.primaryEmail = primaryEmail;
454
- for (const [fieldName, field] of Object.entries(def.fields))
455
- if (field.slot) attrs[field.slot] = fields[fieldName] ?? null;
456
- return { ok: true, attrs };
481
+ const retract = [];
482
+ const clear = (column) => {
483
+ if (existing) retract.push(column);
484
+ };
485
+ if (def.emailField) {
486
+ if (primaryEmail === null) clear("primaryEmail");
487
+ else attrs.primaryEmail = primaryEmail;
488
+ }
489
+ for (const [fieldName, field] of Object.entries(def.fields)) {
490
+ if (!field.slot) continue;
491
+ const value = fields[fieldName];
492
+ if (empty(field, value)) clear(field.slot);
493
+ else attrs[field.slot] = value;
494
+ }
495
+ return { ok: true, attrs, retract };
457
496
  }
458
497
 
459
498
  // src/config.ts
@@ -534,6 +573,11 @@ function defineCrm(config) {
534
573
  if (tpl.class !== "transactional" && tpl.class !== "marketing")
535
574
  fail(at, `class must be transactional|marketing`);
536
575
  for (const v of tpl.vars) if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v)) fail(at, `bad var "${v}"`);
576
+ if (tpl.defaults) {
577
+ const lint = lintTemplate(`${tpl.defaults.subject}
578
+ ${tpl.defaults.text}`, tpl.vars);
579
+ if (lint.unknown.length) fail(at, `defaults reference unknown vars: ${lint.unknown.join(", ")}`);
580
+ }
537
581
  }
538
582
  const type = (name) => {
539
583
  const def = config.types[name];
@@ -681,25 +725,6 @@ function canEmail(consent, cls) {
681
725
  return true;
682
726
  }
683
727
 
684
- // src/template.ts
685
- var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
686
- function renderTemplate(template, vars) {
687
- return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
688
- }
689
- function templateVars(template) {
690
- const seen = /* @__PURE__ */ new Set();
691
- for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
692
- return [...seen];
693
- }
694
- function lintTemplate(template, knownVars) {
695
- const used = templateVars(template);
696
- const known = new Set(knownVars);
697
- return {
698
- unknown: used.filter((v) => !known.has(v)),
699
- unused: knownVars.filter((v) => !used.includes(v))
700
- };
701
- }
702
-
703
728
  // src/channels.ts
704
729
  var channelKey = (recordId, kind, value) => `${recordId}:${kind}:${value}`;
705
730
  function foldEmailStatus(consent) {
@@ -777,6 +802,29 @@ async function applyConsent(deps, opts) {
777
802
  return { state: outcome.state, recordId: channel.recordId, duplicate };
778
803
  }
779
804
 
805
+ // src/write-ops.ts
806
+ function patchOps(ns, id, patch, alsoClear = []) {
807
+ const attrs = {};
808
+ const retract = [...alsoClear];
809
+ for (const [key, value] of Object.entries(patch)) {
810
+ if (value === null) retract.push(key);
811
+ else if (value !== void 0) attrs[key] = value;
812
+ }
813
+ const ops = [];
814
+ if (Object.keys(attrs).length > 0) ops.push({ t: "update", ns, id, attrs });
815
+ if (retract.length > 0) ops.push({ t: "retract", ns, id, attrs: retract });
816
+ return ops;
817
+ }
818
+ function applyPatch(base, patch, alsoClear = []) {
819
+ const out = { ...base };
820
+ for (const [key, value] of Object.entries(patch)) {
821
+ if (value === null) delete out[key];
822
+ else if (value !== void 0) out[key] = value;
823
+ }
824
+ for (const key of alsoClear) delete out[key];
825
+ return out;
826
+ }
827
+
780
828
  // src/records.ts
781
829
  function rowToRecord(row) {
782
830
  const record = row;
@@ -833,6 +881,8 @@ async function createRecord(deps, opts) {
833
881
  const at = now();
834
882
  const stage = opts.stage ?? crm.initialStage(opts.type);
835
883
  const attrs = {
884
+ id,
885
+ // mirror the entity id as an attr so `where: { id }` reads can find it
836
886
  type: opts.type,
837
887
  ...prepared.attrs,
838
888
  archived: false,
@@ -867,32 +917,31 @@ async function updateRecord(deps, opts) {
867
917
  const existing = await mustGetRecord(deps, opts.id);
868
918
  const prepared = crm.prepare(existing.type, opts.input, existing);
869
919
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
870
- const attrs = { ...prepared.attrs, updatedAt: now() };
871
- if (opts.ownerId !== void 0) attrs.ownerId = opts.ownerId;
872
- const ops = [];
920
+ const patch = { ...prepared.attrs, updatedAt: now(), ownerId: opts.ownerId };
921
+ const channelOps = [];
873
922
  if (crm.type(existing.type).emailField) {
874
923
  const nextEmail = prepared.attrs["primaryEmail"] ?? null;
875
924
  if (nextEmail !== (existing.primaryEmail ?? null)) {
876
925
  const channels = await listChannels(deps, existing.id);
877
926
  const channel = emailChannelOps(deps, existing.id, nextEmail, channels);
878
- attrs.emailStatus = channel.emailStatus;
879
- ops.push(...channel.ops);
927
+ patch.emailStatus = channel.emailStatus;
928
+ channelOps.push(...channel.ops);
880
929
  }
881
930
  }
882
- const candidate = { ...existing, ...attrs };
931
+ const candidate = { ...existing, ...prepared.attrs };
883
932
  const score = scoreOf(deps, existing.type, candidate);
884
- if (score !== void 0) attrs.score = score;
885
- ops.unshift({ t: "update", ns: CRM_NS.record, id: existing.id, attrs });
933
+ if (score !== void 0) patch.score = score;
934
+ const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];
886
935
  const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
887
- return { record: { ...existing, ...attrs }, duplicate };
936
+ return { record: applyPatch(existing, patch, prepared.retract), duplicate };
888
937
  }
889
938
  async function setArchived(deps, opts) {
890
939
  const { db, now } = resolveDeps(deps);
891
940
  await mustGetRecord(deps, opts.id);
892
941
  const at = now();
893
- const attrs = opts.archived ? { archived: true, archivedAt: at, updatedAt: at } : { archived: false, archivedAt: null, updatedAt: at };
942
+ const patch = opts.archived ? { archived: true, archivedAt: at, updatedAt: at } : { archived: false, archivedAt: null, updatedAt: at };
894
943
  const { duplicate } = await db.transact(
895
- [{ t: "update", ns: CRM_NS.record, id: opts.id, attrs }],
944
+ patchOps(CRM_NS.record, opts.id, patch),
896
945
  { mutationId: opts.mutationId }
897
946
  );
898
947
  return { duplicate };
@@ -911,13 +960,16 @@ async function setStage(deps, opts) {
911
960
  stageChangedAt: at,
912
961
  updatedAt: at
913
962
  };
963
+ const activityId = newId();
914
964
  const ops = [
915
965
  { t: "update", ns: CRM_NS.record, id: record.id, attrs },
916
966
  {
917
967
  t: "update",
918
968
  ns: CRM_NS.activity,
919
- id: newId(),
969
+ id: activityId,
920
970
  attrs: {
971
+ id: activityId,
972
+ // mirror the entity id so the activity is readable by id
921
973
  recordId: record.id,
922
974
  kind: "stage_change",
923
975
  body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
@@ -1096,6 +1148,8 @@ async function addActivity(deps, opts) {
1096
1148
  await mustGetRecord(deps, opts.recordId);
1097
1149
  const id = newId();
1098
1150
  const attrs = {
1151
+ id,
1152
+ // mirror the entity id so updateTask's `where: { id }` read can find it
1099
1153
  recordId: opts.recordId,
1100
1154
  kind: opts.kind,
1101
1155
  body,
@@ -1121,25 +1175,25 @@ async function updateTask(deps, opts) {
1121
1175
  if (!row) throw new CrmNotFoundError("activity");
1122
1176
  const activity = rowToActivity(row);
1123
1177
  if (activity.kind !== "task") throw new CrmInputError("only tasks can be updated");
1124
- const attrs = {};
1178
+ const patch = {};
1125
1179
  if (opts.status !== void 0) {
1126
1180
  if (!TASK_STATUSES.includes(opts.status)) throw new CrmInputError(`unknown status "${opts.status}"`);
1127
- attrs.status = opts.status;
1128
- attrs.completedAt = opts.status === "done" ? now() : null;
1181
+ patch.status = opts.status;
1182
+ patch.completedAt = opts.status === "done" ? now() : null;
1129
1183
  }
1130
- if (opts.dueAt !== void 0) attrs.dueAt = opts.dueAt;
1131
- if (opts.assigneeId !== void 0) attrs.assigneeId = opts.assigneeId;
1132
- if (opts.waitingOn !== void 0) attrs.waitingOn = opts.waitingOn;
1184
+ if (opts.dueAt !== void 0) patch.dueAt = opts.dueAt;
1185
+ if (opts.assigneeId !== void 0) patch.assigneeId = opts.assigneeId;
1186
+ if (opts.waitingOn !== void 0) patch.waitingOn = opts.waitingOn;
1133
1187
  if (opts.body !== void 0) {
1134
1188
  const body = opts.body.trim();
1135
1189
  if (!body) throw new CrmInputError("body is required");
1136
- attrs.body = body;
1190
+ patch.body = body;
1137
1191
  }
1138
- if (Object.keys(attrs).length === 0) throw new CrmInputError("nothing to update");
1139
- const { duplicate } = await db.transact([{ t: "update", ns: CRM_NS.activity, id: opts.id, attrs }], {
1192
+ if (Object.keys(patch).length === 0) throw new CrmInputError("nothing to update");
1193
+ const { duplicate } = await db.transact(patchOps(CRM_NS.activity, opts.id, patch), {
1140
1194
  mutationId: opts.mutationId
1141
1195
  });
1142
- return { activity: { ...activity, ...attrs }, duplicate };
1196
+ return { activity: applyPatch(activity, patch), duplicate };
1143
1197
  }
1144
1198
  async function listActivities(deps, opts) {
1145
1199
  const { db } = resolveDeps(deps);
@@ -1200,6 +1254,8 @@ async function saveView(deps, opts) {
1200
1254
  ns: CRM_NS.view,
1201
1255
  id,
1202
1256
  attrs: {
1257
+ id,
1258
+ // mirror the entity id so getView/updateView can read one by id
1203
1259
  name: opts.spec.name.trim(),
1204
1260
  type: opts.spec.type,
1205
1261
  ownerId: opts.ownerId,
@@ -1300,6 +1356,9 @@ async function saveConfig(deps, patch, opts = {}) {
1300
1356
  throw new CrmInputError(`template "${id}": text must be a string`);
1301
1357
  if (tpl.enabled !== void 0 && typeof tpl.enabled !== "boolean")
1302
1358
  throw new CrmInputError(`template "${id}": enabled must be a boolean`);
1359
+ const copy = [tpl.subject, tpl.text].filter((value) => typeof value === "string").join("\n");
1360
+ const unknown = lintTemplate(copy, declared[id].vars).unknown;
1361
+ if (unknown.length) throw new CrmInputError(`template "${id}": unknown vars ${unknown.join(", ")}`);
1303
1362
  }
1304
1363
  const existing = await getConfig(deps);
1305
1364
  const base = existing ?? {
@@ -1323,23 +1382,17 @@ async function saveConfig(deps, patch, opts = {}) {
1323
1382
  settings: patch.settings !== void 0 ? patch.settings : base.settings,
1324
1383
  updatedAt: now()
1325
1384
  };
1385
+ const write = {
1386
+ key: CONFIG_KEY,
1387
+ notificationEmail: merged.notificationEmail ?? null,
1388
+ replyTo: merged.replyTo ?? null,
1389
+ debugEmail: merged.debugEmail ?? null,
1390
+ emailTemplates: merged.emailTemplates,
1391
+ settings: merged.settings,
1392
+ updatedAt: merged.updatedAt
1393
+ };
1326
1394
  const { duplicate } = await db.transact(
1327
- [
1328
- {
1329
- t: "update",
1330
- ns: CRM_NS.config,
1331
- id: { ns: CRM_NS.config, attr: "key", value: CONFIG_KEY },
1332
- attrs: {
1333
- key: CONFIG_KEY,
1334
- notificationEmail: merged.notificationEmail ?? null,
1335
- replyTo: merged.replyTo ?? null,
1336
- debugEmail: merged.debugEmail ?? null,
1337
- emailTemplates: merged.emailTemplates,
1338
- settings: merged.settings,
1339
- updatedAt: merged.updatedAt
1340
- }
1341
- }
1342
- ],
1395
+ patchOps(CRM_NS.config, { ns: CRM_NS.config, attr: "key", value: CONFIG_KEY }, write),
1343
1396
  { mutationId: opts.mutationId }
1344
1397
  );
1345
1398
  return { config: merged, duplicate };
@@ -2166,7 +2219,7 @@ var crmIntegration = {
2166
2219
  provision: {
2167
2220
  human: [
2168
2221
  "None for the core install \u2014 records/pipelines/email-consent need no external accounts.",
2169
- "When billing lands (@odla-ai/stripe): paste the printed webhook URL into the Stripe dashboard and vault the sk_/whsec_ secrets (Studio, write-only)."
2222
+ "If the app injects billing, configure that provider's webhook and vault secrets according to the app-owned adapter."
2170
2223
  ],
2171
2224
  cli: [
2172
2225
  "POST the merged CRM_SCHEMA to /app/:id/schema.",
@@ -2175,10 +2228,36 @@ var crmIntegration = {
2175
2228
  ],
2176
2229
  doctor: [
2177
2230
  "Every crm_* namespace has rules installed (deny-all: no rule = exposed to nothing, but assert explicitly).",
2178
- "The crm_config row exists and its emailTemplates parse against the code-declared registry.",
2179
- "lintTemplate reports no unknown {{vars}} in stored template copy.",
2231
+ "The guarded crm_config seed targets the declared-unique crm_config.key attribute.",
2232
+ "Code-declared template defaults have no unknown {{vars}}; owner-edited copies are checked when saved."
2233
+ ],
2234
+ smoke: [
2180
2235
  "A GET probe of <basePath>/records without credentials answers 401 (routes mounted, authorize enforced)."
2181
2236
  ]
2182
2237
  }
2183
2238
  };
2239
+ function createCrmIntegration(crm, options = {}) {
2240
+ const basePath = options.basePath ?? "/api/crm";
2241
+ if (!/^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/.test(basePath) || basePath.endsWith("/")) {
2242
+ throw new Error("createCrmIntegration: basePath must be an absolute path without a trailing slash");
2243
+ }
2244
+ const attrs = {
2245
+ emailTemplates: defaultTemplates(crm),
2246
+ settings: options.settings ?? {},
2247
+ updatedAt: options.now ?? Date.now()
2248
+ };
2249
+ if (options.notificationEmail !== void 0) attrs.notificationEmail = options.notificationEmail;
2250
+ if (options.replyTo !== void 0) attrs.replyTo = options.replyTo;
2251
+ if (options.debugEmail !== void 0) attrs.debugEmail = options.debugEmail;
2252
+ return {
2253
+ ...crmIntegration,
2254
+ seeds: [{
2255
+ id: "config",
2256
+ ns: CRM_NS.config,
2257
+ key: { attr: "key", value: CONFIG_KEY },
2258
+ attrs
2259
+ }],
2260
+ probes: [{ path: `${basePath}/records`, expectedStatus: 401 }]
2261
+ };
2262
+ }
2184
2263
  //# sourceMappingURL=index.cjs.map