@odla-ai/crm 0.4.0 → 0.6.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/README.md CHANGED
@@ -20,7 +20,11 @@ npm i @odla-ai/crm
20
20
  The CRM is a **schema + deny-all rules + a route factory + an admin UI kit** — not a service you run.
21
21
 
22
22
  - **Record types are configuration, not schema.** Every type shares one generic `crm_record` namespace: promoted columns for the hot paths every type has (name, stage + position, rank, score, contactability, billing cache), nine typed slot columns (`s1`–`s4`, `n1`–`n3`, `d1`–`d2`) that index each type's custom sortable/filterable fields, the complete field payload in a json column, and a denormalized FTS haystack rebuilt on every write.
23
- - **Tags and relations are natural-key join rows** (`recordId:tag`, `fromId:relation:toId`) — idempotent upserts that double as cohort provenance.
23
+ - **Tags and relations are natural-key join rows** (`recordId:tag`,
24
+ `fromId:relation:toId`) — idempotent upserts for human-curated cohorts and
25
+ graph edges. Machine federation identity and delivery state use separate
26
+ structured origin/delivery rows, so editing a display tag cannot break a
27
+ retry contract.
24
28
  - **Consent is a table-driven state machine.** Suppression is admin-sticky, an unsubscribe is undone only by the contact's own opt-in, hard bounces land from anywhere, and `unsubscribed` still receives transactional mail. Marketing sends carry `{{unsubscribeUrl}}` and RFC 8058 one-click headers automatically.
25
29
  - **All access is worker-mediated by design.** Slot mapping, searchText rebuilds, pipeline gates, and validation are functions of your config — CEL rules cannot express them — so every `crm_*` namespace installs deny-all and `createCrmRoutes` (admin key, behind your own `authorize`) is the only door.
26
30
  - **Zero runtime dependencies.** The db client and email transport are injected structurally: a real `@odla-ai/db` `AdminDb` and a thin wrapper over `@odla-ai/email`'s `sendMessage` satisfy the interfaces.
@@ -83,6 +87,19 @@ export default {
83
87
  };
84
88
  ```
85
89
 
90
+ Compose reusable and host-owned CRM modules before resolving them:
91
+
92
+ ```ts
93
+ import { composeCrmConfigs, defineCrm } from "@odla-ai/crm";
94
+
95
+ const crm = defineCrm(composeCrmConfigs(peopleConfig, portfolioConfig));
96
+ ```
97
+
98
+ Duplicate type, relation, or template ids fail instead of silently replacing
99
+ one module. A type may set `workspace: "portfolio"` (or another host-defined
100
+ string) as a generic UI grouping hint; core CRM CRUD and authorization do not
101
+ interpret that value.
102
+
86
103
  `GET /api/crm/discussion-references?q=…` searches product-owned records and
87
104
  activities; exact `kind` + `id` lookup proves the current row and parentage.
88
105
  Results contain canonical kind/id/label, bounded summary/status/destination,
@@ -170,13 +187,20 @@ design:
170
187
  renderSummary={({ query }) => <Summary total={query.page?.total ?? 0} />}
171
188
  renderMaster={({ defaultMaster }) => <BrandedRail>{defaultMaster}</BrandedRail>}
172
189
  renderDetailHeader={({ detail }) => <RecordHeading record={detail.record} />}
190
+ renderDetail={(context, defaultDetail) => (
191
+ <RelationshipProfile record={context.detail.record}>
192
+ {defaultDetail}
193
+ </RelationshipProfile>
194
+ )}
173
195
  />
174
196
  ```
175
197
 
176
198
  Record links, the mobile back control, and detail tabs become native anchors
177
199
  when their `hrefFor*` builders are supplied. Record panels mount only the
178
200
  active tab by default, preventing hidden communications or scheduling panels
179
- from fetching data.
201
+ from fetching data. `renderDetail` receives the fully composed default record
202
+ panel, so a host can wrap or replace the entire detail experience while CRM
203
+ continues to own loading, selection, mutation state, and tab composition.
180
204
 
181
205
  For records whose displayed pipeline mirrors another authoritative workflow,
182
206
  delegate transitions instead of calling the CRM route directly:
