@odla-ai/crm 0.3.2 → 0.4.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
@@ -65,6 +65,11 @@ const crmRoutes = createCrmRoutes({
65
65
  crm,
66
66
  db,
67
67
  authorize: async (req) => ((await isAdmin(req)) ? { userId: await adminId(req) } : null),
68
+ // Registry-owned read assertion; it cannot authorize a CRM mutation.
69
+ authorizeDiscussionReferences: async (req) => {
70
+ const actor = await verifyRegistryCrmReference(req);
71
+ return actor ? { userId: actor.id, discussionReferenceScope: "all" } : null;
72
+ },
68
73
  envName: env.ENV_NAME, // only exactly "production" delivers real email
69
74
  baseUrl: "https://app.example.com",
70
75
  from: env.EMAIL_FROM,
@@ -78,6 +83,16 @@ export default {
78
83
  };
79
84
  ```
80
85
 
86
+ `GET /api/crm/discussion-references?q=…` searches product-owned records and
87
+ activities; exact `kind` + `id` lookup proves the current row and parentage.
88
+ Results contain canonical kind/id/label, bounded summary/status/destination,
89
+ and a same-origin `odla-ref` link that opens the record or focused activity.
90
+ For a Registry caller, `authorizeDiscussionReferences` must verify the exact
91
+ `crm` product, `crm.read`, canonical audience, app incarnation, environment,
92
+ principal, and—when present—manager plus grant revision. Ordinary agent
93
+ handshakes exclude CRM; an owner must explicitly opt into read-only
94
+ `crm.read`. This scope cannot edit records, send mail, or approve anything.
95
+
81
96
  Put the resolved CRM in an app module both the Worker and checked-in odla
82
97
  config can import, then declare the project-specific integration:
83
98
 
@@ -196,6 +211,8 @@ panels are neither rendered nor mounted.
196
211
  ## Guarantees & limits
197
212
 
198
213
  - Every write accepts a `mutationId` for exactly-once application; webhook-style callers key on it (`{provider}:{eventId}`, `consent:{token}:{event}`, `email:{dedupeKey}`).
214
+ - Discussion reference projections are read-only and product-authorized; a
215
+ stored ref or `odla-ref` link is navigation, never CRM mutation authority.
199
216
  - 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.
200
217
  - Sorting is server-side on exactly one indexed field (odla-db's contract): promoted columns and slotted fields only — the UI kit marks exactly those sortable.
201
218
  - List windows cap at 200 rows; tag cohorts resolve up to 1000 members; unsubscribe GETs never mutate (mail scanners prefetch).
package/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ __export(index_exports, {
23
23
  ACTIVITY_KINDS: () => ACTIVITY_KINDS,
24
24
  CONFIG_KEY: () => CONFIG_KEY,
25
25
  CONSENT_STATES: () => CONSENT_STATES,
26
+ CRM_DISCUSSION_REFERENCE_KINDS: () => CRM_DISCUSSION_REFERENCE_KINDS,
26
27
  CRM_NS: () => CRM_NS,
27
28
  CRM_RULES: () => CRM_RULES,
28
29
  CRM_SCHEMA: () => CRM_SCHEMA,
@@ -49,6 +50,8 @@ __export(index_exports, {
49
50
  createCrmIntegration: () => createCrmIntegration,
50
51
  createCrmRoutes: () => createCrmRoutes,
51
52
  createRecord: () => createRecord,
53
+ crmDiscussionReferenceHref: () => crmDiscussionReferenceHref,
54
+ crmDiscussionReferenceId: () => crmDiscussionReferenceId,
52
55
  crmIntegration: () => crmIntegration,
53
56
  crmRules: () => crmRules,
54
57
  defaultTemplates: () => defaultTemplates,
@@ -56,6 +59,7 @@ __export(index_exports, {
56
59
  deleteView: () => deleteView,
57
60
  emailChannelOps: () => emailChannelOps,
58
61
  foldEmailStatus: () => foldEmailStatus,
62
+ formatCrmDiscussionReference: () => formatCrmDiscussionReference,
59
63
  getConfig: () => getConfig,
60
64
  getRecord: () => getRecord,
61
65
  initialStage: () => initialStage,
@@ -72,6 +76,7 @@ __export(index_exports, {
72
76
  mustGetRecord: () => mustGetRecord,
73
77
  needsRebalance: () => needsRebalance,
74
78
  normalizeTag: () => normalizeTag,
79
+ parseCrmDiscussionReference: () => parseCrmDiscussionReference,
75
80
  prepare: () => prepare,
76
81
  rankBetween: () => rankBetween,
77
82
  rebalancePlan: () => rebalancePlan,
@@ -596,6 +601,49 @@ ${tpl.defaults.text}`, tpl.vars);
596
601
  };
