@odla-ai/crm 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @odla-ai/crm
2
+
3
+ A flexible CRM layer for odla apps — configurable record types (people, companies, anything), pipelines with gated transitions, tags, notes and follow-ups, consent-gated email with audited sends, and saved views, all on [odla-db](https://odla.ai/docs/packages/db) with a mountable route factory and an admin UI kit over [@odla-ai/ui](https://odla.ai/docs/packages/ui).
4
+
5
+ ```sh
6
+ npm i @odla-ai/crm
7
+ ```
8
+
9
+ > **Agentic experiment.** This package is built and maintained by AI agents working from bounded runbooks with human review. Review its documented guarantees before relying on it.
10
+
11
+ ## The shape
12
+
13
+ The CRM is a **schema + deny-all rules + a route factory + an admin UI kit** — not a service you run.
14
+
15
+ - **Record types are configuration, not schema.** Every type shares one generic `crm_record` namespace: promoted columns for the hot paths every type has (name, stage + position, rank, score, contactability, billing cache), nine typed slot columns (`s1`–`s4`, `n1`–`n3`, `d1`–`d2`) that index each type's custom sortable/filterable fields, the complete field payload in a json column, and a denormalized FTS haystack rebuilt on every write.
16
+ - **Tags and relations are natural-key join rows** (`recordId:tag`, `fromId:relation:toId`) — idempotent upserts that double as cohort provenance.
17
+ - **Consent is a table-driven state machine.** Suppression is admin-sticky, an unsubscribe is undone only by the contact's own opt-in, hard bounces land from anywhere, and `unsubscribed` still receives transactional mail. Marketing sends carry `{{unsubscribeUrl}}` and RFC 8058 one-click headers automatically.
18
+ - **All access is worker-mediated by design.** Slot mapping, searchText rebuilds, pipeline gates, and validation are functions of your config — CEL rules cannot express them — so every `crm_*` namespace installs deny-all and `createCrmRoutes` (admin key, behind your own `authorize`) is the only door.
19
+ - **Zero runtime dependencies.** The db client and email transport are injected structurally: a real `@odla-ai/db` `AdminDb` and a thin wrapper over `@odla-ai/email`'s `sendMessage` satisfy the interfaces.
20
+
21
+ ## Quick start
22
+
23
+ ```ts
24
+ import { defineCrm, createCrmRoutes } from "@odla-ai/crm";
25
+ import { init } from "@odla-ai/db";
26
+
27
+ const crm = defineCrm({
28
+ types: {
29
+ person: {
30
+ label: "Person",
31
+ emailField: "email",
32
+ fields: {
33
+ name: { type: "string", required: true },
34
+ email: { type: "email" },
35
+ state: { type: "enum", options: ["UT", "CA"], slot: "s1" },
36
+ netWorth: { type: "number", slot: "n1" },
37
+ },
38
+ pipeline: {
39
+ stages: [{ id: "prospect" }, { id: "applied" }, { id: "member", terminal: true }],
40
+ transitions: { prospect: ["applied"], applied: ["member"] },
41
+ gates: { member: (r) => (r.emailStatus === "none" ? "needs an email first" : null) },
42
+ },
43
+ facets: { identity: true, email: true, rank: "manual" },
44
+ onTransition: { member: async (r) => promoteToMember(r) }, // post-commit hook
45
+ },
46
+ company: { label: "Company", fields: { name: { type: "string", required: true } } },
47
+ },
48
+ relations: { works_at: { from: "person", to: "company", label: "works at" } },
49
+ templates: {
50
+ welcome: { vars: ["firstName"], class: "transactional",
51
+ defaults: { subject: "Welcome {{firstName}}", text: "You're in." } },
52
+ newsletter: { vars: ["firstName", "unsubscribeUrl"], class: "marketing" },
53
+ },
54
+ });
55
+
56
+ // Provision once (the odla CLI automates this):
57
+ // POST crm.schema → /app/:id/schema
58
+ // crm.rules → /app/:id/admin/rules
59
+
60
+ const db = init({ appId, adminToken, endpoint }); // @odla-ai/db admin client
61
+ const crmRoutes = createCrmRoutes({
62
+ crm,
63
+ db,
64
+ authorize: async (req) => ((await isAdmin(req)) ? { userId: await adminId(req) } : null),
65
+ envName: env.ENV_NAME, // only exactly "production" delivers real email
66
+ baseUrl: "https://app.example.com",
67
+ from: env.EMAIL_FROM,
68
+ sender: { send: (payload) => sendMessage(mySender, payload) }, // optional
69
+ });
70
+
71
+ export default {
72
+ async fetch(req: Request): Promise<Response> {
73
+ return (await crmRoutes(req)) ?? myAppRoutes(req); // null = not a crm path
74
+ },
75
+ };
76
+ ```
77
+
78
+ And the admin surface, from `@odla-ai/crm/ui` (React or Preact via compat, `--ui-*` app-tier styling):
79
+
80
+ ```tsx
81
+ import { CrmClient } from "@odla-ai/crm";
82
+ import { CrmShell, CrmList, useCrmQuery } from "@odla-ai/crm/ui";
83
+
84
+ const client = new CrmClient({ headers: async () => ({ authorization: `Bearer ${await token()}` }) });
85
+
86
+ function People() {
87
+ const query = useCrmQuery(client, "person");
88
+ return (
89
+ <CrmShell crm={crm} active={{ type: "person" }} onNavigate={goTo}>
90
+ <CrmList crm={crm} type="person" query={query} onOpenRecord={openPanel} selectable />
91
+ </CrmShell>
92
+ );
93
+ }
94
+ ```
95
+
96
+ ## What ships where
97
+
98
+ | Concern | Where it lives |
99
+ | --- | --- |
100
+ | Types, pipelines, gates, scorers, template contracts | Code — `defineCrm` (validated at boot) |
101
+ | Template copy, enable flags, destination addresses | Data — the `crm_config` row (owner-editable) |
102
+ | Records, tags, links, activities, channels, send audit, views | odla-db (`CRM_SCHEMA` namespaces) |
103
+ | Money | Nowhere here — `BillingProvider` is a declared port; the `@odla-ai/stripe` adapter is the next milestone. The record carries cache columns only. |
104
+ | Meetings/scheduling | `@odla-ai/calendar` |
105
+ | Clerk role changes | Your `onTransition` hooks (via `@odla-ai/auth-clerk`) |
106
+
107
+ ## Guarantees & limits
108
+
109
+ - Every write accepts a `mutationId` for exactly-once application; webhook-style callers key on it (`{provider}:{eventId}`, `consent:{token}:{event}`, `email:{dedupeKey}`).
110
+ - Send-path failure rows are written unconditionally, so a retry's success is never swallowed; dev environments redirect to `debugEmail` or fall back to log-only.
111
+ - Sorting is server-side on exactly one indexed field (odla-db's contract): promoted columns and slotted fields only — the UI kit marks exactly those sortable.
112
+ - List windows cap at 200 rows; tag cohorts resolve up to 1000 members; unsubscribe GETs never mutate (mail scanners prefetch).
113
+
114
+ MIT © odla