@odla-ai/crm 0.3.2 → 0.5.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 +41 -1
- package/dist/index.cjs +390 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +136 -2
- package/dist/index.d.ts +136 -2
- package/dist/index.js +390 -12
- package/dist/index.js.map +1 -1
- package/dist/ui/index.d.ts +37 -1
- package/dist/ui/index.js +82 -28
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
- package/ui.css +4 -0
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`,
|
|
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.
|
|
@@ -65,6 +69,11 @@ const crmRoutes = createCrmRoutes({
|
|
|
65
69
|
crm,
|
|
66
70
|
db,
|
|
67
71
|
authorize: async (req) => ((await isAdmin(req)) ? { userId: await adminId(req) } : null),
|
|
72
|
+
// Registry-owned read assertion; it cannot authorize a CRM mutation.
|
|
73
|
+
authorizeDiscussionReferences: async (req) => {
|
|
74
|
+
const actor = await verifyRegistryCrmReference(req);
|
|
75
|
+
return actor ? { userId: actor.id, discussionReferenceScope: "all" } : null;
|
|
76
|
+
},
|
|
68
77
|
envName: env.ENV_NAME, // only exactly "production" delivers real email
|
|
69
78
|
baseUrl: "https://app.example.com",
|
|
70
79
|
from: env.EMAIL_FROM,
|
|
@@ -78,6 +87,29 @@ export default {
|
|
|
78
87
|
};
|
|
79
88
|
```
|
|
80
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
|
+
|
|
103
|
+
`GET /api/crm/discussion-references?q=…` searches product-owned records and
|
|
104
|
+
activities; exact `kind` + `id` lookup proves the current row and parentage.
|
|
105
|
+
Results contain canonical kind/id/label, bounded summary/status/destination,
|
|
106
|
+
and a same-origin `odla-ref` link that opens the record or focused activity.
|
|
107
|
+
For a Registry caller, `authorizeDiscussionReferences` must verify the exact
|
|
108
|
+
`crm` product, `crm.read`, canonical audience, app incarnation, environment,
|
|
109
|
+
principal, and—when present—manager plus grant revision. Ordinary agent
|
|
110
|
+
handshakes exclude CRM; an owner must explicitly opt into read-only
|
|
111
|
+
`crm.read`. This scope cannot edit records, send mail, or approve anything.
|
|
112
|
+
|
|
81
113
|
Put the resolved CRM in an app module both the Worker and checked-in odla
|
|
82
114
|
config can import, then declare the project-specific integration:
|
|
83
115
|
|
|
@@ -189,6 +221,7 @@ panels are neither rendered nor mounted.
|
|
|
189
221
|
| Types, pipelines, gates, scorers, template contracts | Code — `defineCrm` (validated at boot) |
|
|
190
222
|
| Template copy, enable flags, destination addresses | Data — the `crm_config` row (owner-editable) |
|
|
191
223
|
| Records, tags, links, activities, channels, send audit, views | odla-db (`CRM_SCHEMA` namespaces) |
|
|
224
|
+
| Cross-system record identity and latest target delivery state | `crm_record_origin` and `crm_record_delivery` |
|
|
192
225
|
| Money | Nowhere here — `BillingProvider` is an optional port an app-owned client or reusable provider package may implement. The record carries cache columns only. |
|
|
193
226
|
| Meetings/scheduling | `@odla-ai/calendar` |
|
|
194
227
|
| Clerk role changes | Your `onTransition` hooks (via `@odla-ai/auth-clerk`) |
|
|
@@ -196,6 +229,13 @@ panels are neither rendered nor mounted.
|
|
|
196
229
|
## Guarantees & limits
|
|
197
230
|
|
|
198
231
|
- Every write accepts a `mutationId` for exactly-once application; webhook-style callers key on it (`{provider}:{eventId}`, `consent:{token}:{event}`, `email:{dedupeKey}`).
|
|
232
|
+
- `upsertRecordOrigin` binds one source site + source record id to one local
|
|
233
|
+
record and refuses remapping. `recordDeliveryAttempt` retains the latest
|
|
234
|
+
per-record/per-target status and bounded error while incrementing attempts.
|
|
235
|
+
`GET /api/crm/records/:id` includes `origins` and `deliveries`; the standard
|
|
236
|
+
record UI exposes them in a Network tab only when data exists.
|
|
237
|
+
- Discussion reference projections are read-only and product-authorized; a
|
|
238
|
+
stored ref or `odla-ref` link is navigation, never CRM mutation authority.
|
|
199
239
|
- 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
240
|
- 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
241
|
- 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,
|
|
@@ -46,9 +47,12 @@ __export(index_exports, {
|
|
|
46
47
|
canTransition: () => canTransition,
|
|
47
48
|
channelKey: () => channelKey,
|
|
48
49
|
compileList: () => compileList,
|
|
50
|
+
composeCrmConfigs: () => composeCrmConfigs,
|
|
49
51
|
createCrmIntegration: () => createCrmIntegration,
|
|
50
52
|
createCrmRoutes: () => createCrmRoutes,
|
|
51
53
|
createRecord: () => createRecord,
|
|
54
|
+
crmDiscussionReferenceHref: () => crmDiscussionReferenceHref,
|
|
55
|
+
crmDiscussionReferenceId: () => crmDiscussionReferenceId,
|
|
52
56
|
crmIntegration: () => crmIntegration,
|
|
53
57
|
crmRules: () => crmRules,
|
|
54
58
|
defaultTemplates: () => defaultTemplates,
|
|
@@ -56,8 +60,11 @@ __export(index_exports, {
|
|
|
56
60
|
deleteView: () => deleteView,
|
|
57
61
|
emailChannelOps: () => emailChannelOps,
|
|
58
62
|
foldEmailStatus: () => foldEmailStatus,
|
|
63
|
+
formatCrmDiscussionReference: () => formatCrmDiscussionReference,
|
|
59
64
|
getConfig: () => getConfig,
|
|
60
65
|
getRecord: () => getRecord,
|
|
66
|
+
getRecordByOrigin: () => getRecordByOrigin,
|
|
67
|
+
getRecordOrigin: () => getRecordOrigin,
|
|
61
68
|
initialStage: () => initialStage,
|
|
62
69
|
linkIdentity: () => linkIdentity,
|
|
63
70
|
lintTemplate: () => lintTemplate,
|
|
@@ -65,6 +72,8 @@ __export(index_exports, {
|
|
|
65
72
|
listChannels: () => listChannels,
|
|
66
73
|
listEmailLog: () => listEmailLog,
|
|
67
74
|
listLinks: () => listLinks,
|
|
75
|
+
listRecordDeliveries: () => listRecordDeliveries,
|
|
76
|
+
listRecordOrigins: () => listRecordOrigins,
|
|
68
77
|
listRecords: () => listRecords,
|
|
69
78
|
listTags: () => listTags,
|
|
70
79
|
listTasks: () => listTasks,
|
|
@@ -72,11 +81,15 @@ __export(index_exports, {
|
|
|
72
81
|
mustGetRecord: () => mustGetRecord,
|
|
73
82
|
needsRebalance: () => needsRebalance,
|
|
74
83
|
normalizeTag: () => normalizeTag,
|
|
84
|
+
parseCrmDiscussionReference: () => parseCrmDiscussionReference,
|
|
75
85
|
prepare: () => prepare,
|
|
76
86
|
rankBetween: () => rankBetween,
|
|
77
87
|
rebalancePlan: () => rebalancePlan,
|
|
78
88
|
rebalanceRanks: () => rebalanceRanks,
|
|
79
89
|
recordCanEmail: () => recordCanEmail,
|
|
90
|
+
recordDeliveryAttempt: () => recordDeliveryAttempt,
|
|
91
|
+
recordDeliveryKey: () => recordDeliveryKey,
|
|
92
|
+
recordOriginKey: () => recordOriginKey,
|
|
80
93
|
removeLink: () => removeLink,
|
|
81
94
|
removeTag: () => removeTag,
|
|
82
95
|
renderTemplate: () => renderTemplate,
|
|
@@ -95,7 +108,8 @@ __export(index_exports, {
|
|
|
95
108
|
typeSummary: () => typeSummary,
|
|
96
109
|
updateRecord: () => updateRecord,
|
|
97
110
|
updateTask: () => updateTask,
|
|
98
|
-
updateView: () => updateView
|
|
111
|
+
updateView: () => updateView,
|
|
112
|
+
upsertRecordOrigin: () => upsertRecordOrigin
|
|
99
113
|
});
|
|
100
114
|
module.exports = __toCommonJS(index_exports);
|
|
101
115
|
|
|
@@ -108,7 +122,9 @@ var CRM_NS = {
|
|
|
108
122
|
channel: "crm_contact_channel",
|
|
109
123
|
emailLog: "crm_email_log",
|
|
110
124
|
view: "crm_view",
|
|
111
|
-
config: "crm_config"
|
|
125
|
+
config: "crm_config",
|
|
126
|
+
origin: "crm_record_origin",
|
|
127
|
+
delivery: "crm_record_delivery"
|
|
112
128
|
};
|
|
113
129
|
var CRM_SLOTS = ["s1", "s2", "s3", "s4", "n1", "n2", "n3", "d1", "d2"];
|
|
114
130
|
var CONSENT_STATES = ["subscribed", "unsubscribed", "bounced", "suppressed"];
|
|
@@ -306,6 +322,37 @@ var CRM_SCHEMA = {
|
|
|
306
322
|
settings: a("json"),
|
|
307
323
|
updatedAt: idx("date")
|
|
308
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
|
+
}
|
|
309
356
|
}
|
|
310
357
|
},
|
|
311
358
|
links: {}
|
|
@@ -515,6 +562,9 @@ function fail(path, message) {
|
|
|
515
562
|
function checkType(typeName, def) {
|
|
516
563
|
const at = `types.${typeName}`;
|
|
517
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
|
+
}
|
|
518
568
|
const claimed = /* @__PURE__ */ new Map();
|
|
519
569
|
for (const [fieldName, field] of Object.entries(def.fields)) {
|
|
520
570
|
const fat = `${at}.fields.${fieldName}`;
|
|
@@ -595,6 +645,71 @@ ${tpl.defaults.text}`, tpl.vars);
|
|
|
595
645
|
stageIndex: (name, stage) => stageIndexOf(type(name), stage)
|
|
596
646
|
};
|
|
597
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
|
+
}
|
|
670
|
+
|
|
671
|
+
// src/discussion-reference.ts
|
|
672
|
+
var CRM_DISCUSSION_REFERENCE_KINDS = [
|
|
673
|
+
"crm:record",
|
|
674
|
+
"crm:activity"
|
|
675
|
+
];
|
|
676
|
+
var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,199}$/;
|
|
677
|
+
function crmDiscussionReferenceId(target) {
|
|
678
|
+
const root = `${target.type}/${target.recordId}`;
|
|
679
|
+
return target.activityId ? `${root}/${target.activityId}` : root;
|
|
680
|
+
}
|
|
681
|
+
function formatCrmDiscussionReference(target) {
|
|
682
|
+
return `${target.kind}/${crmDiscussionReferenceId(target)}`;
|
|
683
|
+
}
|
|
684
|
+
function parseCrmDiscussionReference(input) {
|
|
685
|
+
let raw;
|
|
686
|
+
try {
|
|
687
|
+
raw = input instanceof URL ? input.searchParams.get("odla-ref") : new URL(input, "https://crm.invalid").searchParams.get("odla-ref");
|
|
688
|
+
} catch {
|
|
689
|
+
return null;
|
|
690
|
+
}
|
|
691
|
+
if (!raw) return null;
|
|
692
|
+
const [kind, type, recordId, activityId, extra] = raw.split("/");
|
|
693
|
+
if (extra !== void 0 || !CRM_DISCUSSION_REFERENCE_KINDS.includes(
|
|
694
|
+
kind
|
|
695
|
+
) || !type || !recordId || !SEGMENT.test(type) || !SEGMENT.test(recordId)) return null;
|
|
696
|
+
if (kind === "crm:record") {
|
|
697
|
+
return activityId === void 0 ? { kind, type, recordId } : null;
|
|
698
|
+
}
|
|
699
|
+
return activityId && SEGMENT.test(activityId) ? { kind: "crm:activity", type, recordId, activityId } : null;
|
|
700
|
+
}
|
|
701
|
+
function crmDiscussionReferenceHref(current, target, basePath = "/admin/") {
|
|
702
|
+
const next = new URL(current.origin);
|
|
703
|
+
next.pathname = basePath.startsWith("/") ? basePath : `/${basePath}`;
|
|
704
|
+
next.searchParams.set("odla-ref", formatCrmDiscussionReference(target));
|
|
705
|
+
next.hash = [
|
|
706
|
+
"people",
|
|
707
|
+
target.type,
|
|
708
|
+
target.recordId,
|
|
709
|
+
target.kind === "crm:activity" ? "notes" : "profile"
|
|
710
|
+
].map(encodeURIComponent).join("/");
|
|
711
|
+
return next.toString();
|
|
712
|
+
}
|
|
598
713
|
|
|
599
714
|
// src/deps.ts
|
|
600
715
|
function resolveDeps(deps) {
|
|
@@ -644,14 +759,14 @@ function compileList(crm, params, tagRecordIds) {
|
|
|
644
759
|
const column = resolveSortColumn(crm, params.type, sort.field);
|
|
645
760
|
const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
|
|
646
761
|
const offset = Math.max(params.offset ?? 0, 0);
|
|
647
|
-
const
|
|
762
|
+
const search2 = params.search?.trim();
|
|
648
763
|
return {
|
|
649
764
|
opts: {
|
|
650
765
|
where: { and },
|
|
651
766
|
order: { [column]: sort.dir },
|
|
652
767
|
limit,
|
|
653
768
|
offset,
|
|
654
|
-
...
|
|
769
|
+
...search2 ? { search: search2 } : {}
|
|
655
770
|
},
|
|
656
771
|
limit,
|
|
657
772
|
offset
|
|
@@ -1138,6 +1253,129 @@ async function listLinks(deps, recordId) {
|
|
|
1138
1253
|
return (result[CRM_NS.link] ?? []).map((row) => row);
|
|
1139
1254
|
}
|
|
1140
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
|
+
|
|
1141
1379
|
// src/activities.ts
|
|
1142
1380
|
var rowToActivity = (row) => row;
|
|
1143
1381
|
async function addActivity(deps, opts) {
|
|
@@ -1580,8 +1818,8 @@ function parseListParams(url) {
|
|
|
1580
1818
|
const type = q.get("type");
|
|
1581
1819
|
if (!type) throw new CrmInputError("type is required");
|
|
1582
1820
|
const params = { type };
|
|
1583
|
-
const
|
|
1584
|
-
if (
|
|
1821
|
+
const search2 = q.get("search");
|
|
1822
|
+
if (search2) params.search = search2;
|
|
1585
1823
|
params.stage = csv(q.get("stage"));
|
|
1586
1824
|
params.emailStatus = csv(q.get("emailStatus"));
|
|
1587
1825
|
params.billingStatus = csv(q.get("billingStatus"));
|
|
@@ -1855,12 +2093,14 @@ async function handleRecordItem(ctx, req, id) {
|
|
|
1855
2093
|
if (req.method === "GET") {
|
|
1856
2094
|
const record = await getRecord(ctx.deps, id);
|
|
1857
2095
|
if (!record) throw new CrmNotFoundError("record");
|
|
1858
|
-
const [tags, channels, links] = await Promise.all([
|
|
2096
|
+
const [tags, channels, links, origins, deliveries] = await Promise.all([
|
|
1859
2097
|
listTags(ctx.deps, id),
|
|
1860
2098
|
listChannels(ctx.deps, id),
|
|
1861
|
-
listLinks(ctx.deps, id)
|
|
2099
|
+
listLinks(ctx.deps, id),
|
|
2100
|
+
listRecordOrigins(ctx.deps, id),
|
|
2101
|
+
listRecordDeliveries(ctx.deps, { recordId: id })
|
|
1862
2102
|
]);
|
|
1863
|
-
return json({ record, tags, channels, links });
|
|
2103
|
+
return json({ record, tags, channels, links, origins, deliveries });
|
|
1864
2104
|
}
|
|
1865
2105
|
if (req.method === "PATCH") {
|
|
1866
2106
|
const body = await readJson(req);
|
|
@@ -1994,9 +2234,141 @@ async function handleUnsubscribe(deps, req, url) {
|
|
|
1994
2234
|
return oneClick ? json({ ok: true }) : unsubscribePage(token, true);
|
|
1995
2235
|
}
|
|
1996
2236
|
|
|
2237
|
+
// src/routes/discussion-references.ts
|
|
2238
|
+
var capLimit = (raw) => {
|
|
2239
|
+
const parsed = Number(raw ?? 20);
|
|
2240
|
+
return Number.isInteger(parsed) ? Math.max(1, Math.min(parsed, 20)) : 20;
|
|
2241
|
+
};
|
|
2242
|
+
var targetFromQuery = (url) => {
|
|
2243
|
+
const kind = url.searchParams.get("kind");
|
|
2244
|
+
const id = url.searchParams.get("id");
|
|
2245
|
+
if (!kind || !id) return null;
|
|
2246
|
+
const value = new URL("https://crm.invalid");
|
|
2247
|
+
value.searchParams.set("odla-ref", `${kind}/${id}`);
|
|
2248
|
+
return parseCrmDiscussionReference(value);
|
|
2249
|
+
};
|
|
2250
|
+
var recordItem = (ctx, req, record) => {
|
|
2251
|
+
const typeLabel = ctx.deps.crm.type(record.type).label;
|
|
2252
|
+
const status = record.archived ? "archived" : record.stage ?? "record";
|
|
2253
|
+
const target = {
|
|
2254
|
+
kind: "crm:record",
|
|
2255
|
+
type: record.type,
|
|
2256
|
+
recordId: record.id
|
|
2257
|
+
};
|
|
2258
|
+
return {
|
|
2259
|
+
kind: target.kind,
|
|
2260
|
+
id: crmDiscussionReferenceId(target),
|
|
2261
|
+
label: record.name,
|
|
2262
|
+
hint: `${typeLabel} \xB7 ${status}`,
|
|
2263
|
+
summary: `${typeLabel} record for ${record.name}`,
|
|
2264
|
+
status,
|
|
2265
|
+
destination: `CRM \xB7 ${typeLabel} profile`,
|
|
2266
|
+
href: crmDiscussionReferenceHref(
|
|
2267
|
+
new URL(req.url),
|
|
2268
|
+
target,
|
|
2269
|
+
ctx.opts.discussionBasePath
|
|
2270
|
+
)
|
|
2271
|
+
};
|
|
2272
|
+
};
|
|
2273
|
+
var activityItem = (ctx, req, record, activity) => {
|
|
2274
|
+
const target = {
|
|
2275
|
+
kind: "crm:activity",
|
|
2276
|
+
type: record.type,
|
|
2277
|
+
recordId: record.id,
|
|
2278
|
+
activityId: activity.id
|
|
2279
|
+
};
|
|
2280
|
+
return {
|
|
2281
|
+
kind: target.kind,
|
|
2282
|
+
id: crmDiscussionReferenceId(target),
|
|
2283
|
+
label: activity.body,
|
|
2284
|
+
hint: `${record.name} \xB7 ${activity.kind}${activity.status ? ` \xB7 ${activity.status}` : ""}`,
|
|
2285
|
+
summary: `${activity.kind} on ${record.name}: ${activity.body}`,
|
|
2286
|
+
status: activity.status ?? activity.kind,
|
|
2287
|
+
destination: `CRM \xB7 ${record.name} notes`,
|
|
2288
|
+
href: crmDiscussionReferenceHref(
|
|
2289
|
+
new URL(req.url),
|
|
2290
|
+
target,
|
|
2291
|
+
ctx.opts.discussionBasePath
|
|
2292
|
+
)
|
|
2293
|
+
};
|
|
2294
|
+
};
|
|
2295
|
+
async function exact(ctx, req, target) {
|
|
2296
|
+
const record = await getRecord(ctx.deps, target.recordId);
|
|
2297
|
+
if (!record || record.type !== target.type) return [];
|
|
2298
|
+
if (target.kind === "crm:record") return [recordItem(ctx, req, record)];
|
|
2299
|
+
const result = await ctx.deps.db.query({
|
|
2300
|
+
[CRM_NS.activity]: {
|
|
2301
|
+
$: { where: { id: target.activityId }, limit: 1 }
|
|
2302
|
+
}
|
|
2303
|
+
});
|
|
2304
|
+
const activity = (result[CRM_NS.activity] ?? [])[0];
|
|
2305
|
+
return activity && activity.recordId === record.id ? [activityItem(ctx, req, record, activity)] : [];
|
|
2306
|
+
}
|
|
2307
|
+
var matches = (item, needle) => !needle || `${item.label}
|
|
2308
|
+
${item.hint}
|
|
2309
|
+
${item.id}`.toLowerCase().includes(needle);
|
|
2310
|
+
async function searchableActivities(ctx, req, needle) {
|
|
2311
|
+
const result = await ctx.deps.db.query({
|
|
2312
|
+
[CRM_NS.activity]: {
|
|
2313
|
+
$: { order: { createdAt: "desc" }, limit: 100 }
|
|
2314
|
+
}
|
|
2315
|
+
});
|
|
2316
|
+
const rows = result[CRM_NS.activity] ?? [];
|
|
2317
|
+
const matching = rows.filter(
|
|
2318
|
+
(activity) => !needle || activity.body.toLowerCase().includes(needle)
|
|
2319
|
+
);
|
|
2320
|
+
const records = await Promise.all(
|
|
2321
|
+
[...new Set(matching.map((activity) => activity.recordId))].map((id) => getRecord(ctx.deps, id))
|
|
2322
|
+
);
|
|
2323
|
+
const byId = new Map(
|
|
2324
|
+
records.filter((record) => record !== null).map((record) => [record.id, record])
|
|
2325
|
+
);
|
|
2326
|
+
return matching.flatMap((activity) => {
|
|
2327
|
+
const record = byId.get(activity.recordId);
|
|
2328
|
+
return record ? [activityItem(ctx, req, record, activity)] : [];
|
|
2329
|
+
});
|
|
2330
|
+
}
|
|
2331
|
+
async function search(ctx, req, url) {
|
|
2332
|
+
const limit = capLimit(url.searchParams.get("limit"));
|
|
2333
|
+
const needle = (url.searchParams.get("q") ?? "").trim().toLowerCase().slice(0, 120);
|
|
2334
|
+
const recordPages = await Promise.all(
|
|
2335
|
+
Object.keys(ctx.deps.crm.config.types).map(
|
|
2336
|
+
(type) => listRecords(ctx.deps, {
|
|
2337
|
+
type,
|
|
2338
|
+
...needle ? { search: needle } : {},
|
|
2339
|
+
limit,
|
|
2340
|
+
offset: 0
|
|
2341
|
+
})
|
|
2342
|
+
)
|
|
2343
|
+
);
|
|
2344
|
+
const records = recordPages.flatMap(
|
|
2345
|
+
(page) => page.records.map((record) => recordItem(ctx, req, record))
|
|
2346
|
+
);
|
|
2347
|
+
const activities = await searchableActivities(ctx, req, needle);
|
|
2348
|
+
return [...records, ...activities].filter((item) => matches(item, needle)).slice(0, limit);
|
|
2349
|
+
}
|
|
2350
|
+
async function handleCrmDiscussionReferences(ctx, req, url) {
|
|
2351
|
+
if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
|
|
2352
|
+
if (ctx.actor.discussionReferenceScope !== "all") {
|
|
2353
|
+
return json({ error: "forbidden" }, 403);
|
|
2354
|
+
}
|
|
2355
|
+
const kind = url.searchParams.get("kind");
|
|
2356
|
+
const id = url.searchParams.get("id");
|
|
2357
|
+
if (kind && !id || !kind && id) {
|
|
2358
|
+
return json({ error: "kind and id must be paired" }, 400);
|
|
2359
|
+
}
|
|
2360
|
+
const target = targetFromQuery(url);
|
|
2361
|
+
if ((kind || id) && !target) return json({ items: [] });
|
|
2362
|
+
return json({
|
|
2363
|
+
items: target ? await exact(ctx, req, target) : await search(ctx, req, url)
|
|
2364
|
+
});
|
|
2365
|
+
}
|
|
2366
|
+
|
|
1997
2367
|
// src/routes/index.ts
|
|
1998
2368
|
async function route(ctx, req, url, seg) {
|
|
1999
2369
|
const [head, id, action, ...rest] = seg;
|
|
2370
|
+
if (head === "discussion-references" && id === void 0)
|
|
2371
|
+
return handleCrmDiscussionReferences(ctx, req, url);
|
|
2000
2372
|
if (head === "records") {
|
|
2001
2373
|
if (id === void 0) return handleRecordsRoot(ctx, req, url);
|
|
2002
2374
|
if (action === void 0) return handleRecordItem(ctx, req, id);
|
|
@@ -2027,7 +2399,8 @@ function createCrmRoutes(options) {
|
|
|
2027
2399
|
...options,
|
|
2028
2400
|
basePath,
|
|
2029
2401
|
envName: options.envName ?? "development",
|
|
2030
|
-
baseUrl: options.baseUrl ?? ""
|
|
2402
|
+
baseUrl: options.baseUrl ?? "",
|
|
2403
|
+
discussionBasePath: options.discussionBasePath ?? "/admin/"
|
|
2031
2404
|
};
|
|
2032
2405
|
const deps = {
|
|
2033
2406
|
crm: options.crm,
|
|
@@ -2043,9 +2416,14 @@ function createCrmRoutes(options) {
|
|
|
2043
2416
|
try {
|
|
2044
2417
|
if (segments[0] === "unsubscribe" && segments.length === 1)
|
|
2045
2418
|
return await handleUnsubscribe(deps, req, url);
|
|
2046
|
-
const
|
|
2419
|
+
const discussionReferences = segments[0] === "discussion-references";
|
|
2420
|
+
const actor = discussionReferences && options.authorizeDiscussionReferences ? await options.authorizeDiscussionReferences(req) : await options.authorize(req);
|
|
2047
2421
|
if (!actor) return json({ error: "unauthorized" }, 401);
|
|
2048
|
-
const ctx = {
|
|
2422
|
+
const ctx = {
|
|
2423
|
+
deps,
|
|
2424
|
+
opts,
|
|
2425
|
+
actor: discussionReferences && !options.authorizeDiscussionReferences ? { ...actor, discussionReferenceScope: "all" } : actor
|
|
2426
|
+
};
|
|
2049
2427
|
return await route(ctx, req, url, segments) ?? json({ error: "not found" }, 404);
|
|
2050
2428
|
} catch (error) {
|
|
2051
2429
|
return errorResponse(error);
|