@@ -204,6 +228,7 @@ panels are neither rendered nor mounted.
204
228
  | Types, pipelines, gates, scorers, template contracts | Code — `defineCrm` (validated at boot) |
205
229
  | Template copy, enable flags, destination addresses | Data — the `crm_config` row (owner-editable) |
206
230
  | Records, tags, links, activities, channels, send audit, views | odla-db (`CRM_SCHEMA` namespaces) |
231
+ | Cross-system record identity and latest target delivery state | `crm_record_origin` and `crm_record_delivery` |
207
232
  | Money | Nowhere here — `BillingProvider` is an optional port an app-owned client or reusable provider package may implement. The record carries cache columns only. |
208
233
  | Meetings/scheduling | `@odla-ai/calendar` |
209
234
  | Clerk role changes | Your `onTransition` hooks (via `@odla-ai/auth-clerk`) |
@@ -211,6 +236,11 @@ panels are neither rendered nor mounted.
211
236
  ## Guarantees & limits
212
237
 
213
238
  - Every write accepts a `mutationId` for exactly-once application; webhook-style callers key on it (`{provider}:{eventId}`, `consent:{token}:{event}`, `email:{dedupeKey}`).
239
+ - `upsertRecordOrigin` binds one source site + source record id to one local
240
+ record and refuses remapping. `recordDeliveryAttempt` retains the latest
241
+ per-record/per-target status and bounded error while incrementing attempts.
242
+ `GET /api/crm/records/:id` includes `origins` and `deliveries`; the standard
243
+ record UI exposes them in a Network tab only when data exists.
214
244
  - Discussion reference projections are read-only and product-authorized; a
215
245
  stored ref or `odla-ref` link is navigation, never CRM mutation authority.
216
246
  - Send-path failure rows are written unconditionally, so a retry's success is never swallowed; dev environments redirect to `debugEmail` or fall back to log-only.
