@odla-ai/crm 0.9.1 → 0.10.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/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;
@@ -755,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
755
764
  unused: string[];
756
765
  };
757
766
 
758
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
759
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
760
769
  /** Load one record by id, or null. */
761
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -772,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
772
781
  /** Create a record of `type` from custom-field input. Also creates (or
773
782
  * upserts) the primary email contact channel when the type declares an
774
783
  * `emailField`. New records rank at `now` so manual order defaults to
775
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
776
787
  declare function createRecord(deps: CrmDeps, opts: {
777
788
  type: string;
778
789
  input: Record<string, unknown>;
779
790
  ownerId?: string;
780
- stage?: string;
791
+ stage?: string | null;
781
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
782
799
  }): Promise<{
783
800
  id: string;
784
801
  duplicate: boolean;
@@ -792,6 +809,16 @@ declare function updateRecord(deps: CrmDeps, opts: {
792
809
  input: Record<string, unknown>;
793
810
  ownerId?: string | null;
794
811
  mutationId?: string;
812
+ /** Compare-and-swap token. The write and optional audit append commit only
813
+ * while the record still has this `updatedAt` value. */
814
+ expectedUpdatedAt?: number;
815
+ /** Optional audit entry committed atomically with the profile patch. */
816
+ audit?: {
817
+ id?: string;
818
+ body: string;
819
+ authorId: string;
820
+ meta?: Record<string, unknown>;
821
+ };
795
822
  }): Promise<{
796
823
  record: CrmRecord;
797
824
  duplicate: boolean;
@@ -818,6 +845,14 @@ declare function setStage(deps: CrmDeps, opts: {
818
845
  to: string;
819
846
  authorId: string;
820
847
  mutationId?: string;
848
+ /** Atomic optimistic token for remote or long-lived editors. */
849
+ expectedUpdatedAt?: number;
850
+ /** Expected current stage. `null` requires the stage attr to be absent. */
851
+ expectedStage?: string | null;
852
+ /** Stable audit id and attribution metadata for federated writes. */
853
+ activityId?: string;
854
+ activityBody?: string;
855
+ activityMeta?: Record<string, unknown>;
821
856
  }): Promise<{
822
857
  record: CrmRecord;
823
858
  from: string | null;
@@ -993,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
993
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
994
1029
  * the ops plus the `emailStatus` the record should fold to.
995
1030
  */
996
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
997
1035
  ops: CrmOp[];
998
1036
  emailStatus: EmailStatus;
999
1037
  };
@@ -1323,7 +1361,7 @@ declare class CrmClient {
1323
1361
  type: string;
1324
1362
  input: Record<string, unknown>;
1325
1363
  ownerId?: string;
1326
- stage?: string;
1364
+ stage?: string | null;
1327
1365
  mutationId?: string;
1328
1366
  }): Promise<{
1329
1367
  id: string;
@@ -1527,4 +1565,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1527
1565
  */
1528
1566
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1529
1567
 
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 };
1568
+ 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;
@@ -755,7 +764,7 @@ declare function lintTemplate(template: string, knownVars: readonly string[]): {
755
764
  unused: string[];
756
765
  };
757
766
 
758
- /** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */
767
+ /** Decode a raw row to {@link CrmRecord}, normalizing declared dates and defaulting JSON fields. */
759
768
  declare function rowToRecord(row: CrmRow): CrmRecord;
760
769
  /** Load one record by id, or null. */
761
770
  declare function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null>;
