@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 +27 -6
- package/dist/index.cjs +143 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +62 -11
- package/dist/index.d.ts +62 -11
- package/dist/index.js +143 -64
- package/dist/index.js.map +1 -1
- package/dist/ui/index.d.ts +7 -2
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -120,7 +120,8 @@ type CrmEntityRef = string | CrmLookup;
|
|
|
120
120
|
* `transact` constrains attrs to its own `Value` type, and `any` is the one
|
|
121
121
|
* shape assignable in both directions with no cast. */
|
|
122
122
|
type CrmAttrs = Record<string, any>;
|
|
123
|
-
/** One transact operation (update = attr-merge upsert
|
|
123
|
+
/** One transact operation (update = attr-merge upsert; retract = clear the
|
|
124
|
+
* named attributes, since a typed scalar can't store null). */
|
|
124
125
|
type CrmOp = {
|
|
125
126
|
t: "update";
|
|
126
127
|
ns: string;
|
|
@@ -131,6 +132,11 @@ type CrmOp = {
|
|
|
131
132
|
ns: string;
|
|
132
133
|
id: CrmEntityRef;
|
|
133
134
|
attrs: CrmAttrs;
|
|
135
|
+
} | {
|
|
136
|
+
t: "retract";
|
|
137
|
+
ns: string;
|
|
138
|
+
id: CrmEntityRef;
|
|
139
|
+
attrs: string[];
|
|
134
140
|
} | {
|
|
135
141
|
t: "delete";
|
|
136
142
|
ns: string;
|
|
@@ -322,10 +328,15 @@ interface CrmConfigRow {
|
|
|
322
328
|
settings: Record<string, unknown>;
|
|
323
329
|
updatedAt: number;
|
|
324
330
|
}
|
|
325
|
-
/** Outcome of validating + coercing input for a type (see `prepare`).
|
|
331
|
+
/** Outcome of validating + coercing input for a type (see `prepare`). On
|
|
332
|
+
* success, `attrs` are the columns to WRITE (never null — odla-db rejects null
|
|
333
|
+
* on a typed scalar) and `retract` names the slots/promoted columns to CLEAR
|
|
334
|
+
* because their field went empty (populated only on update; empty on create,
|
|
335
|
+
* where there is nothing to clear). */
|
|
326
336
|
type PreparedWrite = {
|
|
327
337
|
ok: true;
|
|
328
338
|
attrs: CrmAttrs;
|
|
339
|
+
retract: string[];
|
|
329
340
|
} | {
|
|
330
341
|
ok: false;
|
|
331
342
|
errors: Record<string, string>;
|
|
@@ -454,10 +465,12 @@ declare function searchTextFor(def: TypeDef, name: string, email: string | null,
|
|
|
454
465
|
* Validate + coerce `input` (keyed by config field name) for one type.
|
|
455
466
|
* Create (no `existing`): required fields must be present, and the
|
|
456
467
|
* `nameField` always (a record without a name is unlistable). Update:
|
|
457
|
-
* partial — unnamed fields keep their stored values.
|
|
458
|
-
* to write
|
|
459
|
-
*
|
|
460
|
-
* rebuilt `searchText` —
|
|
468
|
+
* partial — unnamed fields keep their stored values. On success returns the
|
|
469
|
+
* columns to write — promoted `name`, `primaryEmail` and each claimed slot
|
|
470
|
+
* that has a value, the complete `fields` json (source of truth), and the
|
|
471
|
+
* rebuilt `searchText` — plus `retract`, the columns whose field went empty
|
|
472
|
+
* (odla-db can't store a scalar null, so an empty column is omitted on create
|
|
473
|
+
* and retracted on update). Otherwise `{ ok: false, errors }` keyed by field.
|
|
461
474
|
*/
|
|
462
475
|
declare function prepare(def: TypeDef, input: Record<string, unknown>, existing?: CrmRecord): PreparedWrite;
|
|
463
476
|
|
|
@@ -1264,6 +1277,22 @@ interface IntegrationProvision {
|
|
|
1264
1277
|
human: string[];
|
|
1265
1278
|
cli: string[];
|
|
1266
1279
|
doctor: string[];
|
|
1280
|
+
smoke?: string[];
|
|
1281
|
+
}
|
|
1282
|
+
/** Natural-key config row the CLI creates only when no CRM config exists. */
|
|
1283
|
+
interface CrmIntegrationSeed {
|
|
1284
|
+
id: string;
|
|
1285
|
+
ns: string;
|
|
1286
|
+
key: {
|
|
1287
|
+
attr: string;
|
|
1288
|
+
value: string;
|
|
1289
|
+
};
|
|
1290
|
+
attrs: Record<string, unknown>;
|
|
1291
|
+
}
|
|
1292
|
+
/** Unauthenticated route check run by `odla-ai smoke`. */
|
|
1293
|
+
interface CrmIntegrationProbe {
|
|
1294
|
+
path: string;
|
|
1295
|
+
expectedStatus: number;
|
|
1267
1296
|
}
|
|
1268
1297
|
/** The CRM's descriptor shape: the shared base plus the schema + deny-all
|
|
1269
1298
|
* rules provisioning installs (the chat-style extension). */
|
|
@@ -1275,16 +1304,38 @@ interface CrmIntegrationDescriptor {
|
|
|
1275
1304
|
secrets: IntegrationSecret[];
|
|
1276
1305
|
schema: SerializedSchema;
|
|
1277
1306
|
rules: CrmRules;
|
|
1307
|
+
seeds?: CrmIntegrationSeed[];
|
|
1308
|
+
probes?: CrmIntegrationProbe[];
|
|
1278
1309
|
provision: IntegrationProvision;
|
|
1279
1310
|
}
|
|
1311
|
+
/** Initial owner-editable CRM settings seeded during first provisioning. */
|
|
1312
|
+
interface CrmIntegrationOptions {
|
|
1313
|
+
/** Worker mount path; defaults to `/api/crm`. */
|
|
1314
|
+
basePath?: string;
|
|
1315
|
+
notificationEmail?: string;
|
|
1316
|
+
replyTo?: string;
|
|
1317
|
+
debugEmail?: string;
|
|
1318
|
+
settings?: Record<string, unknown>;
|
|
1319
|
+
/** Seed timestamp override for reproducible builds/tests. */
|
|
1320
|
+
now?: number;
|
|
1321
|
+
}
|
|
1280
1322
|
/**
|
|
1281
|
-
* The
|
|
1282
|
-
*
|
|
1323
|
+
* The static documentation descriptor for @odla-ai/crm. Data only: it
|
|
1324
|
+
* describes what installing the
|
|
1283
1325
|
* CRM means (push {@link CRM_SCHEMA}, install deny-all {@link CRM_RULES},
|
|
1284
1326
|
* seed the `crm_config` row, mount `createCrmRoutes` in the app worker); it
|
|
1285
|
-
* performs none of it.
|
|
1286
|
-
*
|
|
1327
|
+
* performs none of it. Use {@link createCrmIntegration} in `odla.config.mjs`
|
|
1328
|
+
* to add the config seed and live route probe the CLI can execute. Billing is
|
|
1329
|
+
* an optional injected provider seam and the core CRM needs no vault entries.
|
|
1287
1330
|
*/
|
|
1288
1331
|
declare const crmIntegration: CrmIntegrationDescriptor;
|
|
1332
|
+
/**
|
|
1333
|
+
* Build the project-specific, CLI-consumable CRM integration descriptor.
|
|
1334
|
+
* The returned schema/rules merge structurally with app-authored db config;
|
|
1335
|
+
* the config singleton is seeded only when absent, preserving later owner
|
|
1336
|
+
* edits, and `smoke` verifies the mounted records route rejects anonymous
|
|
1337
|
+
* access. Mounting `createCrmRoutes` remains app-owned source work.
|
|
1338
|
+
*/
|
|
1339
|
+
declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
|
|
1289
1340
|
|
|
1290
|
-
export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, canEmail, canTransition, channelKey, compileList, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
|
|
1341
|
+
export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
|
package/dist/index.d.ts
CHANGED
|
@@ -120,7 +120,8 @@ type CrmEntityRef = string | CrmLookup;
|
|
|
120
120
|
* `transact` constrains attrs to its own `Value` type, and `any` is the one
|
|
121
121
|
* shape assignable in both directions with no cast. */
|
|
122
122
|
type CrmAttrs = Record<string, any>;
|
|
123
|
-
/** One transact operation (update = attr-merge upsert
|
|
123
|
+
/** One transact operation (update = attr-merge upsert; retract = clear the
|
|
124
|
+
* named attributes, since a typed scalar can't store null). */
|
|
124
125
|
type CrmOp = {
|
|
125
126
|
t: "update";
|
|
126
127
|
ns: string;
|
|
@@ -131,6 +132,11 @@ type CrmOp = {
|
|
|
131
132
|
ns: string;
|
|
132
133
|
id: CrmEntityRef;
|
|
133
134
|
attrs: CrmAttrs;
|
|
135
|
+
} | {
|
|
136
|
+
t: "retract";
|
|
137
|
+
ns: string;
|
|
138
|
+
id: CrmEntityRef;
|
|
139
|
+
attrs: string[];
|
|
134
140
|
} | {
|
|
135
141
|
t: "delete";
|
|
136
142
|
ns: string;
|
|
@@ -322,10 +328,15 @@ interface CrmConfigRow {
|
|
|
322
328
|
settings: Record<string, unknown>;
|
|
323
329
|
updatedAt: number;
|
|
324
330
|
}
|
|
325
|
-
/** Outcome of validating + coercing input for a type (see `prepare`).
|
|
331
|
+
/** Outcome of validating + coercing input for a type (see `prepare`). On
|
|
332
|
+
* success, `attrs` are the columns to WRITE (never null — odla-db rejects null
|
|
333
|
+
* on a typed scalar) and `retract` names the slots/promoted columns to CLEAR
|
|
334
|
+
* because their field went empty (populated only on update; empty on create,
|
|
335
|
+
* where there is nothing to clear). */
|
|
326
336
|
type PreparedWrite = {
|
|
327
337
|
ok: true;
|
|
328
338
|
attrs: CrmAttrs;
|
|
339
|
+
retract: string[];
|
|
329
340
|
} | {
|
|
330
341
|
ok: false;
|
|
331
342
|
errors: Record<string, string>;
|
|
@@ -454,10 +465,12 @@ declare function searchTextFor(def: TypeDef, name: string, email: string | null,
|
|
|
454
465
|
* Validate + coerce `input` (keyed by config field name) for one type.
|
|
455
466
|
* Create (no `existing`): required fields must be present, and the
|
|
456
467
|
* `nameField` always (a record without a name is unlistable). Update:
|
|
457
|
-
* partial — unnamed fields keep their stored values.
|
|
458
|
-
* to write
|
|
459
|
-
*
|
|
460
|
-
* rebuilt `searchText` —
|
|
468
|
+
* partial — unnamed fields keep their stored values. On success returns the
|
|
469
|
+
* columns to write — promoted `name`, `primaryEmail` and each claimed slot
|
|
470
|
+
* that has a value, the complete `fields` json (source of truth), and the
|
|
471
|
+
* rebuilt `searchText` — plus `retract`, the columns whose field went empty
|
|
472
|
+
* (odla-db can't store a scalar null, so an empty column is omitted on create
|
|
473
|
+
* and retracted on update). Otherwise `{ ok: false, errors }` keyed by field.
|
|
461
474
|
*/
|
|
462
475
|
declare function prepare(def: TypeDef, input: Record<string, unknown>, existing?: CrmRecord): PreparedWrite;
|
|
463
476
|
|
|
@@ -1264,6 +1277,22 @@ interface IntegrationProvision {
|
|
|
1264
1277
|
human: string[];
|
|
1265
1278
|
cli: string[];
|
|
1266
1279
|
doctor: string[];
|
|
1280
|
+
smoke?: string[];
|
|
1281
|
+
}
|
|
1282
|
+
/** Natural-key config row the CLI creates only when no CRM config exists. */
|
|
1283
|
+
interface CrmIntegrationSeed {
|
|
1284
|
+
id: string;
|
|
1285
|
+
ns: string;
|
|
1286
|
+
key: {
|
|
1287
|
+
attr: string;
|
|
1288
|
+
value: string;
|
|
1289
|
+
};
|
|
1290
|
+
attrs: Record<string, unknown>;
|
|
1291
|
+
}
|
|
1292
|
+
/** Unauthenticated route check run by `odla-ai smoke`. */
|
|
1293
|
+
interface CrmIntegrationProbe {
|
|
1294
|
+
path: string;
|
|
1295
|
+
expectedStatus: number;
|
|
1267
1296
|
}
|
|
1268
1297
|
/** The CRM's descriptor shape: the shared base plus the schema + deny-all
|
|
1269
1298
|
* rules provisioning installs (the chat-style extension). */
|
|
@@ -1275,16 +1304,38 @@ interface CrmIntegrationDescriptor {
|
|
|
1275
1304
|
secrets: IntegrationSecret[];
|
|
1276
1305
|
schema: SerializedSchema;
|
|
1277
1306
|
rules: CrmRules;
|
|
1307
|
+
seeds?: CrmIntegrationSeed[];
|
|
1308
|
+
probes?: CrmIntegrationProbe[];
|
|
1278
1309
|
provision: IntegrationProvision;
|
|
1279
1310
|
}
|
|
1311
|
+
/** Initial owner-editable CRM settings seeded during first provisioning. */
|
|
1312
|
+
interface CrmIntegrationOptions {
|
|
1313
|
+
/** Worker mount path; defaults to `/api/crm`. */
|
|
1314
|
+
basePath?: string;
|
|
1315
|
+
notificationEmail?: string;
|
|
1316
|
+
replyTo?: string;
|
|
1317
|
+
debugEmail?: string;
|
|
1318
|
+
settings?: Record<string, unknown>;
|
|
1319
|
+
/** Seed timestamp override for reproducible builds/tests. */
|
|
1320
|
+
now?: number;
|
|
1321
|
+
}
|
|
1280
1322
|
/**
|
|
1281
|
-
* The
|
|
1282
|
-
*
|
|
1323
|
+
* The static documentation descriptor for @odla-ai/crm. Data only: it
|
|
1324
|
+
* describes what installing the
|
|
1283
1325
|
* CRM means (push {@link CRM_SCHEMA}, install deny-all {@link CRM_RULES},
|
|
1284
1326
|
* seed the `crm_config` row, mount `createCrmRoutes` in the app worker); it
|
|
1285
|
-
* performs none of it.
|
|
1286
|
-
*
|
|
1327
|
+
* performs none of it. Use {@link createCrmIntegration} in `odla.config.mjs`
|
|
1328
|
+
* to add the config seed and live route probe the CLI can execute. Billing is
|
|
1329
|
+
* an optional injected provider seam and the core CRM needs no vault entries.
|
|
1287
1330
|
*/
|
|
1288
1331
|
declare const crmIntegration: CrmIntegrationDescriptor;
|
|
1332
|
+
/**
|
|
1333
|
+
* Build the project-specific, CLI-consumable CRM integration descriptor.
|
|
1334
|
+
* The returned schema/rules merge structurally with app-authored db config;
|
|
1335
|
+
* the config singleton is seeded only when absent, preserving later owner
|
|
1336
|
+
* edits, and `smoke` verifies the mounted records route rejects anonymous
|
|
1337
|
+
* access. Mounting `createCrmRoutes` remains app-owned source work.
|
|
1338
|
+
*/
|
|
1339
|
+
declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
|
|
1289
1340
|
|
|
1290
|
-
export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, canEmail, canTransition, channelKey, compileList, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
|
|
1341
|
+
export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, canEmail, canTransition, channelKey, compileList, createCrmIntegration, createCrmRoutes, createRecord, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
|
package/dist/index.js
CHANGED
|
@@ -71,6 +71,10 @@ var CRM_SCHEMA = {
|
|
|
71
71
|
entities: {
|
|
72
72
|
[CRM_NS.record]: {
|
|
73
73
|
attrs: {
|
|
74
|
+
// Entity ids are not attributes in odla-db, so `where: { id }` matches
|
|
75
|
+
// nothing unless the id is mirrored as a written attr — the getRecord /
|
|
76
|
+
// tag-filter / neighbor reads all filter by id. Mirror it as unique.
|
|
77
|
+
id: uniq("string"),
|
|
74
78
|
type: idx("string"),
|
|
75
79
|
name: idx("string"),
|
|
76
80
|
primaryEmail: idx("string", true),
|
|
@@ -125,6 +129,8 @@ var CRM_SCHEMA = {
|
|
|
125
129
|
},
|
|
126
130
|
[CRM_NS.activity]: {
|
|
127
131
|
attrs: {
|
|
132
|
+
id: uniq("string"),
|
|
133
|
+
// mirrored so updateTask can read one by id
|
|
128
134
|
recordId: idx("string"),
|
|
129
135
|
kind: idx("string"),
|
|
130
136
|
body: a("string"),
|
|
@@ -174,6 +180,8 @@ var CRM_SCHEMA = {
|
|
|
174
180
|
},
|
|
175
181
|
[CRM_NS.view]: {
|
|
176
182
|
attrs: {
|
|
183
|
+
id: uniq("string"),
|
|
184
|
+
// mirrored so getView/updateView can read one by id
|
|
177
185
|
name: a("string"),
|
|
178
186
|
type: idx("string"),
|
|
179
187
|
ownerId: idx("string", true),
|
|
@@ -260,6 +268,25 @@ function canTransition(def, record, to) {
|
|
|
260
268
|
return null;
|
|
261
269
|
}
|
|
262
270
|
|
|
271
|
+
// src/template.ts
|
|
272
|
+
var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
|
|
273
|
+
function renderTemplate(template, vars) {
|
|
274
|
+
return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
|
|
275
|
+
}
|
|
276
|
+
function templateVars(template) {
|
|
277
|
+
const seen = /* @__PURE__ */ new Set();
|
|
278
|
+
for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
|
|
279
|
+
return [...seen];
|
|
280
|
+
}
|
|
281
|
+
function lintTemplate(template, knownVars) {
|
|
282
|
+
const used = templateVars(template);
|
|
283
|
+
const known = new Set(knownVars);
|
|
284
|
+
return {
|
|
285
|
+
unknown: used.filter((v) => !known.has(v)),
|
|
286
|
+
unused: knownVars.filter((v) => !used.includes(v))
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
263
290
|
// src/validate.ts
|
|
264
291
|
var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
265
292
|
var STRINGISH = /* @__PURE__ */ new Set(["string", "email", "url", "enum"]);
|
|
@@ -350,10 +377,21 @@ function prepare(def, input, existing) {
|
|
|
350
377
|
fields,
|
|
351
378
|
searchText: searchTextFor(def, name, primaryEmail, fields)
|
|
352
379
|
};
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
if (
|
|
356
|
-
|
|
380
|
+
const retract = [];
|
|
381
|
+
const clear = (column) => {
|
|
382
|
+
if (existing) retract.push(column);
|
|
383
|
+
};
|
|
384
|
+
if (def.emailField) {
|
|
385
|
+
if (primaryEmail === null) clear("primaryEmail");
|
|
386
|
+
else attrs.primaryEmail = primaryEmail;
|
|
387
|
+
}
|
|
388
|
+
for (const [fieldName, field] of Object.entries(def.fields)) {
|
|
389
|
+
if (!field.slot) continue;
|
|
390
|
+
const value = fields[fieldName];
|
|
391
|
+
if (empty(field, value)) clear(field.slot);
|
|
392
|
+
else attrs[field.slot] = value;
|
|
393
|
+
}
|
|
394
|
+
return { ok: true, attrs, retract };
|
|
357
395
|
}
|
|
358
396
|
|
|
359
397
|
// src/config.ts
|
|
@@ -434,6 +472,11 @@ function defineCrm(config) {
|
|
|
434
472
|
if (tpl.class !== "transactional" && tpl.class !== "marketing")
|
|
435
473
|
fail(at, `class must be transactional|marketing`);
|
|
436
474
|
for (const v of tpl.vars) if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v)) fail(at, `bad var "${v}"`);
|
|
475
|
+
if (tpl.defaults) {
|
|
476
|
+
const lint = lintTemplate(`${tpl.defaults.subject}
|
|
477
|
+
${tpl.defaults.text}`, tpl.vars);
|
|
478
|
+
if (lint.unknown.length) fail(at, `defaults reference unknown vars: ${lint.unknown.join(", ")}`);
|
|
479
|
+
}
|
|
437
480
|
}
|
|
438
481
|
const type = (name) => {
|
|
439
482
|
const def = config.types[name];
|
|
@@ -581,25 +624,6 @@ function canEmail(consent, cls) {
|
|
|
581
624
|
return true;
|
|
582
625
|
}
|
|
583
626
|
|
|
584
|
-
// src/template.ts
|
|
585
|
-
var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
|
|
586
|
-
function renderTemplate(template, vars) {
|
|
587
|
-
return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
|
|
588
|
-
}
|
|
589
|
-
function templateVars(template) {
|
|
590
|
-
const seen = /* @__PURE__ */ new Set();
|
|
591
|
-
for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
|
|
592
|
-
return [...seen];
|
|
593
|
-
}
|
|
594
|
-
function lintTemplate(template, knownVars) {
|
|
595
|
-
const used = templateVars(template);
|
|
596
|
-
const known = new Set(knownVars);
|
|
597
|
-
return {
|
|
598
|
-
unknown: used.filter((v) => !known.has(v)),
|
|
599
|
-
unused: knownVars.filter((v) => !used.includes(v))
|
|
600
|
-
};
|
|
601
|
-
}
|
|
602
|
-
|
|
603
627
|
// src/channels.ts
|
|
604
628
|
var channelKey = (recordId, kind, value) => `${recordId}:${kind}:${value}`;
|
|
605
629
|
function foldEmailStatus(consent) {
|
|
@@ -677,6 +701,29 @@ async function applyConsent(deps, opts) {
|
|
|
677
701
|
return { state: outcome.state, recordId: channel.recordId, duplicate };
|
|
678
702
|
}
|
|
679
703
|
|
|
704
|
+
// src/write-ops.ts
|
|
705
|
+
function patchOps(ns, id, patch, alsoClear = []) {
|
|
706
|
+
const attrs = {};
|
|
707
|
+
const retract = [...alsoClear];
|
|
708
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
709
|
+
if (value === null) retract.push(key);
|
|
710
|
+
else if (value !== void 0) attrs[key] = value;
|
|
711
|
+
}
|
|
712
|
+
const ops = [];
|
|
713
|
+
if (Object.keys(attrs).length > 0) ops.push({ t: "update", ns, id, attrs });
|
|
714
|
+
if (retract.length > 0) ops.push({ t: "retract", ns, id, attrs: retract });
|
|
715
|
+
return ops;
|
|
716
|
+
}
|
|
717
|
+
function applyPatch(base, patch, alsoClear = []) {
|
|
718
|
+
const out = { ...base };
|
|
719
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
720
|
+
if (value === null) delete out[key];
|
|
721
|
+
else if (value !== void 0) out[key] = value;
|
|
722
|
+
}
|
|
723
|
+
for (const key of alsoClear) delete out[key];
|
|
724
|
+
return out;
|
|
725
|
+
}
|
|
726
|
+
|
|
680
727
|
// src/records.ts
|
|
681
728
|
function rowToRecord(row) {
|
|
682
729
|
const record = row;
|
|
@@ -733,6 +780,8 @@ async function createRecord(deps, opts) {
|
|
|
733
780
|
const at = now();
|
|
734
781
|
const stage = opts.stage ?? crm.initialStage(opts.type);
|
|
735
782
|
const attrs = {
|
|
783
|
+
id,
|
|
784
|
+
// mirror the entity id as an attr so `where: { id }` reads can find it
|
|
736
785
|
type: opts.type,
|
|
737
786
|
...prepared.attrs,
|
|
738
787
|
archived: false,
|
|
@@ -767,32 +816,31 @@ async function updateRecord(deps, opts) {
|
|
|
767
816
|
const existing = await mustGetRecord(deps, opts.id);
|
|
768
817
|
const prepared = crm.prepare(existing.type, opts.input, existing);
|
|
769
818
|
if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
const ops = [];
|
|
819
|
+
const patch = { ...prepared.attrs, updatedAt: now(), ownerId: opts.ownerId };
|
|
820
|
+
const channelOps = [];
|
|
773
821
|
if (crm.type(existing.type).emailField) {
|
|
774
822
|
const nextEmail = prepared.attrs["primaryEmail"] ?? null;
|
|
775
823
|
if (nextEmail !== (existing.primaryEmail ?? null)) {
|
|
776
824
|
const channels = await listChannels(deps, existing.id);
|
|
777
825
|
const channel = emailChannelOps(deps, existing.id, nextEmail, channels);
|
|
778
|
-
|
|
779
|
-
|
|
826
|
+
patch.emailStatus = channel.emailStatus;
|
|
827
|
+
channelOps.push(...channel.ops);
|
|
780
828
|
}
|
|
781
829
|
}
|
|
782
|
-
const candidate = { ...existing, ...attrs };
|
|
830
|
+
const candidate = { ...existing, ...prepared.attrs };
|
|
783
831
|
const score = scoreOf(deps, existing.type, candidate);
|
|
784
|
-
if (score !== void 0)
|
|
785
|
-
ops
|
|
832
|
+
if (score !== void 0) patch.score = score;
|
|
833
|
+
const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];
|
|
786
834
|
const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
|
|
787
|
-
return { record:
|
|
835
|
+
return { record: applyPatch(existing, patch, prepared.retract), duplicate };
|
|
788
836
|
}
|
|
789
837
|
async function setArchived(deps, opts) {
|
|
790
838
|
const { db, now } = resolveDeps(deps);
|
|
791
839
|
await mustGetRecord(deps, opts.id);
|
|
792
840
|
const at = now();
|
|
793
|
-
const
|
|
841
|
+
const patch = opts.archived ? { archived: true, archivedAt: at, updatedAt: at } : { archived: false, archivedAt: null, updatedAt: at };
|
|
794
842
|
const { duplicate } = await db.transact(
|
|
795
|
-
|
|
843
|
+
patchOps(CRM_NS.record, opts.id, patch),
|
|
796
844
|
{ mutationId: opts.mutationId }
|
|
797
845
|
);
|
|
798
846
|
return { duplicate };
|
|
@@ -811,13 +859,16 @@ async function setStage(deps, opts) {
|
|
|
811
859
|
stageChangedAt: at,
|
|
812
860
|
updatedAt: at
|
|
813
861
|
};
|
|
862
|
+
const activityId = newId();
|
|
814
863
|
const ops = [
|
|
815
864
|
{ t: "update", ns: CRM_NS.record, id: record.id, attrs },
|
|
816
865
|
{
|
|
817
866
|
t: "update",
|
|
818
867
|
ns: CRM_NS.activity,
|
|
819
|
-
id:
|
|
868
|
+
id: activityId,
|
|
820
869
|
attrs: {
|
|
870
|
+
id: activityId,
|
|
871
|
+
// mirror the entity id so the activity is readable by id
|
|
821
872
|
recordId: record.id,
|
|
822
873
|
kind: "stage_change",
|
|
823
874
|
body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
|
|
@@ -996,6 +1047,8 @@ async function addActivity(deps, opts) {
|
|
|
996
1047
|
await mustGetRecord(deps, opts.recordId);
|
|
997
1048
|
const id = newId();
|
|
998
1049
|
const attrs = {
|
|
1050
|
+
id,
|
|
1051
|
+
// mirror the entity id so updateTask's `where: { id }` read can find it
|
|
999
1052
|
recordId: opts.recordId,
|
|
1000
1053
|
kind: opts.kind,
|
|
1001
1054
|
body,
|
|
@@ -1021,25 +1074,25 @@ async function updateTask(deps, opts) {
|
|
|
1021
1074
|
if (!row) throw new CrmNotFoundError("activity");
|
|
1022
1075
|
const activity = rowToActivity(row);
|
|
1023
1076
|
if (activity.kind !== "task") throw new CrmInputError("only tasks can be updated");
|
|
1024
|
-
const
|
|
1077
|
+
const patch = {};
|
|
1025
1078
|
if (opts.status !== void 0) {
|
|
1026
1079
|
if (!TASK_STATUSES.includes(opts.status)) throw new CrmInputError(`unknown status "${opts.status}"`);
|
|
1027
|
-
|
|
1028
|
-
|
|
1080
|
+
patch.status = opts.status;
|
|
1081
|
+
patch.completedAt = opts.status === "done" ? now() : null;
|
|
1029
1082
|
}
|
|
1030
|
-
if (opts.dueAt !== void 0)
|
|
1031
|
-
if (opts.assigneeId !== void 0)
|
|
1032
|
-
if (opts.waitingOn !== void 0)
|
|
1083
|
+
if (opts.dueAt !== void 0) patch.dueAt = opts.dueAt;
|
|
1084
|
+
if (opts.assigneeId !== void 0) patch.assigneeId = opts.assigneeId;
|
|
1085
|
+
if (opts.waitingOn !== void 0) patch.waitingOn = opts.waitingOn;
|
|
1033
1086
|
if (opts.body !== void 0) {
|
|
1034
1087
|
const body = opts.body.trim();
|
|
1035
1088
|
if (!body) throw new CrmInputError("body is required");
|
|
1036
|
-
|
|
1089
|
+
patch.body = body;
|
|
1037
1090
|
}
|
|
1038
|
-
if (Object.keys(
|
|
1039
|
-
const { duplicate } = await db.transact(
|
|
1091
|
+
if (Object.keys(patch).length === 0) throw new CrmInputError("nothing to update");
|
|
1092
|
+
const { duplicate } = await db.transact(patchOps(CRM_NS.activity, opts.id, patch), {
|
|
1040
1093
|
mutationId: opts.mutationId
|
|
1041
1094
|
});
|
|
1042
|
-
return { activity:
|
|
1095
|
+
return { activity: applyPatch(activity, patch), duplicate };
|
|
1043
1096
|
}
|
|
1044
1097
|
async function listActivities(deps, opts) {
|
|
1045
1098
|
const { db } = resolveDeps(deps);
|
|
@@ -1100,6 +1153,8 @@ async function saveView(deps, opts) {
|
|
|
1100
1153
|
ns: CRM_NS.view,
|
|
1101
1154
|
id,
|
|
1102
1155
|
attrs: {
|
|
1156
|
+
id,
|
|
1157
|
+
// mirror the entity id so getView/updateView can read one by id
|
|
1103
1158
|
name: opts.spec.name.trim(),
|
|
1104
1159
|
type: opts.spec.type,
|
|
1105
1160
|
ownerId: opts.ownerId,
|
|
@@ -1200,6 +1255,9 @@ async function saveConfig(deps, patch, opts = {}) {
|
|
|
1200
1255
|
throw new CrmInputError(`template "${id}": text must be a string`);
|
|
1201
1256
|
if (tpl.enabled !== void 0 && typeof tpl.enabled !== "boolean")
|
|
1202
1257
|
throw new CrmInputError(`template "${id}": enabled must be a boolean`);
|
|
1258
|
+
const copy = [tpl.subject, tpl.text].filter((value) => typeof value === "string").join("\n");
|
|
1259
|
+
const unknown = lintTemplate(copy, declared[id].vars).unknown;
|
|
1260
|
+
if (unknown.length) throw new CrmInputError(`template "${id}": unknown vars ${unknown.join(", ")}`);
|
|
1203
1261
|
}
|
|
1204
1262
|
const existing = await getConfig(deps);
|
|
1205
1263
|
const base = existing ?? {
|
|
@@ -1223,23 +1281,17 @@ async function saveConfig(deps, patch, opts = {}) {
|
|
|
1223
1281
|
settings: patch.settings !== void 0 ? patch.settings : base.settings,
|
|
1224
1282
|
updatedAt: now()
|
|
1225
1283
|
};
|
|
1284
|
+
const write = {
|
|
1285
|
+
key: CONFIG_KEY,
|
|
1286
|
+
notificationEmail: merged.notificationEmail ?? null,
|
|
1287
|
+
replyTo: merged.replyTo ?? null,
|
|
1288
|
+
debugEmail: merged.debugEmail ?? null,
|
|
1289
|
+
emailTemplates: merged.emailTemplates,
|
|
1290
|
+
settings: merged.settings,
|
|
1291
|
+
updatedAt: merged.updatedAt
|
|
1292
|
+
};
|
|
1226
1293
|
const { duplicate } = await db.transact(
|
|
1227
|
-
|
|
1228
|
-
{
|
|
1229
|
-
t: "update",
|
|
1230
|
-
ns: CRM_NS.config,
|
|
1231
|
-
id: { ns: CRM_NS.config, attr: "key", value: CONFIG_KEY },
|
|
1232
|
-
attrs: {
|
|
1233
|
-
key: CONFIG_KEY,
|
|
1234
|
-
notificationEmail: merged.notificationEmail ?? null,
|
|
1235
|
-
replyTo: merged.replyTo ?? null,
|
|
1236
|
-
debugEmail: merged.debugEmail ?? null,
|
|
1237
|
-
emailTemplates: merged.emailTemplates,
|
|
1238
|
-
settings: merged.settings,
|
|
1239
|
-
updatedAt: merged.updatedAt
|
|
1240
|
-
}
|
|
1241
|
-
}
|
|
1242
|
-
],
|
|
1294
|
+
patchOps(CRM_NS.config, { ns: CRM_NS.config, attr: "key", value: CONFIG_KEY }, write),
|
|
1243
1295
|
{ mutationId: opts.mutationId }
|
|
1244
1296
|
);
|
|
1245
1297
|
return { config: merged, duplicate };
|
|
@@ -2066,7 +2118,7 @@ var crmIntegration = {
|
|
|
2066
2118
|
provision: {
|
|
2067
2119
|
human: [
|
|
2068
2120
|
"None for the core install \u2014 records/pipelines/email-consent need no external accounts.",
|
|
2069
|
-
"
|
|
2121
|
+
"If the app injects billing, configure that provider's webhook and vault secrets according to the app-owned adapter."
|
|
2070
2122
|
],
|
|
2071
2123
|
cli: [
|
|
2072
2124
|
"POST the merged CRM_SCHEMA to /app/:id/schema.",
|
|
@@ -2075,12 +2127,38 @@ var crmIntegration = {
|
|
|
2075
2127
|
],
|
|
2076
2128
|
doctor: [
|
|
2077
2129
|
"Every crm_* namespace has rules installed (deny-all: no rule = exposed to nothing, but assert explicitly).",
|
|
2078
|
-
"The crm_config
|
|
2079
|
-
"
|
|
2130
|
+
"The guarded crm_config seed targets the declared-unique crm_config.key attribute.",
|
|
2131
|
+
"Code-declared template defaults have no unknown {{vars}}; owner-edited copies are checked when saved."
|
|
2132
|
+
],
|
|
2133
|
+
smoke: [
|
|
2080
2134
|
"A GET probe of <basePath>/records without credentials answers 401 (routes mounted, authorize enforced)."
|
|
2081
2135
|
]
|
|
2082
2136
|
}
|
|
2083
2137
|
};
|
|
2138
|
+
function createCrmIntegration(crm, options = {}) {
|
|
2139
|
+
const basePath = options.basePath ?? "/api/crm";
|
|
2140
|
+
if (!/^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/.test(basePath) || basePath.endsWith("/")) {
|
|
2141
|
+
throw new Error("createCrmIntegration: basePath must be an absolute path without a trailing slash");
|
|
2142
|
+
}
|
|
2143
|
+
const attrs = {
|
|
2144
|
+
emailTemplates: defaultTemplates(crm),
|
|
2145
|
+
settings: options.settings ?? {},
|
|
2146
|
+
updatedAt: options.now ?? Date.now()
|
|
2147
|
+
};
|
|
2148
|
+
if (options.notificationEmail !== void 0) attrs.notificationEmail = options.notificationEmail;
|
|
2149
|
+
if (options.replyTo !== void 0) attrs.replyTo = options.replyTo;
|
|
2150
|
+
if (options.debugEmail !== void 0) attrs.debugEmail = options.debugEmail;
|
|
2151
|
+
return {
|
|
2152
|
+
...crmIntegration,
|
|
2153
|
+
seeds: [{
|
|
2154
|
+
id: "config",
|
|
2155
|
+
ns: CRM_NS.config,
|
|
2156
|
+
key: { attr: "key", value: CONFIG_KEY },
|
|
2157
|
+
attrs
|
|
2158
|
+
}],
|
|
2159
|
+
probes: [{ path: `${basePath}/records`, expectedStatus: 401 }]
|
|
2160
|
+
};
|
|
2161
|
+
}
|
|
2084
2162
|
export {
|
|
2085
2163
|
ACTIVITY_KINDS,
|
|
2086
2164
|
CONFIG_KEY,
|
|
@@ -2108,6 +2186,7 @@ export {
|
|
|
2108
2186
|
canTransition,
|
|
2109
2187
|
channelKey,
|
|
2110
2188
|
compileList,
|
|
2189
|
+
createCrmIntegration,
|
|
2111
2190
|
createCrmRoutes,
|
|
2112
2191
|
createRecord,
|
|
2113
2192
|
crmIntegration,
|