597
602
  }
598
603
 
604
+ // src/discussion-reference.ts
605
+ var CRM_DISCUSSION_REFERENCE_KINDS = [
606
+ "crm:record",
607
+ "crm:activity"
608
+ ];
609
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,199}$/;
610
+ function crmDiscussionReferenceId(target) {
611
+ const root = `${target.type}/${target.recordId}`;
612
+ return target.activityId ? `${root}/${target.activityId}` : root;
613
+ }
614
+ function formatCrmDiscussionReference(target) {
615
+ return `${target.kind}/${crmDiscussionReferenceId(target)}`;
616
+ }
617
+ function parseCrmDiscussionReference(input) {
618
+ let raw;
619
+ try {
620
+ raw = input instanceof URL ? input.searchParams.get("odla-ref") : new URL(input, "https://crm.invalid").searchParams.get("odla-ref");
621
+ } catch {
622
+ return null;
623
+ }
624
+ if (!raw) return null;
625
+ const [kind, type, recordId, activityId, extra] = raw.split("/");
626
+ if (extra !== void 0 || !CRM_DISCUSSION_REFERENCE_KINDS.includes(
627
+ kind
628
+ ) || !type || !recordId || !SEGMENT.test(type) || !SEGMENT.test(recordId)) return null;
629
+ if (kind === "crm:record") {
630
+ return activityId === void 0 ? { kind, type, recordId } : null;
631
+ }
632
+ return activityId && SEGMENT.test(activityId) ? { kind: "crm:activity", type, recordId, activityId } : null;
633
+ }
634
+ function crmDiscussionReferenceHref(current, target, basePath = "/admin/") {
635
+ const next = new URL(current.origin);
636
+ next.pathname = basePath.startsWith("/") ? basePath : `/${basePath}`;
637
+ next.searchParams.set("odla-ref", formatCrmDiscussionReference(target));
638
+ next.hash = [
639
+ "people",
640
+ target.type,
641
+ target.recordId,
642
+ target.kind === "crm:activity" ? "notes" : "profile"
643
+ ].map(encodeURIComponent).join("/");
644
+ return next.toString();
645
+ }
646
+
599
647
  // src/deps.ts
