@voyantjs/crm 0.26.3 → 0.26.5

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.
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Customer signals — lighter than `opportunities` (no deal value or
3
+ * stages), heavier than `segments` (lifecycle + assignment). Records
4
+ * "person X expressed interest in product/departure Y from source Z,
5
+ * status pending". The most common use cases:
6
+ *
7
+ * - Notify-availability ("ping me when this departure opens up")
8
+ * - Wishlist / saved trips
9
+ * - Inquiry captured by an operator (phone call, web form)
10
+ * - Request-offer pre-pipeline that may or may not become a booking
11
+ * - Abandoned-cart recovery
12
+ *
13
+ * Cross-module IDs (`productId`, `optionUnitId`, `resolvedBookingId`)
14
+ * are intentionally plain `text()` columns rather than FK references
15
+ * — voyant's project-wide rule is that cross-module FKs go through
16
+ * link tables or stay loose. The signal is owned by CRM; products
17
+ * and bookings reference its id, not the other way around.
18
+ */
19
+ import { typeId, typeIdRef } from "@voyantjs/db/lib/typeid-column";
20
+ import { index, jsonb, pgEnum, pgTable, text, timestamp } from "drizzle-orm/pg-core";
21
+ import { people } from "./schema-accounts.js";
22
+ export const customerSignalKindEnum = pgEnum("customer_signal_kind", [
23
+ "wishlist",
24
+ "notify",
25
+ "inquiry",
26
+ "request_offer",
27
+ "referral",
28
+ ]);
29
+ export const customerSignalSourceEnum = pgEnum("customer_signal_source", [
30
+ "form",
31
+ "phone",
32
+ "admin",
33
+ "abandoned_cart",
34
+ "website",
35
+ "booking",
36
+ ]);
37
+ export const customerSignalStatusEnum = pgEnum("customer_signal_status", [
38
+ "new",
39
+ "contacted",
40
+ "qualified",
41
+ "converted",
42
+ "lost",
43
+ "expired",
44
+ ]);
45
+ export const customerSignals = pgTable("customer_signals", {
46
+ id: typeId("customer_signals"),
47
+ personId: typeIdRef("person_id")
48
+ .notNull()
49
+ .references(() => people.id, { onDelete: "cascade" }),
50
+ /** Optional reference into `@voyantjs/products`. Plain text — no FK. */
51
+ productId: text("product_id"),
52
+ /** Optional reference into a product's `option_units` row (the "departure"-equivalent). Plain text — no FK. */
53
+ optionUnitId: text("option_unit_id"),
54
+ kind: customerSignalKindEnum("kind").notNull(),
55
+ source: customerSignalSourceEnum("source").notNull(),
56
+ status: customerSignalStatusEnum("status").notNull().default("new"),
57
+ /**
58
+ * Free-form priority. The validation layer constrains input to
59
+ * `low | normal | high | urgent`; storing as text keeps room for
60
+ * deployment-specific values without a DB migration.
61
+ */
62
+ priority: text("priority").notNull().default("normal"),
63
+ notes: text("notes"),
64
+ tags: jsonb("tags").$type().notNull().default([]),
65
+ /** User id (Better Auth user) of the staff member assigned to follow up. */
66
+ assignedToUserId: text("assigned_to_user_id"),
67
+ followUpAt: timestamp("follow_up_at", { withTimezone: true }),
68
+ /** Set when the signal was converted into a real booking. Plain text — cross-module FK. */
69
+ resolvedBookingId: text("resolved_booking_id"),
70
+ /** Free-form provenance id (form-submission id, abandoned-cart key, ...). */
71
+ sourceSubmissionId: text("source_submission_id"),
72
+ metadata: jsonb("metadata").$type(),
73
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
74
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
75
+ }, (table) => [
76
+ index("idx_customer_signals_person_status_created").on(table.personId, table.status, table.createdAt),
77
+ index("idx_customer_signals_assignee_status").on(table.assignedToUserId, table.status),
78
+ index("idx_customer_signals_kind").on(table.kind),
79
+ index("idx_customer_signals_resolved_booking").on(table.resolvedBookingId),
80
+ ]);
package/dist/schema.d.ts CHANGED
@@ -4,4 +4,5 @@ export * from "./schema-activities.js";
4
4
  export * from "./schema-relations.js";