package/dist/index.cjs CHANGED
@@ -47,6 +47,7 @@ __export(index_exports, {
47
47
  canTransition: () => canTransition,
48
48
  channelKey: () => channelKey,
49
49
  compileList: () => compileList,
50
+ composeCrmConfigs: () => composeCrmConfigs,
50
51
  createCrmIntegration: () => createCrmIntegration,
51
52
  createCrmRoutes: () => createCrmRoutes,
52
53
  createRecord: () => createRecord,
@@ -62,6 +63,8 @@ __export(index_exports, {
62
63
  formatCrmDiscussionReference: () => formatCrmDiscussionReference,
63
64
  getConfig: () => getConfig,
64
65
  getRecord: () => getRecord,
66
+ getRecordByOrigin: () => getRecordByOrigin,
67
+ getRecordOrigin: () => getRecordOrigin,
65
68
  initialStage: () => initialStage,
66
69
  linkIdentity: () => linkIdentity,
67
70
  lintTemplate: () => lintTemplate,
@@ -69,6 +72,8 @@ __export(index_exports, {
69
72
  listChannels: () => listChannels,
70
73
  listEmailLog: () => listEmailLog,
71
74
  listLinks: () => listLinks,
75
+ listRecordDeliveries: () => listRecordDeliveries,
76
+ listRecordOrigins: () => listRecordOrigins,
72
77
  listRecords: () => listRecords,
73
78
  listTags: () => listTags,
74
79
  listTasks: () => listTasks,
@@ -82,6 +87,9 @@ __export(index_exports, {
82
87
  rebalancePlan: () => rebalancePlan,
83
88
  rebalanceRanks: () => rebalanceRanks,
84
89
  recordCanEmail: () => recordCanEmail,
90
+ recordDeliveryAttempt: () => recordDeliveryAttempt,
91
+ recordDeliveryKey: () => recordDeliveryKey,
92
+ recordOriginKey: () => recordOriginKey,
85
93
  removeLink: () => removeLink,
86
94
  removeTag: () => removeTag,
87
95
  renderTemplate: () => renderTemplate,
@@ -100,7 +108,8 @@ __export(index_exports, {
100
108
  typeSummary: () => typeSummary,
101
109
  updateRecord: () => updateRecord,
102
110
  updateTask: () => updateTask,
103
- updateView: () => updateView
111
+ updateView: () => updateView,
112
+ upsertRecordOrigin: () => upsertRecordOrigin
104
113
  });
105
114
  module.exports = __toCommonJS(index_exports);
106
115
 
@@ -113,7 +122,9 @@ var CRM_NS = {
113
122
  channel: "crm_contact_channel",
114
123
  emailLog: "crm_email_log",
115
124
  view: "crm_view",
116
- config: "crm_config"
125
+ config: "crm_config",
126
+ origin: "crm_record_origin",
127
+ delivery: "crm_record_delivery"
117
128
  };
118
129
  var CRM_SLOTS = ["s1", "s2", "s3", "s4", "n1", "n2", "n3", "d1", "d2"];
119
130
  var CONSENT_STATES = ["subscribed", "unsubscribed", "bounced", "suppressed"];
@@ -311,6 +322,37 @@ var CRM_SCHEMA = {
311
322
  settings: a("json"),
312
323
  updatedAt: idx("date")
313
324
  }
325
+ },
326
+ [CRM_NS.origin]: {
327
+ attrs: {
328
+ // One upstream record maps to one local record. The structured source
329
+ // survives tag edits and supports more than one upstream site.
330
+ key: uniq("string"),
331
+ // `${sourceId}:${sourceRecordId}`
332
+ recordId: idx("string"),
333
+ sourceId: idx("string"),
334
+ sourceRecordId: idx("string"),
335
+ sourceUrl: opt("string"),
336
+ payloadVersion: idx("number"),
337
+ firstReceivedAt: idx("date"),
338
+ lastReceivedAt: idx("date")
339
+ }
340
+ },
341
+ [CRM_NS.delivery]: {
342
+ attrs: {
343
+ // The latest delivery state for one local record → target edge.
344
+ key: uniq("string"),
345
+ // `${recordId}:${targetId}`
346
+ recordId: idx("string"),
347
+ targetId: idx("string"),
348
+ remoteRecordId: idx("string", true),
349
+ status: idx("string"),
350
+ attempts: idx("number"),
351
+ payloadVersion: idx("number"),
352
+ lastAttemptAt: idx("date"),
353
+ deliveredAt: idx("date", true),
354
+ error: opt("string")
355
+ }
314
356
  }
315
357
  },
316
358
  links: {}
@@ -520,6 +562,9 @@ function fail(path, message) {
520
562
  function checkType(typeName, def) {
521
563
  const at = `types.${typeName}`;
522
564
  if (!NAME_RE.test(typeName)) fail(at, "must match /^[a-z][a-z0-9_-]*$/");
565
+ if (def.workspace != null && !NAME_RE.test(def.workspace)) {
566
+ fail(`${at}.workspace`, "must match /^[a-z][a-z0-9_-]*$/");
567
+ }
523
568
  const claimed = /* @__PURE__ */ new Map();
524
569
  for (const [fieldName, field] of Object.entries(def.fields)) {
525
570
  const fat = `${at}.fields.${fieldName}`;
@@ -600,6 +645,28 @@ ${tpl.defaults.text}`, tpl.vars);
600
645
  stageIndex: (name, stage) => stageIndexOf(type(name), stage)
601
646
  };
602
647
  }
648
+ function composeCrmConfigs(...configs) {
649
+ if (configs.length === 0) throw new Error("composeCrmConfigs: at least one config is required");
650
+ const result = { types: {} };
651
+ const merge = (kind, target, source) => {
652
+ for (const [id, value] of Object.entries(source ?? {})) {
653
+ if (Object.hasOwn(target, id)) throw new Error(`composeCrmConfigs: duplicate ${kind} "${id}"`);
654
+ target[id] = value;
655
+ }
656
+ };
657
+ for (const config of configs) {
658
+ merge("type", result.types, config.types);
659
+ if (config.relations) {
660
+ result.relations ??= {};
661
+ merge("relation", result.relations, config.relations);
662
+ }
663
+ if (config.templates) {
664
+ result.templates ??= {};
665
+ merge("template", result.templates, config.templates);
666
+ }
667
+ }
668
+ return result;
669
+ }
603
670
 
604
671
  // src/discussion-reference.ts
605
672
  var CRM_DISCUSSION_REFERENCE_KINDS = [
@@ -1186,6 +1253,129 @@ async function listLinks(deps, recordId) {
1186
1253
  return (result[CRM_NS.link] ?? []).map((row) => row);
1187
1254
  }
1188
1255
 
1256
+ // src/provenance.ts
1257
+ var SOURCE_ID = /^[a-z0-9][a-z0-9-]{1,127}$/;
1258
+ var TARGET_ID = SOURCE_ID;
1259
+ function required(value, label, max = 512) {
1260
+ const normalized = value.trim();
1261
+ if (!normalized || normalized.length > max) throw new CrmInputError(`${label} must be 1\u2013${max} characters`);
1262
+ return normalized;
1263
+ }
1264
+ function recordOriginKey(sourceId, sourceRecordId) {
1265
+ const source = required(sourceId, "sourceId", 128);
1266
+ const record = required(sourceRecordId, "sourceRecordId");
1267
+ if (!SOURCE_ID.test(source)) throw new CrmInputError("sourceId must be a lowercase app slug");
1268
+ return `${source}:${record}`;
1269
+ }
1270
+ async function getRecordOrigin(deps, sourceId, sourceRecordId) {
1271
+ const { db } = resolveDeps(deps);
1272
+ const key = recordOriginKey(sourceId, sourceRecordId);
1273
+ const result = await db.query({ [CRM_NS.origin]: { $: { where: { key }, limit: 1 } } });
1274
+ return (result[CRM_NS.origin] ?? [])[0] ?? null;
1275
+ }
1276
+ async function getRecordByOrigin(deps, sourceId, sourceRecordId) {
1277
+ const origin = await getRecordOrigin(deps, sourceId, sourceRecordId);
1278
+ return origin ? getRecord(deps, origin.recordId) : null;
1279
+ }
1280
+ async function upsertRecordOrigin(deps, opts) {
1281
+ const { db, now } = resolveDeps(deps);
1282
+ await mustGetRecord(deps, opts.recordId);
1283
+ const key = recordOriginKey(opts.sourceId, opts.sourceRecordId);
1284
+ if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {
1285
+ throw new CrmInputError("payloadVersion must be a positive integer");
1286
+ }
1287
+ const sourceUrl = opts.sourceUrl == null ? void 0 : required(opts.sourceUrl, "sourceUrl", 2048);
1288
+ const existing = await getRecordOrigin(deps, opts.sourceId, opts.sourceRecordId);
1289
+ if (existing && existing.recordId !== opts.recordId) {
1290
+ throw new CrmInputError("upstream record is already bound to another local record");
1291
+ }
1292
+ const at = now();
1293
+ const attrs = {
1294
+ key,
1295
+ recordId: opts.recordId,
1296
+ sourceId: opts.sourceId,
1297
+ sourceRecordId: opts.sourceRecordId,
1298
+ payloadVersion: opts.payloadVersion,
1299
+ firstReceivedAt: existing?.firstReceivedAt ?? at,
1300
+ lastReceivedAt: at,
1301
+ ...sourceUrl ? { sourceUrl } : {}
1302
+ };
1303
+ const { duplicate } = await db.transact(
1304
+ [{ t: "update", ns: CRM_NS.origin, id: { ns: CRM_NS.origin, attr: "key", value: key }, attrs }],
1305
+ { mutationId: opts.mutationId }
1306
+ );
1307
+ return {
1308
+ duplicate,
1309
+ origin: {
1310
+ id: existing?.id ?? key,
1311
+ ...attrs
1312
+ }
1313
+ };
1314
+ }
1315
+ async function listRecordOrigins(deps, recordId) {
1316
+ const { db } = resolveDeps(deps);
1317
+ const result = await db.query({
1318
+ [CRM_NS.origin]: { $: { where: { recordId }, order: { firstReceivedAt: "asc" }, limit: 200 } }
1319
+ });
1320
+ return result[CRM_NS.origin] ?? [];
1321
+ }
1322
+ function recordDeliveryKey(recordId, targetId) {
1323
+ const record = required(recordId, "recordId");
1324
+ const target = required(targetId, "targetId", 128);
1325
+ if (!TARGET_ID.test(target)) throw new CrmInputError("targetId must be a lowercase app slug");
1326
+ return `${record}:${target}`;
1327
+ }
1328
+ async function recordDeliveryAttempt(deps, opts) {
1329
+ const { db, now } = resolveDeps(deps);
1330
+ await mustGetRecord(deps, opts.recordId);
1331
+ const key = recordDeliveryKey(opts.recordId, opts.targetId);
1332
+ if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {
1333
+ throw new CrmInputError("payloadVersion must be a positive integer");
1334
+ }
1335
+ const found = await db.query({ [CRM_NS.delivery]: { $: { where: { key }, limit: 1 } } });
1336
+ const existing = (found[CRM_NS.delivery] ?? [])[0];
1337
+ const at = now();
1338
+ const remoteRecordId = opts.remoteRecordId == null ? existing?.remoteRecordId : required(opts.remoteRecordId, "remoteRecordId");
1339
+ const error = opts.error == null ? void 0 : required(opts.error, "error", 1e3);
1340
+ const attrs = {
1341
+ key,
1342
+ recordId: opts.recordId,
1343
+ targetId: opts.targetId,
1344
+ status: opts.status,
1345
+ attempts: (existing?.attempts ?? 0) + 1,
1346
+ payloadVersion: opts.payloadVersion,
1347
+ lastAttemptAt: at,
1348
+ ...remoteRecordId ? { remoteRecordId } : {},
1349
+ ...opts.status === "delivered" ? { deliveredAt: at } : existing?.deliveredAt ? { deliveredAt: existing.deliveredAt } : {},
1350
+ ...error ? { error } : {}
1351
+ };
1352
+ const ref = { ns: CRM_NS.delivery, attr: "key", value: key };
1353
+ const ops = [{ t: "update", ns: CRM_NS.delivery, id: ref, attrs }];
1354
+ if (opts.status === "delivered" && existing?.error) {
1355
+ ops.push({ t: "retract", ns: CRM_NS.delivery, id: ref, attrs: ["error"] });
1356
+ }
1357
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1358
+ return {
1359
+ duplicate,
1360
+ delivery: {
1361
+ id: existing?.id ?? key,
1362
+ ...attrs
1363
+ }
1364
+ };
1365
+ }
1366
+ async function listRecordDeliveries(deps, filter) {
1367
+ if (!filter.recordId && !filter.targetId) throw new CrmInputError("recordId or targetId is required");
1368
+ const { db } = resolveDeps(deps);
1369
+ const where = {
1370
+ ...filter.recordId ? { recordId: required(filter.recordId, "recordId") } : {},
1371
+ ...filter.targetId ? { targetId: required(filter.targetId, "targetId", 128) } : {}
1372
+ };
1373
+ const result = await db.query({
1374
+ [CRM_NS.delivery]: { $: { where, order: { lastAttemptAt: "desc" }, limit: 500 } }
1375
+ });
1376
+ return result[CRM_NS.delivery] ?? [];
1377
+ }
1378
+
1189
1379
  // src/activities.ts
1190
1380
  var rowToActivity = (row) => row;
1191
1381
  async function addActivity(deps, opts) {
@@ -1903,12 +2093,14 @@ async function handleRecordItem(ctx, req, id) {
1903
2093
  if (req.method === "GET") {
1904
2094
  const record = await getRecord(ctx.deps, id);
1905
2095
  if (!record) throw new CrmNotFoundError("record");
1906
- const [tags, channels, links] = await Promise.all([
2096
+ const [tags, channels, links, origins, deliveries] = await Promise.all([
1907
2097
  listTags(ctx.deps, id),
1908
2098
  listChannels(ctx.deps, id),
1909
- listLinks(ctx.deps, id)
2099
+ listLinks(ctx.deps, id),
2100
+ listRecordOrigins(ctx.deps, id),
2101
+ listRecordDeliveries(ctx.deps, { recordId: id })
1910
2102
  ]);
1911
- return json({ record, tags, channels, links });
2103
+ return json({ record, tags, channels, links, origins, deliveries });
1912
2104
  }
1913
2105
  if (req.method === "PATCH") {
1914
2106
  const body = await readJson(req);