@@ -772,13 +781,21 @@ declare function listRecords(deps: CrmDeps, params: CrmListParams): Promise<{
772
781
  /** Create a record of `type` from custom-field input. Also creates (or
773
782
  * upserts) the primary email contact channel when the type declares an
774
783
  * `emailField`. New records rank at `now` so manual order defaults to
775
- * creation order. */
784
+ * creation order. `stage: null` explicitly keeps a record outside its pipeline;
785
+ * omission retains the configured initial stage. An explicit `id` is create-only
786
+ * (atomically guarded), for convergent server projections. */
776
787
  declare function createRecord(deps: CrmDeps, opts: {
777
788
  type: string;
778
789
  input: Record<string, unknown>;
779
790
  ownerId?: string;
780
- stage?: string;
791
+ stage?: string | null;
781
792
  mutationId?: string;
793
+ id?: string;
794
+ guards?: CrmTransactGuard[];
795
+ emailConsent?: {
796
+ state: ConsentState;
797
+ source: string;
798
+ };
782
799
  }): Promise<{
783
800
  id: string;
784
801
  duplicate: boolean;
@@ -792,6 +809,16 @@ declare function updateRecord(deps: CrmDeps, opts: {
792
809
  input: Record<string, unknown>;
793
810
  ownerId?: string | null;
794
811
  mutationId?: string;
812
+ /** Compare-and-swap token. The write and optional audit append commit only
813
+ * while the record still has this `updatedAt` value. */
814
+ expectedUpdatedAt?: number;
815
+ /** Optional audit entry committed atomically with the profile patch. */
816
+ audit?: {
817
+ id?: string;
818
+ body: string;
819
+ authorId: string;
820
+ meta?: Record<string, unknown>;
821
+ };
795
822
  }): Promise<{
796
823
  record: CrmRecord;
797
824
  duplicate: boolean;
@@ -818,6 +845,14 @@ declare function setStage(deps: CrmDeps, opts: {
818
845
  to: string;
819
846
  authorId: string;
820
847
  mutationId?: string;
848
+ /** Atomic optimistic token for remote or long-lived editors. */
849
+ expectedUpdatedAt?: number;
850
+ /** Expected current stage. `null` requires the stage attr to be absent. */
851
+ expectedStage?: string | null;
852
+ /** Stable audit id and attribution metadata for federated writes. */
853
+ activityId?: string;
854
+ activityBody?: string;
855
+ activityMeta?: Record<string, unknown>;
821
856
  }): Promise<{
822
857
  record: CrmRecord;
823
858
  from: string | null;
@@ -993,7 +1028,10 @@ declare function listChannels(deps: CrmDeps, recordId: string): Promise<CrmConta
993
1028
  * demote any other primary, or — with `email: null` — just demote. Returns
994
1029
  * the ops plus the `emailStatus` the record should fold to.
995
1030
  */
996
- declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[]): {
1031
+ declare function emailChannelOps(deps: CrmDeps, recordId: string, email: string | null, existing: readonly CrmContactChannel[], initialConsent?: {
1032
+ state: ConsentState;
1033
+ source: string;
1034
+ }): {
997
1035
  ops: CrmOp[];
998
1036
  emailStatus: EmailStatus;
999
1037
  };
@@ -1323,7 +1361,7 @@ declare class CrmClient {
1323
1361
  type: string;
1324
1362
  input: Record<string, unknown>;
1325
1363
  ownerId?: string;
1326
- stage?: string;
1364
+ stage?: string | null;
1327
1365
  mutationId?: string;
1328
1366
  }): Promise<{
1329
1367
  id: string;
@@ -1527,4 +1565,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1527
1565
  */
1528
1566
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1529
1567
 
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 };
1568
+ 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
@@ -837,7 +837,7 @@ async function listChannels(deps, recordId) {
837
837
  });
838
838
  return (result[CRM_NS.channel] ?? []).map(rowToChannel);
839
839
  }
840
- function emailChannelOps(deps, recordId, email, existing) {
840
+ function emailChannelOps(deps, recordId, email, existing, initialConsent = { state: "subscribed", source: "record-write" }) {
841
841
  const { now, newId } = resolveDeps(deps);
842
842
  const ops = [];
843
843
  const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
@@ -861,14 +861,14 @@ function emailChannelOps(deps, recordId, email, existing) {
861
861
  kind: "email",
862
862
  value: email,
863
863
  isPrimary: true,
864
- consent: "subscribed",
864
+ consent: initialConsent.state,
865
865
  consentAt: now(),
866
- consentSource: "record-write",
866
+ consentSource: initialConsent.source,
867
867
  unsubscribeToken: newId(),
868
868
  createdAt: now()
869
869
  }
870
870
  });
871
- return { ops, emailStatus: "ok" };
871
+ return { ops, emailStatus: foldEmailStatus(initialConsent.state) };
872
872
  }