5
5
  export * from "./schema-sales.js";
6
6
  export * from "./schema-shared.js";
7
+ export * from "./schema-signals.js";
7
8
  //# sourceMappingURL=schema.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,cAAc,sBAAsB,CAAA;AACpC,cAAc,wBAAwB,CAAA;AACtC,cAAc,uBAAuB,CAAA;AACrC,cAAc,mBAAmB,CAAA;AACjC,cAAc,oBAAoB,CAAA"}
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,cAAc,sBAAsB,CAAA;AACpC,cAAc,wBAAwB,CAAA;AACtC,cAAc,uBAAuB,CAAA;AACrC,cAAc,mBAAmB,CAAA;AACjC,cAAc,oBAAoB,CAAA;AAClC,cAAc,qBAAqB,CAAA"}
package/dist/schema.js CHANGED
@@ -4,3 +4,4 @@ export * from "./schema-activities.js";
4
4
  export * from "./schema-relations.js";
5
5
  export * from "./schema-sales.js";
6
6
  export * from "./schema-shared.js";
7
+ export * from "./schema-signals.js";
@@ -56,8 +56,6 @@ export declare function personBaseFields(data: CreatePersonInput | UpdatePersonI
56
56
  enc: string;
57
57
  } | null | undefined;
58
58
  };
59
- export declare function rebuildPersonDirectoryProjection(db: PostgresJsDatabase, personId: string): Promise<void>;
60
- export declare function rebuildPersonDirectoryProjections(db: PostgresJsDatabase, personIds: string[]): Promise<void>;
61
59
  export declare function syncPersonIdentity(db: PostgresJsDatabase, personId: string, data: PersonIdentityInput): Promise<void>;
62
60
  export declare function deletePersonIdentity(db: PostgresJsDatabase, personId: string): Promise<void>;
