@odla-ai/crm 0.9.1 → 0.9.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/dist/index.d.cts CHANGED
@@ -152,6 +152,14 @@ type CrmRow = {
152
152
  } & Record<string, unknown>;
153
153
  /** Query result: namespace → rows. */
154
154
  type CrmResult = Record<string, CrmRow[]>;
155
+ /** Atomic entity precondition supported by @odla-ai/db transactions. */
156
+ interface CrmTransactGuard {
157
+ ns: string;
158
+ id: string;
159
+ exists: boolean;
160
+ equals?: Record<string, unknown>;
161
+ absent?: string[];
162
+ }
155
163
  /** Aggregate request/response (the odla-db `aggregate` endpoint's shape). */
156
164
  interface CrmAggregateSpec {
157
165
  count?: boolean;
@@ -175,6 +183,7 @@ interface CrmDb {
175
183
  query(query: CrmQuery): Promise<CrmResult>;
176
184
  transact(ops: CrmOp[], opts?: {
177
185
  mutationId?: string;
186
+ guards?: CrmTransactGuard[];
178
187
  }): Promise<{
179
188
  txId: number;
180
189
  duplicate: boolean;
@@ -792,6 +801,16 @@ declare function updateRecord(deps: CrmDeps, opts: {
792
801
  input: Record<string, unknown>;
793
802
  ownerId?: string | null;
794
803
  mutationId?: string;
804
+ /** Compare-and-swap token. The write and optional audit append commit only
805
+ * while the record still has this `updatedAt` value. */
806
+ expectedUpdatedAt?: number;
807
+ /** Optional audit entry committed atomically with the profile patch. */
808
+ audit?: {
809
+ id?: string;
810
+ body: string;
811
+ authorId: string;
812
+ meta?: Record<string, unknown>;
813
+ };
795
814
  }): Promise<{
796
815
  record: CrmRecord;
797
816
  duplicate: boolean;
@@ -818,6 +837,14 @@ declare function setStage(deps: CrmDeps, opts: {
818
837
  to: string;
819
838
  authorId: string;
820
839
  mutationId?: string;
840
+ /** Atomic optimistic token for remote or long-lived editors. */
841
+ expectedUpdatedAt?: number;
842
+ /** Expected current stage. `null` requires the stage attr to be absent. */
843
+ expectedStage?: string | null;
844
+ /** Stable audit id and attribution metadata for federated writes. */
845
+ activityId?: string;
846
+ activityBody?: string;
847
+ activityMeta?: Record<string, unknown>;
821
848
  }): Promise<{
822
849
  record: CrmRecord;
823
850
  from: string | null;
@@ -1527,4 +1554,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1527
1554
  */
1528
1555
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1529
1556
 
1530
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, 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 CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, 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 CrmRecordDelivery, type CrmRecordOrigin, 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 FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, 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, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1557
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, 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 CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, 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 CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, 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, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
package/dist/index.d.ts CHANGED
@@ -152,6 +152,14 @@ type CrmRow = {
152
152
  } & Record<string, unknown>;
153
153
  /** Query result: namespace → rows. */
154
154
  type CrmResult = Record<string, CrmRow[]>;
155
+ /** Atomic entity precondition supported by @odla-ai/db transactions. */
156
+ interface CrmTransactGuard {
157
+ ns: string;
158
+ id: string;
159
+ exists: boolean;
160
+ equals?: Record<string, unknown>;
161
+ absent?: string[];
162
+ }
155
163
  /** Aggregate request/response (the odla-db `aggregate` endpoint's shape). */
156
164
  interface CrmAggregateSpec {
157
165
  count?: boolean;
@@ -175,6 +183,7 @@ interface CrmDb {
175
183
  query(query: CrmQuery): Promise<CrmResult>;
176
184
  transact(ops: CrmOp[], opts?: {
177
185
  mutationId?: string;
186
+ guards?: CrmTransactGuard[];
178
187
  }): Promise<{
179
188
  txId: number;
180
189
  duplicate: boolean;
@@ -792,6 +801,16 @@ declare function updateRecord(deps: CrmDeps, opts: {
792
801
  input: Record<string, unknown>;
793
802
  ownerId?: string | null;
794
803
  mutationId?: string;
804
+ /** Compare-and-swap token. The write and optional audit append commit only
805
+ * while the record still has this `updatedAt` value. */
806
+ expectedUpdatedAt?: number;
807
+ /** Optional audit entry committed atomically with the profile patch. */
808
+ audit?: {
809
+ id?: string;
810
+ body: string;
811
+ authorId: string;
812
+ meta?: Record<string, unknown>;
813
+ };
795
814
  }): Promise<{
796
815
  record: CrmRecord;
797
816
  duplicate: boolean;
@@ -818,6 +837,14 @@ declare function setStage(deps: CrmDeps, opts: {
818
837
  to: string;
819
838
  authorId: string;
820
839
  mutationId?: string;
840
+ /** Atomic optimistic token for remote or long-lived editors. */
841
+ expectedUpdatedAt?: number;
842
+ /** Expected current stage. `null` requires the stage attr to be absent. */
843
+ expectedStage?: string | null;
844
+ /** Stable audit id and attribution metadata for federated writes. */
845
+ activityId?: string;
846
+ activityBody?: string;
847
+ activityMeta?: Record<string, unknown>;
821
848
  }): Promise<{
822
849
  record: CrmRecord;
823
850
  from: string | null;
@@ -1527,4 +1554,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1527
1554
  */
1528
1555
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1529
1556
 
1530
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, 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 CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, 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 CrmRecordDelivery, type CrmRecordOrigin, 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 FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, 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, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1557
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, 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 CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, 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 CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, 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, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
package/dist/index.js CHANGED
@@ -1010,7 +1010,7 @@ async function createRecord(deps, opts) {
1010
1010
  return { id, duplicate, record: { id, ...attrs } };
1011
1011
  }
1012
1012
  async function updateRecord(deps, opts) {
1013
- const { crm, db, now } = resolveDeps(deps);
1013
+ const { crm, db, now, newId } = resolveDeps(deps);
1014
1014
  const existing = await mustGetRecord(deps, opts.id);
1015
1015
  const prepared = crm.prepare(existing.type, opts.input, existing);
1016
1016
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
@@ -1029,8 +1029,33 @@ async function updateRecord(deps, opts) {
1029
1029
  const score = scoreOf(deps, existing.type, candidate);
1030
1030
  if (score !== void 0) patch.score = score;
1031
1031
  const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];
1032
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1033
- return { record: applyPatch(existing, patch, prepared.retract), duplicate };
1032
+ if (opts.audit) {
1033
+ const body = opts.audit.body.trim();
1034
+ if (!body) throw new CrmInputError("audit body is required");
1035
+ const id = opts.audit.id ?? newId();
1036
+ ops.push({
1037
+ t: "update",
1038
+ ns: CRM_NS.activity,
1039
+ id,
1040
+ attrs: {
1041
+ id,
1042
+ recordId: existing.id,
1043
+ kind: "note",
1044
+ body,
1045
+ authorId: opts.audit.authorId,
1046
+ createdAt: now(),
1047
+ ...opts.audit.meta ? { meta: opts.audit.meta } : {}
1048
+ }
1049
+ });
1050
+ }
1051
+ const { duplicate } = await db.transact(ops, {
1052
+ mutationId: opts.mutationId,
1053
+ ...opts.expectedUpdatedAt === void 0 ? {} : { guards: [{ ns: CRM_NS.record, id: existing.id, exists: true, equals: { updatedAt: opts.expectedUpdatedAt } }] }
1054
+ });
1055
+ return {
1056
+ record: duplicate ? await mustGetRecord(deps, existing.id) : applyPatch(existing, patch, prepared.retract),
1057
+ duplicate
1058
+ };
1034
1059
  }
1035
1060
  async function setArchived(deps, opts) {
1036
1061
  const { db, now } = resolveDeps(deps);
@@ -1057,7 +1082,7 @@ async function setStage(deps, opts) {
1057
1082
  stageChangedAt: at,
1058
1083
  updatedAt: at
1059
1084
  };
1060
- const activityId = newId();
1085
+ const activityId = opts.activityId ?? newId();
1061
1086
  const ops = [
1062
1087
  { t: "update", ns: CRM_NS.record, id: record.id, attrs },
1063
1088
  {
@@ -1069,14 +1094,30 @@ async function setStage(deps, opts) {
1069
1094
  // mirror the entity id so the activity is readable by id
1070
1095
  recordId: record.id,
1071
1096
  kind: "stage_change",
1072
- body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1097
+ body: opts.activityBody ?? `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1073
1098
  authorId: opts.authorId,
1074
- createdAt: at
1099
+ createdAt: at,
1100
+ ...opts.activityMeta ? { meta: opts.activityMeta } : {}
1075
1101
  }
1076
1102
  }
1077
1103
  ];
1078
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1079
- const updated = { ...record, ...attrs };
1104
+ const equals = {};
1105
+ if (opts.expectedUpdatedAt !== void 0) equals.updatedAt = opts.expectedUpdatedAt;
1106
+ if (typeof opts.expectedStage === "string") equals.stage = opts.expectedStage;
1107
+ const guarded = opts.expectedUpdatedAt !== void 0 || opts.expectedStage !== void 0;
1108
+ const { duplicate } = await db.transact(ops, {
1109
+ mutationId: opts.mutationId,
1110
+ ...guarded ? {
1111
+ guards: [{
1112
+ ns: CRM_NS.record,
1113
+ id: record.id,
1114
+ exists: true,
1115
+ ...Object.keys(equals).length ? { equals } : {},
1116
+ ...opts.expectedStage === null ? { absent: ["stage"] } : {}
1117
+ }]
1118
+ } : {}
1119
+ });
1120
+ const updated = duplicate ? await mustGetRecord(deps, record.id) : { ...record, ...attrs };
1080
1121
  return {
1081
1122
  record: updated,
1082
1123
  from: record.stage ?? null,