873
873
  async function applyConsent(deps, opts) {
874
874
  const { db, now } = resolveDeps(deps);
@@ -924,7 +924,7 @@ function applyPatch(base, patch, alsoClear = []) {
924
924
 
925
925
  // src/records.ts
926
926
  function rowToRecord(row) {
927
- const record = row;
927
+ const record = rowAsWritten(CRM_NS.record, row);
928
928
  return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
929
929
  }
930
930
  async function getRecord(deps, id) {
@@ -974,9 +974,9 @@ async function createRecord(deps, opts) {
974
974
  const { crm, db, now, newId } = resolveDeps(deps);
975
975
  const prepared = crm.prepare(opts.type, opts.input);
976
976
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
977
- const id = newId();
977
+ const id = opts.id ?? newId();
978
978
  const at = now();
979
- const stage = opts.stage ?? crm.initialStage(opts.type);
979
+ const stage = opts.stage === void 0 ? crm.initialStage(opts.type) : opts.stage;
980
980
  const attrs = {
981
981
  id,
982
982
  // mirror the entity id as an attr so `where: { id }` reads can find it
@@ -996,7 +996,7 @@ async function createRecord(deps, opts) {
996
996
  const ops = [];
997
997
  const email = prepared.attrs["primaryEmail"] ?? null;
998
998
  if (crm.type(opts.type).emailField) {
999
- const channel = emailChannelOps(deps, id, email, []);
999
+ const channel = emailChannelOps(deps, id, email, [], opts.emailConsent);
1000
1000
  attrs.emailStatus = channel.emailStatus;
1001
1001
  ops.push(...channel.ops);
1002
1002
  } else {
@@ -1006,11 +1006,13 @@ async function createRecord(deps, opts) {
1006
1006
  const score = scoreOf(deps, opts.type, candidate);
1007
1007
  if (score !== void 0) attrs.score = score;
1008
1008
  ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
1009
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1009
+ const guards = [...opts.guards ?? [], ...opts.id ? [{ ns: CRM_NS.record, id, exists: false }] : []];
1010
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId, ...guards.length ? { guards } : {} });
1011
+ if (duplicate && opts.id) return { id, duplicate, record: await mustGetRecord(deps, id) };
1010
1012
  return { id, duplicate, record: { id, ...attrs } };
1011
1013
  }
1012
1014
  async function updateRecord(deps, opts) {
1013
- const { crm, db, now } = resolveDeps(deps);
1015
+ const { crm, db, now, newId } = resolveDeps(deps);
1014
1016
  const existing = await mustGetRecord(deps, opts.id);
1015
1017
  const prepared = crm.prepare(existing.type, opts.input, existing);
1016
1018
  if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
@@ -1029,8 +1031,33 @@ async function updateRecord(deps, opts) {
1029
1031
  const score = scoreOf(deps, existing.type, candidate);
1030
1032
  if (score !== void 0) patch.score = score;
1031
1033
  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 };
1034
+ if (opts.audit) {
1035
+ const body = opts.audit.body.trim();
1036
+ if (!body) throw new CrmInputError("audit body is required");
1037
+ const id = opts.audit.id ?? newId();
1038
+ ops.push({
1039
+ t: "update",
1040
+ ns: CRM_NS.activity,
1041
+ id,
1042
+ attrs: {
1043
+ id,
1044
+ recordId: existing.id,
1045
+ kind: "note",
1046
+ body,
1047
+ authorId: opts.audit.authorId,
1048
+ createdAt: now(),
1049
+ ...opts.audit.meta ? { meta: opts.audit.meta } : {}
1050
+ }
1051
+ });
1052
+ }
1053
+ const { duplicate } = await db.transact(ops, {
1054
+ mutationId: opts.mutationId,
1055
+ ...opts.expectedUpdatedAt === void 0 ? {} : { guards: [{ ns: CRM_NS.record, id: existing.id, exists: true, equals: { updatedAt: opts.expectedUpdatedAt } }] }
1056
+ });
1057
+ return {
1058
+ record: duplicate ? await mustGetRecord(deps, existing.id) : applyPatch(existing, patch, prepared.retract),
1059
+ duplicate
1060
+ };
1034
1061
  }
1035
1062
  async function setArchived(deps, opts) {
1036
1063
  const { db, now } = resolveDeps(deps);
@@ -1057,7 +1084,7 @@ async function setStage(deps, opts) {
1057
1084
  stageChangedAt: at,
1058
1085
  updatedAt: at
1059
1086
  };
1060
- const activityId = newId();
1087
+ const activityId = opts.activityId ?? newId();
1061
1088
  const ops = [
1062
1089
  { t: "update", ns: CRM_NS.record, id: record.id, attrs },
1063
1090
  {
@@ -1069,14 +1096,30 @@ async function setStage(deps, opts) {
1069
1096
  // mirror the entity id so the activity is readable by id
1070
1097
  recordId: record.id,
1071
1098
  kind: "stage_change",
1072
- body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1099
+ body: opts.activityBody ?? `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
1073
1100
  authorId: opts.authorId,
1074
- createdAt: at
1101
+ createdAt: at,
1102
+ ...opts.activityMeta ? { meta: opts.activityMeta } : {}
1075
1103
  }
1076
1104
  }
1077
1105
  ];
1078
- const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1079
- const updated = { ...record, ...attrs };
1106
+ const equals = {};
1107
+ if (opts.expectedUpdatedAt !== void 0) equals.updatedAt = opts.expectedUpdatedAt;
1108
+ if (typeof opts.expectedStage === "string") equals.stage = opts.expectedStage;
1109
+ const guarded = opts.expectedUpdatedAt !== void 0 || opts.expectedStage !== void 0;
1110
+ const { duplicate } = await db.transact(ops, {
1111
+ mutationId: opts.mutationId,
1112
+ ...guarded ? {
1113
+ guards: [{
1114
+ ns: CRM_NS.record,
1115
+ id: record.id,
1116
+ exists: true,
1117
+ ...Object.keys(equals).length ? { equals } : {},
1118
+ ...opts.expectedStage === null ? { absent: ["stage"] } : {}
1119
+ }]
1120
+ } : {}
1121
+ });
1122
+ const updated = duplicate ? await mustGetRecord(deps, record.id) : { ...record, ...attrs };
1080
1123
  return {
1081
1124
  record: updated,
1082
1125
  from: record.stage ?? null,
@@ -1725,10 +1768,12 @@ async function recordCanEmail(deps, recordId, cls) {
1725
1768
  async function linkIdentity(deps, opts) {
1726
1769
  const { db, now } = resolveDeps(deps);
1727
1770
  const record = await mustGetRecord(deps, opts.recordId);
1771
+ if (record.clerkUserId) return { linked: true, clerkUserId: record.clerkUserId };
1728
1772
  const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1729
1773
  if (!email) throw new CrmInputError("record has no email to match on");
1730
- const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1731
- const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1774
+ const result = await db.query({ $users: { $: { where: { email }, limit: 2 } } });
1775
+ const users = result["$users"] ?? [];
1776
+ const user = users.length === 1 && !users[0]["deleted"] ? users[0] : void 0;
1732
1777
  if (!user) return { linked: false };
1733
1778
  const { duplicate } = await db.transact(
1734
1779
  [
@@ -1739,7 +1784,24 @@ async function linkIdentity(deps, opts) {
1739
1784
  attrs: { clerkUserId: user.id, updatedAt: now() }
1740
1785
  }
1741
1786
  ],
1742
- { mutationId: opts.mutationId }
1787
+ { mutationId: opts.mutationId, guards: [
1788
+ {
1789
+ ns: "$users",
1790
+ id: user.id,
1791
+ exists: true,
1792
+ equals: {
1793
+ email,
1794
+ ...user["deleted"] !== void 0 ? { deleted: user["deleted"] } : {}
1795
+ },
1796
+ ...user["deleted"] === void 0 ? { absent: ["deleted"] } : {}
1797
+ },
1798
+ {
1799
+ ns: CRM_NS.record,
1800
+ id: record.id,
1801
+ exists: true,
1802
+ ...record.clerkUserId === null ? { equals: { clerkUserId: null } } : { absent: ["clerkUserId"] }
1803
+ }
1804
+ ] }
1743
1805
  );
1744
1806
  return { linked: true, clerkUserId: user.id, duplicate };
1745
1807
  }
@@ -2080,7 +2142,7 @@ async function handleRecordsRoot(ctx, req, url) {
2080
2142
  type: str(body, "type"),
2081
2143
  input: obj(body, "input"),
2082
2144
  ownerId: optStr(body, "ownerId"),
2083
- stage: optStr(body, "stage"),
2145
+ stage: nullableStr(body, "stage"),
2084
2146
  mutationId: optStr(body, "mutationId")
2085
2147
  });
2086
2148
  return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);