63
61
  export declare function hydratePeople<T extends {
@@ -1 +1 @@
1
- {"version":3,"file":"accounts-shared.d.ts","sourceRoot":"","sources":["../../src/service/accounts-shared.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,mBAAmB,EACnB,wBAAwB,EACzB,MAAM,+BAA+B,CAAA;AAEtC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAA;AACjE,OAAO,KAAK,EAAE,CAA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AoB,CAAC,EAAE,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,iBAUlF;AAED,wBAAsB,aAAa,CAAC,CAAC,SAAS;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,EAC1D,EAAE,EAAE,kBAAkB,EACtB,IAAI,EAAE,CAAC,EAAE,GACR,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,oBAAoB,CAAC,CAAC,CAiB1C"}
@@ -1,7 +1,6 @@
1
- import { identityContactPoints } from "@voyantjs/identity/schema";
2
1
  import { identityService } from "@voyantjs/identity/service";
3
- import { and, eq, inArray } from "drizzle-orm";
4
- import { personDirectoryProjections } from "../schema.js";
2
+ import { inArray } from "drizzle-orm";
3
+ import { personDirectoryView } from "../schema.js";
5
4
  import { isManagedBySource, normalizeContactValue, toNullableTrimmed } from "./helpers.js";
6
5
  export const organizationEntityType = "organization";
7
6
  export const personEntityType = "person";
@@ -37,80 +36,30 @@ export function personBaseFields(data) {
37
36
  insuranceEncrypted: data.insuranceEncrypted,
38
37
  };
39
38
  }
40
- async function buildPersonDirectoryProjectionRows(db, personIds) {
41
- if (personIds.length === 0) {
42
- return [];
43
- }
44
- const ids = [...new Set(personIds)];
45
- const contactPoints = await db
46
- .select()
47
- .from(identityContactPoints)
48
- .where(and(eq(identityContactPoints.entityType, personEntityType), inArray(identityContactPoints.entityId, ids)));
49
- const contactPointMap = new Map();
50
- for (const point of contactPoints) {
51
- const bucket = contactPointMap.get(point.entityId) ?? [];
52
- bucket.push(point);
53
- contactPointMap.set(point.entityId, bucket);
54
- }
55
- return ids.map((personId) => {
56
- const entityContactPoints = contactPointMap.get(personId) ?? [];
57
- const findPrimaryContactPoint = (kind) => entityContactPoints.find((point) => point.kind === kind && point.isPrimary)?.value ??
58
- entityContactPoints.find((point) => point.kind === kind)?.value ??
59
- null;
60
- return {
61
- personId,
62
- email: findPrimaryContactPoint("email"),
63
- phone: findPrimaryContactPoint("phone"),
64
- website: findPrimaryContactPoint("website"),
65
- };
66
- });
67
- }
68
- export async function rebuildPersonDirectoryProjection(db, personId) {
69
- return rebuildPersonDirectoryProjections(db, [personId]);
70
- }
71
- export async function rebuildPersonDirectoryProjections(db, personIds) {
72
- const ids = [...new Set(personIds)];
73
- if (ids.length === 0) {
74
- return;
75
- }
76
- const rows = await buildPersonDirectoryProjectionRows(db, ids);
77
- await db
78
- .delete(personDirectoryProjections)
79
- .where(inArray(personDirectoryProjections.personId, ids));
80
- await db.insert(personDirectoryProjections).values(rows);
81
- }
82
- async function ensurePersonDirectoryProjectionMap(db, personIds) {
39
+ /**
40
+ * Reads the per-person `(email, phone, website)` triple from the
41
+ * `person_directory` view (replaces the old projection cache —
42
+ * see #446). The view is computed via indexed `LATERAL` joins on
43
+ * `identity_contact_points`, so callers no longer need a rebuild
44
+ * step after contact-point edits.
45
+ */
46
+ async function loadPersonDirectoryMap(db, personIds) {
83
47
  const ids = [...new Set(personIds)];
84
48
  if (ids.length === 0) {
85
49
  return new Map();
86
50
  }
87
- const existing = await db
51
+ const rows = await db
88
52
  .select()
89
- .from(personDirectoryProjections)
90
- .where(inArray(personDirectoryProjections.personId, ids));
53
+ .from(personDirectoryView)
54
+ .where(inArray(personDirectoryView.personId, ids));
91
55
  const map = new Map();
92
- for (const projection of existing) {
93
- map.set(projection.personId, {
94
- email: projection.email,
95
- phone: projection.phone,
96
- website: projection.website,
56
+ for (const row of rows) {
57
+ map.set(row.personId, {
58
+ email: row.email,
59
+ phone: row.phone,
60
+ website: row.website,
97
61
  });
98
62
  }
99
- const missingIds = ids.filter((id) => !map.has(id));
100
- if (missingIds.length > 0) {
101
- await rebuildPersonDirectoryProjections(db, missingIds);
102
- const rebuilt = await db
103
- .select()
104
- .from(personDirectoryProjections)
105
- .where(inArray(personDirectoryProjections.personId, missingIds));
106
- for (const projection of rebuilt) {
107
- map.set(projection.personId, {
108
- email: projection.email,
109
- phone: projection.phone,
110
- website: projection.website,
111
- });
112
- }
113
- }
114
63
  for (const id of ids) {
115
64
  if (!map.has(id)) {
116
65
  map.set(id, emptyPersonHydratedFields());
@@ -157,7 +106,6 @@ export async function syncPersonIdentity(db, personId, data) {
157
106
  if (managedAddress) {
158
107
  await identityService.deleteAddress(db, managedAddress.id);
159
108
  }
160
- await rebuildPersonDirectoryProjection(db, personId);
161
109
  }
162
110
  export async function deletePersonIdentity(db, personId) {
163
111
  const [contactPoints, addresses] = await Promise.all([
@@ -177,11 +125,11 @@ export async function hydratePeople(db, rows) {
177
125
  }));
178
126
  }
179
127
  const ids = rows.map((row) => row.id);
180
- const projectionMap = await ensurePersonDirectoryProjectionMap(db, ids);
128
+ const directoryMap = await loadPersonDirectoryMap(db, ids);
181
129
  return rows.map((row) => {
182
130
  return {
183
131
  ...row,
184
- ...(projectionMap.get(row.id) ?? emptyPersonHydratedFields()),
132
+ ...(directoryMap.get(row.id) ?? emptyPersonHydratedFields()),
185
133
  };
186
134
  });
187
135
  }