600
648
  function resolveDeps(deps) {
601
649
  return {
@@ -644,14 +692,14 @@ function compileList(crm, params, tagRecordIds) {
644
692
  const column = resolveSortColumn(crm, params.type, sort.field);
645
693
  const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
646
694
  const offset = Math.max(params.offset ?? 0, 0);
647
- const search = params.search?.trim();
695
+ const search2 = params.search?.trim();
648
696
  return {
649
697
  opts: {
650
698
  where: { and },
651
699
  order: { [column]: sort.dir },
652
700
  limit,
653
701
  offset,
654
- ...search ? { search } : {}
702
+ ...search2 ? { search: search2 } : {}
655
703
  },
656
704
  limit,
657
705
  offset
@@ -1580,8 +1628,8 @@ function parseListParams(url) {
1580
1628
  const type = q.get("type");
1581
1629
  if (!type) throw new CrmInputError("type is required");
1582
1630
  const params = { type };
1583
- const search = q.get("search");
1584
- if (search) params.search = search;
1631
+ const search2 = q.get("search");
1632
+ if (search2) params.search = search2;
1585
1633
  params.stage = csv(q.get("stage"));
1586
1634
  params.emailStatus = csv(q.get("emailStatus"));
1587
1635
  params.billingStatus = csv(q.get("billingStatus"));
@@ -1994,9 +2042,141 @@ async function handleUnsubscribe(deps, req, url) {
1994
2042
  return oneClick ? json({ ok: true }) : unsubscribePage(token, true);
1995
2043
  }
1996
2044
 
2045
+ // src/routes/discussion-references.ts
2046
+ var capLimit = (raw) => {
2047
+ const parsed = Number(raw ?? 20);
2048
+ return Number.isInteger(parsed) ? Math.max(1, Math.min(parsed, 20)) : 20;
2049
+ };
2050
+ var targetFromQuery = (url) => {
2051
+ const kind = url.searchParams.get("kind");
2052
+ const id = url.searchParams.get("id");
2053
+ if (!kind || !id) return null;
2054
+ const value = new URL("https://crm.invalid");
2055
+ value.searchParams.set("odla-ref", `${kind}/${id}`);
2056
+ return parseCrmDiscussionReference(value);
2057
+ };
2058
+ var recordItem = (ctx, req, record) => {
2059
+ const typeLabel = ctx.deps.crm.type(record.type).label;
2060
+ const status = record.archived ? "archived" : record.stage ?? "record";
2061
+ const target = {
2062
+ kind: "crm:record",
2063
+ type: record.type,
2064
+ recordId: record.id
2065
+ };
2066
+ return {
2067
+ kind: target.kind,
2068
+ id: crmDiscussionReferenceId(target),
2069
+ label: record.name,
2070
+ hint: `${typeLabel} \xB7 ${status}`,
2071
+ summary: `${typeLabel} record for ${record.name}`,
2072
+ status,
2073
+ destination: `CRM \xB7 ${typeLabel} profile`,
2074
+ href: crmDiscussionReferenceHref(
2075
+ new URL(req.url),
2076
+ target,
2077
+ ctx.opts.discussionBasePath
2078
+ )
2079
+ };
2080
+ };
2081
+ var activityItem = (ctx, req, record, activity) => {
2082
+ const target = {
2083
+ kind: "crm:activity",
2084
+ type: record.type,
2085
+ recordId: record.id,
2086
+ activityId: activity.id
2087
+ };
2088
+ return {
2089
+ kind: target.kind,
2090
+ id: crmDiscussionReferenceId(target),
2091
+ label: activity.body,
2092
+ hint: `${record.name} \xB7 ${activity.kind}${activity.status ? ` \xB7 ${activity.status}` : ""}`,
2093
+ summary: `${activity.kind} on ${record.name}: ${activity.body}`,
2094
+ status: activity.status ?? activity.kind,
2095
+ destination: `CRM \xB7 ${record.name} notes`,
2096
+ href: crmDiscussionReferenceHref(
2097
+ new URL(req.url),
2098
+ target,
2099
+ ctx.opts.discussionBasePath
2100
+ )
2101
+ };
2102
+ };
2103
+ async function exact(ctx, req, target) {
2104
+ const record = await getRecord(ctx.deps, target.recordId);
2105
+ if (!record || record.type !== target.type) return [];
2106
+ if (target.kind === "crm:record") return [recordItem(ctx, req, record)];
2107
+ const result = await ctx.deps.db.query({
2108
+ [CRM_NS.activity]: {
2109
+ $: { where: { id: target.activityId }, limit: 1 }
2110
+ }
2111
+ });
2112
+ const activity = (result[CRM_NS.activity] ?? [])[0];
2113
+ return activity && activity.recordId === record.id ? [activityItem(ctx, req, record, activity)] : [];
2114
+ }
2115
+ var matches = (item, needle) => !needle || `${item.label}
2116
+ ${item.hint}
2117
+ ${item.id}`.toLowerCase().includes(needle);
2118
+ async function searchableActivities(ctx, req, needle) {
2119
+ const result = await ctx.deps.db.query({
2120
+ [CRM_NS.activity]: {
2121
+ $: { order: { createdAt: "desc" }, limit: 100 }
2122
+ }
2123
+ });
2124
+ const rows = result[CRM_NS.activity] ?? [];
2125
+ const matching = rows.filter(
2126
+ (activity) => !needle || activity.body.toLowerCase().includes(needle)
2127
+ );
2128
+ const records = await Promise.all(
2129
+ [...new Set(matching.map((activity) => activity.recordId))].map((id) => getRecord(ctx.deps, id))
2130
+ );
2131
+ const byId = new Map(
2132
+ records.filter((record) => record !== null).map((record) => [record.id, record])
2133
+ );
2134
+ return matching.flatMap((activity) => {
2135
+ const record = byId.get(activity.recordId);
2136
+ return record ? [activityItem(ctx, req, record, activity)] : [];
2137
+ });
2138
+ }
2139
+ async function search(ctx, req, url) {
2140
+ const limit = capLimit(url.searchParams.get("limit"));
2141
+ const needle = (url.searchParams.get("q") ?? "").trim().toLowerCase().slice(0, 120);
2142
+ const recordPages = await Promise.all(
2143
+ Object.keys(ctx.deps.crm.config.types).map(
2144
+ (type) => listRecords(ctx.deps, {
2145
+ type,
2146
+ ...needle ? { search: needle } : {},
2147
+ limit,
2148
+ offset: 0
2149
+ })
2150
+ )
2151
+ );
2152
+ const records = recordPages.flatMap(
2153
+ (page) => page.records.map((record) => recordItem(ctx, req, record))
2154
+ );
2155
+ const activities = await searchableActivities(ctx, req, needle);
2156
+ return [...records, ...activities].filter((item) => matches(item, needle)).slice(0, limit);
2157
+ }
2158
+ async function handleCrmDiscussionReferences(ctx, req, url) {
2159
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
2160
+ if (ctx.actor.discussionReferenceScope !== "all") {
2161
+ return json({ error: "forbidden" }, 403);
2162
+ }
2163
+ const kind = url.searchParams.get("kind");
2164
+ const id = url.searchParams.get("id");
2165
+ if (kind && !id || !kind && id) {
2166
+ return json({ error: "kind and id must be paired" }, 400);
2167
+ }
2168
+ const target = targetFromQuery(url);
2169
+ if ((kind || id) && !target) return json({ items: [] });
2170
+ return json({
2171
+ items: target ? await exact(ctx, req, target) : await search(ctx, req, url)
2172
+ });
2173
+ }
2174
+
1997
2175
  // src/routes/index.ts
1998
2176
  async function route(ctx, req, url, seg) {
1999
2177
  const [head, id, action, ...rest] = seg;
2178
+ if (head === "discussion-references" && id === void 0)
2179
+ return handleCrmDiscussionReferences(ctx, req, url);
2000
2180
  if (head === "records") {
2001
2181
  if (id === void 0) return handleRecordsRoot(ctx, req, url);
2002
2182
  if (action === void 0) return handleRecordItem(ctx, req, id);
@@ -2027,7 +2207,8 @@ function createCrmRoutes(options) {
2027
2207
  ...options,
2028
2208
  basePath,
2029
2209
  envName: options.envName ?? "development",
2030
- baseUrl: options.baseUrl ?? ""
2210
+ baseUrl: options.baseUrl ?? "",
2211
+ discussionBasePath: options.discussionBasePath ?? "/admin/"
2031
2212
  };
2032
2213
  const deps = {
2033
2214
  crm: options.crm,
@@ -2043,9 +2224,14 @@ function createCrmRoutes(options) {
2043
2224
  try {
2044
2225
  if (segments[0] === "unsubscribe" && segments.length === 1)
2045
2226
  return await handleUnsubscribe(deps, req, url);
2046
- const actor = await options.authorize(req);
2227
+ const discussionReferences = segments[0] === "discussion-references";
2228
+ const actor = discussionReferences && options.authorizeDiscussionReferences ? await options.authorizeDiscussionReferences(req) : await options.authorize(req);
2047
2229
  if (!actor) return json({ error: "unauthorized" }, 401);
2048
- const ctx = { deps, opts, actor };
2230
+ const ctx = {
2231
+ deps,
2232
+ opts,
2233
+ actor: discussionReferences && !options.authorizeDiscussionReferences ? { ...actor, discussionReferenceScope: "all" } : actor
2234
+ };
2049
2235
  return await route(ctx, req, url, segments) ?? json({ error: "not found" }, 404);
2050
2236
  } catch (error) {
2051
2237
  return errorResponse(error);