@fayz-ai/plugin-crm 0.8.0 → 0.8.3

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.
Files changed (57) hide show
  1. package/dist/components/CrmGeneralSettings.d.ts.map +1 -1
  2. package/dist/data/supabase.d.ts.map +1 -1
  3. package/dist/index.cjs +168 -33
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +169 -34
  7. package/dist/index.js.map +1 -1
  8. package/dist/lib/form-answers.d.ts +10 -0
  9. package/dist/lib/form-answers.d.ts.map +1 -0
  10. package/dist/locales/en.d.ts.map +1 -1
  11. package/dist/locales/pt-BR.d.ts.map +1 -1
  12. package/dist/migrations/index.d.ts +2 -0
  13. package/dist/migrations/index.d.ts.map +1 -1
  14. package/dist/public/context.d.ts +23 -0
  15. package/dist/public/context.d.ts.map +1 -0
  16. package/dist/public/createPublicFormsPlugin.d.ts +38 -0
  17. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
  18. package/dist/public/data.supabase.d.ts +7 -0
  19. package/dist/public/data.supabase.d.ts.map +1 -0
  20. package/dist/public/inbox.d.ts +22 -0
  21. package/dist/public/inbox.d.ts.map +1 -0
  22. package/dist/public/index.cjs +306 -0
  23. package/dist/public/index.cjs.map +1 -0
  24. package/dist/public/index.d.ts +10 -0
  25. package/dist/public/index.d.ts.map +1 -0
  26. package/dist/public/index.js +298 -0
  27. package/dist/public/index.js.map +1 -0
  28. package/dist/public/types.d.ts +92 -0
  29. package/dist/public/types.d.ts.map +1 -0
  30. package/dist/views/DealSidebar.d.ts.map +1 -1
  31. package/dist/views/LeadDetailView.d.ts.map +1 -1
  32. package/dist/views/LeadFormView.d.ts.map +1 -1
  33. package/dist/views/LeadListView.d.ts.map +1 -1
  34. package/dist/views/PipelineView.d.ts.map +1 -1
  35. package/dist/views/QuoteFormView.d.ts.map +1 -1
  36. package/package.json +11 -5
  37. package/src/components/CrmGeneralSettings.tsx +35 -15
  38. package/src/data/supabase.ts +47 -4
  39. package/src/index.ts +9 -0
  40. package/src/lib/form-answers.tsx +39 -0
  41. package/src/locales/en.ts +1 -0
  42. package/src/locales/pt-BR.ts +1 -0
  43. package/src/migrations/005_public_lead.sql +189 -0
  44. package/src/migrations/006_lead_enters_pipeline.sql +265 -0
  45. package/src/migrations/index.ts +461 -1
  46. package/src/public/context.tsx +69 -0
  47. package/src/public/createPublicFormsPlugin.ts +188 -0
  48. package/src/public/data.supabase.ts +86 -0
  49. package/src/public/inbox.ts +136 -0
  50. package/src/public/index.ts +30 -0
  51. package/src/public/types.ts +113 -0
  52. package/src/views/DealSidebar.tsx +31 -0
  53. package/src/views/LeadDetailView.tsx +53 -0
  54. package/src/views/LeadFormView.tsx +10 -0
  55. package/src/views/LeadListView.tsx +19 -0
  56. package/src/views/PipelineView.tsx +34 -1
  57. package/src/views/QuoteFormView.tsx +5 -0
@@ -0,0 +1,188 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Public forms plugin — "the site collects, the SDK decides where it goes".
3
+ //
4
+ // Headless on purpose. Marketing sites have bespoke, brand-heavy forms; taking
5
+ // over their markup would be a downgrade. So this ships no UI: a site keeps its
6
+ // own inputs and calls submit() with a plain object of values.
7
+ //
8
+ // Every submission fans out to two places, in this order:
9
+ // 1. the tenant's CRM (create_public_lead) — the record of truth
10
+ // 2. the Fayz project inbox — so the site owner is told, and gets the email
11
+ // Step 2 is best-effort: a notification outage must never cost a lead.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ import { createElement, type FC, type ReactNode } from 'react'
15
+ import type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'
16
+ import { createSupabasePublicLeadProvider } from './data.supabase'
17
+ import { createFayzInboxNotifier } from './inbox'
18
+ import { PublicFormsProvider } from './context'
19
+ import {
20
+ LeadSubmitError,
21
+ type LeadAttribution,
22
+ type LeadFields,
23
+ type LeadNotifier,
24
+ type LeadSubmitResult,
25
+ type PublicFormDef,
26
+ type PublicLeadDataProvider,
27
+ } from './types'
28
+
29
+ export interface PublicFormsOptions {
30
+ /**
31
+ * Tenant the leads land in. REQUIRED — this is the whole point of the
32
+ * abstraction: the site never names a table, only a tenant.
33
+ */
34
+ tenantId: string
35
+ /** The forms this site exposes, keyed by id. */
36
+ forms: PublicFormDef[]
37
+ /**
38
+ * Notify the site owner in the Fayz project inbox. Default true; resolves the
39
+ * project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.
40
+ */
41
+ inbox?: boolean | { projectId?: string; apiBaseUrl?: string }
42
+ /** Inject a custom transport (tests, or a non-Supabase backend). */
43
+ dataProvider?: PublicLeadDataProvider
44
+ /** Inject a custom notifier (tests). */
45
+ notifier?: LeadNotifier
46
+ scope?: PluginScope
47
+ verticalId?: VerticalId
48
+ }
49
+
50
+ export interface PublicFormsPlugin {
51
+ manifest: PluginManifest
52
+ Provider: FC<{ children: ReactNode }>
53
+ /** Imperative submit, for code paths outside React. */
54
+ submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>
55
+ }
56
+
57
+ /** Reads UTM + page context off the browser. Safe to call during SSR. */
58
+ export function readAttribution(): LeadAttribution {
59
+ if (typeof window === 'undefined') return {}
60
+ const params = new URLSearchParams(window.location.search)
61
+ const pick = (k: string) => params.get(k) || undefined
62
+ return {
63
+ utm_source: pick('utm_source'),
64
+ utm_medium: pick('utm_medium'),
65
+ utm_campaign: pick('utm_campaign'),
66
+ utm_term: pick('utm_term'),
67
+ utm_content: pick('utm_content'),
68
+ landing_page: window.location.pathname,
69
+ referrer: document.referrer || undefined,
70
+ }
71
+ }
72
+
73
+ function isEmpty(value: unknown): boolean {
74
+ if (value === null || value === undefined) return true
75
+ if (typeof value === 'string') return value.trim() === ''
76
+ if (Array.isArray(value)) return value.length === 0
77
+ return false
78
+ }
79
+
80
+ function stripUndefined<T extends Record<string, unknown>>(obj: T): T {
81
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T
82
+ }
83
+
84
+ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {
85
+ const { tenantId } = options
86
+ const formsById = new Map(options.forms.map((f) => [f.id, f]))
87
+
88
+ const provider: PublicLeadDataProvider =
89
+ options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })
90
+
91
+ const notifier: LeadNotifier | null =
92
+ options.notifier ??
93
+ (options.inbox === false
94
+ ? null
95
+ : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))
96
+
97
+ async function submit(formId: string, values: LeadFields): Promise<LeadSubmitResult> {
98
+ const form = formsById.get(formId)
99
+ if (!form) {
100
+ throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form "${formId}".`)
101
+ }
102
+
103
+ // Identity fields are pulled OUT of the bag; whatever remains is custom.
104
+ const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }
105
+ const name = String(values[idMap.name] ?? '').trim()
106
+ const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''
107
+ const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''
108
+ const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''
109
+
110
+ for (const key of form.required ?? []) {
111
+ if (isEmpty(values[key])) {
112
+ throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)
113
+ }
114
+ }
115
+ if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')
116
+ if (!phone && !email) {
117
+ throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')
118
+ }
119
+
120
+ const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])
121
+ const fields: LeadFields = Object.fromEntries(
122
+ Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),
123
+ )
124
+
125
+ const attribution = readAttribution()
126
+
127
+ // 1. CRM — if this throws, the submission failed and the site says so.
128
+ const { leadId, createdAt } = await provider.createLead(
129
+ stripUndefined({
130
+ formId: form.id,
131
+ formName: form.name,
132
+ name,
133
+ phone: phone || undefined,
134
+ email: email || undefined,
135
+ notes: notes || undefined,
136
+ fields,
137
+ attribution,
138
+ }),
139
+ )
140
+
141
+ // 2. Inbox — the lead is already safe; never fail the form over a notice.
142
+ let notified = false
143
+ if (notifier) {
144
+ try {
145
+ await notifier.notify({
146
+ formId: form.id,
147
+ formName: form.name,
148
+ leadName: name,
149
+ phone: phone || undefined,
150
+ email: email || undefined,
151
+ fields,
152
+ labels: form.labels,
153
+ attribution,
154
+ })
155
+ notified = true
156
+ } catch (err) {
157
+ if (typeof console !== 'undefined') {
158
+ console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)
159
+ }
160
+ }
161
+ }
162
+
163
+ return { leadId, createdAt, notified }
164
+ }
165
+
166
+ const Provider: FC<{ children: ReactNode }> = ({ children }) =>
167
+ createElement(PublicFormsProvider, { forms: formsById, submit, children })
168
+ Provider.displayName = 'PublicFormsProvider'
169
+
170
+ const manifest: PluginManifest = {
171
+ id: 'public-forms',
172
+ name: 'Formulários',
173
+ icon: 'Inbox',
174
+ version: '0.1.0',
175
+ scope: options.scope ?? 'universal',
176
+ verticalId: options.verticalId,
177
+ scaffolds: ['website', 'landing_page'],
178
+ defaultEnabled: true,
179
+ dependencies: [],
180
+ // Headless: the site owns the markup, so this plugin mounts no route and
181
+ // contributes no navigation. It exists to be registered and provide context.
182
+ navigation: [],
183
+ routes: [],
184
+ widgets: [],
185
+ }
186
+
187
+ return { manifest, Provider, submit }
188
+ }
@@ -0,0 +1,86 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Supabase implementation of PublicLeadDataProvider — anon-safe.
3
+ //
4
+ // Public marketing pages run with the publishable (anon) key and NO user
5
+ // session, so canonical tenant RLS yields nothing. This provider touches only
6
+ // the one object designed for anon access:
7
+ // - public.create_public_lead (SECURITY DEFINER RPC: validates, caps spam,
8
+ // writes people[kind=lead] with the custom fields in metadata)
9
+ // Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.
10
+ //
11
+ // The RPC never reads back — a form writes, it does not query the CRM.
12
+ // ---------------------------------------------------------------------------
13
+
14
+ import { getFayzCloudClient, getSupabaseClientOptional } from '@fayz-ai/core'
15
+ import { LeadSubmitError, type PublicLeadDataProvider } from './types'
16
+
17
+ export interface SupabasePublicLeadOptions {
18
+ /** The tenant leads land in (RPC arg — required). */
19
+ tenantId: string
20
+ }
21
+
22
+ interface SupabaseLikeClient {
23
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>
24
+ }
25
+
26
+ function getClient(): SupabaseLikeClient | null {
27
+ return (getSupabaseClientOptional() ?? getFayzCloudClient()) as SupabaseLikeClient | null
28
+ }
29
+
30
+ /** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */
31
+ function toSubmitError(message: string): LeadSubmitError {
32
+ const m = message.toLowerCase()
33
+ if (m.includes('duplicate submission')) {
34
+ return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')
35
+ }
36
+ if (m.includes('too many submissions')) {
37
+ return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')
38
+ }
39
+ if (
40
+ m.includes('invalid') ||
41
+ m.includes('required') ||
42
+ m.includes('too many fields') ||
43
+ m.includes('fields too large')
44
+ ) {
45
+ return new LeadSubmitError('validation', message)
46
+ }
47
+ return new LeadSubmitError('unavailable', message)
48
+ }
49
+
50
+ export function createSupabasePublicLeadProvider(
51
+ options: SupabasePublicLeadOptions,
52
+ ): PublicLeadDataProvider {
53
+ const { tenantId } = options
54
+
55
+ return {
56
+ async createLead(input) {
57
+ const client = getClient()
58
+ if (!client) {
59
+ throw new LeadSubmitError(
60
+ 'unavailable',
61
+ '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',
62
+ )
63
+ }
64
+
65
+ const { data, error } = await client.rpc('create_public_lead', {
66
+ p_tenant_id: tenantId,
67
+ p_name: input.name,
68
+ p_phone: input.phone ?? null,
69
+ p_email: input.email ?? null,
70
+ p_form_id: input.formId,
71
+ p_form_name: input.formName,
72
+ p_fields: input.fields,
73
+ p_notes: input.notes ?? null,
74
+ p_utm: input.attribution,
75
+ })
76
+
77
+ if (error) throw toSubmitError(error.message)
78
+
79
+ const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined
80
+ if (!row?.lead_id) {
81
+ throw new LeadSubmitError('unavailable', 'Lead não foi criado.')
82
+ }
83
+ return { leadId: String(row.lead_id), createdAt: String(row.created_at) }
84
+ },
85
+ }
86
+ }
@@ -0,0 +1,136 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Fayz inbox notifier — tells the site's owner a lead just arrived.
3
+ //
4
+ // The Fayz platform already ships a public ingest endpoint built for exactly
5
+ // this ("Deployed user-sites POST here"): it stores an InboxRecord against the
6
+ // project and emails the project owner. We only have to speak to it.
7
+ //
8
+ // POST <base>/public/projects/:projectId/inbox
9
+ // { source, subject, payload, metadata }
10
+ //
11
+ // SAME-ORIGIN BY DEFAULT. In production the API's CORS allowlist is a single
12
+ // origin (the editor), so a cross-origin POST from a published site would be
13
+ // refused at preflight. Fayz's Caddy proxies `/api/*` to the API "regardless of
14
+ // host", so a published site — custom domain included — reaches it same-origin
15
+ // with no preflight at all. Hence the default base '/api' (relative). Only pass
16
+ // an absolute base when the site is NOT served by Fayz, and expect to widen
17
+ // CORS on the API before it works.
18
+ //
19
+ // Best-effort by contract: the lead is already safe in the CRM by the time this
20
+ // runs. A failed notification is logged and swallowed — never a failed form.
21
+ // ---------------------------------------------------------------------------
22
+
23
+ import type { LeadNotifier, LeadFields } from './types'
24
+
25
+ export interface FayzInboxNotifierOptions {
26
+ /**
27
+ * Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;
28
+ * omit to read that env var automatically.
29
+ */
30
+ projectId?: string
31
+ /**
32
+ * API base. Defaults to '/api' (same-origin via Caddy) — see the note above
33
+ * before changing it.
34
+ */
35
+ apiBaseUrl?: string
36
+ /** Milliseconds before giving up. The visitor is waiting; keep it short. */
37
+ timeoutMs?: number
38
+ }
39
+
40
+ function readEnv(key: string): string | undefined {
41
+ try {
42
+ const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env
43
+ return env?.[key]
44
+ } catch {
45
+ return undefined
46
+ }
47
+ }
48
+
49
+ /** "age_range" → "Age range", unless the form gave us a real label. */
50
+ function humanize(key: string, labels?: Record<string, string>): string {
51
+ if (labels?.[key]) return labels[key]
52
+ const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\d])([A-Z])/g, '$1 $2')
53
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
54
+ }
55
+
56
+ function renderValue(value: unknown): string {
57
+ if (value === null || value === undefined || value === '') return '—'
58
+ if (Array.isArray(value)) return value.length ? value.join(', ') : '—'
59
+ if (typeof value === 'boolean') return value ? 'Sim' : 'Não'
60
+ return String(value)
61
+ }
62
+
63
+ /**
64
+ * Builds the flat, already-humanized payload the inbox renders. The editor
65
+ * shows this verbatim, so it must read like a message — not like a database row.
66
+ */
67
+ function buildPayload(
68
+ input: Parameters<LeadNotifier['notify']>[0],
69
+ ): Record<string, string> {
70
+ const payload: Record<string, string> = { Nome: input.leadName }
71
+ if (input.phone) payload['Telefone'] = input.phone
72
+ if (input.email) payload['E-mail'] = input.email
73
+
74
+ for (const [key, value] of Object.entries(input.fields as LeadFields)) {
75
+ payload[humanize(key, input.labels)] = renderValue(value)
76
+ }
77
+
78
+ const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution
79
+ if (utm_source) payload['Origem'] = utm_source
80
+ if (utm_medium) payload['Mídia'] = utm_medium
81
+ if (utm_campaign) payload['Campanha'] = utm_campaign
82
+ if (landing_page) payload['Página'] = landing_page
83
+
84
+ return payload
85
+ }
86
+
87
+ /**
88
+ * A notifier that posts to the Fayz project inbox. Returns a no-op notifier
89
+ * (with one loud warning) when no project id is resolvable, so a site running
90
+ * outside Fayz still submits leads normally.
91
+ */
92
+ export function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {
93
+ const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')
94
+ const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\/$/, '')
95
+ const timeoutMs = options.timeoutMs ?? 4000
96
+
97
+ if (!projectId) {
98
+ let warned = false
99
+ return {
100
+ async notify() {
101
+ if (!warned && typeof console !== 'undefined') {
102
+ warned = true
103
+ console.warn(
104
+ '[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +
105
+ 'site owner is NOT notified in the Fayz inbox.',
106
+ )
107
+ }
108
+ },
109
+ }
110
+ }
111
+
112
+ return {
113
+ async notify(input) {
114
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
115
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
116
+ try {
117
+ const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {
118
+ method: 'POST',
119
+ headers: { 'Content-Type': 'application/json' },
120
+ signal: controller?.signal,
121
+ body: JSON.stringify({
122
+ source: 'form',
123
+ subject: `Novo lead: ${input.leadName} — ${input.formName}`,
124
+ payload: buildPayload(input),
125
+ metadata: { formId: input.formId, formName: input.formName, ...input.attribution },
126
+ }),
127
+ })
128
+ if (!res.ok) {
129
+ throw new Error(`inbox responded ${res.status}`)
130
+ }
131
+ } finally {
132
+ if (timer) clearTimeout(timer)
133
+ }
134
+ },
135
+ }
136
+ }
@@ -0,0 +1,30 @@
1
+ // ---------------------------------------------------------------------------
2
+ // @fayz-ai/plugin-crm/public — anon-safe lead capture for marketing sites.
3
+ //
4
+ // Headless: the site keeps its own form UI and calls useLeadForm(formId).submit
5
+ // with a bag of values. The SDK resolves where that goes (the tenant's CRM) and
6
+ // who is told (the Fayz project inbox).
7
+ // ---------------------------------------------------------------------------
8
+
9
+ export { createPublicFormsPlugin, readAttribution } from './createPublicFormsPlugin'
10
+ export type { PublicFormsOptions, PublicFormsPlugin } from './createPublicFormsPlugin'
11
+
12
+ export { PublicFormsProvider, useLeadForm } from './context'
13
+
14
+ export { createSupabasePublicLeadProvider } from './data.supabase'
15
+ export type { SupabasePublicLeadOptions } from './data.supabase'
16
+
17
+ export { createFayzInboxNotifier } from './inbox'
18
+ export type { FayzInboxNotifierOptions } from './inbox'
19
+
20
+ export { LeadSubmitError } from './types'
21
+ export type {
22
+ LeadAttribution,
23
+ LeadFieldValue,
24
+ LeadFields,
25
+ LeadNotifier,
26
+ LeadSubmitErrorKind,
27
+ LeadSubmitResult,
28
+ PublicFormDef,
29
+ PublicLeadDataProvider,
30
+ } from './types'
@@ -0,0 +1,113 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Public lead capture — types
3
+ //
4
+ // The contract between a marketing site's own form UI and the CRM. Sites keep
5
+ // their bespoke layout and copy; all they hand over is a bag of values. Where
6
+ // that lands (which tenant, which table, what status) is decided by the SDK and
7
+ // the RPC behind it, never by the site.
8
+ // ---------------------------------------------------------------------------
9
+
10
+ /** What a form field may carry. Scalars and scalar lists — anything a checkbox
11
+ * group, a select or a text input produces. Files are out of scope: a lead
12
+ * form links to an upload, it does not embed one. */
13
+ export type LeadFieldValue = string | number | boolean | null | string[] | number[]
14
+
15
+ /** The values a site collects, keyed by field id. Free-form on purpose: a new
16
+ * landing page adds keys without touching the schema. */
17
+ export type LeadFields = Record<string, LeadFieldValue>
18
+
19
+ /**
20
+ * One form the site exposes. Registered up-front so submissions carry a stable
21
+ * id (attribution) and a human name (what the operator reads in the CRM).
22
+ */
23
+ export interface PublicFormDef {
24
+ /** Stable id — the attribution key. Keep it stable across redesigns. */
25
+ id: string
26
+ /** Human name shown as the lead's source in the CRM. */
27
+ name: string
28
+ /**
29
+ * Field ids that must be present and non-empty for the submission to be
30
+ * attempted. Contact reachability (phone or email) is enforced server-side
31
+ * regardless of what is declared here.
32
+ */
33
+ required?: string[]
34
+ /**
35
+ * Maps this form's field ids onto the lead's identity columns. Everything NOT
36
+ * mapped stays in `fields` as a custom field.
37
+ *
38
+ * Defaults to { name: 'name', phone: 'phone', email: 'email' }.
39
+ */
40
+ identity?: {
41
+ name?: string
42
+ phone?: string
43
+ email?: string
44
+ /** Field whose value becomes the lead's free-text note. */
45
+ notes?: string
46
+ }
47
+ /** Labels for custom fields, so the CRM shows "Faixa etária" not "age_range". */
48
+ labels?: Record<string, string>
49
+ }
50
+
51
+ /** Result of a submission — enough for the site to show its own success state. */
52
+ export interface LeadSubmitResult {
53
+ leadId: string
54
+ createdAt: string
55
+ /** False when the CRM write succeeded but the inbox notification did not. */
56
+ notified: boolean
57
+ }
58
+
59
+ /** Thrown for problems the site should surface differently than a crash. */
60
+ export type LeadSubmitErrorKind =
61
+ | 'validation' // missing required field / no contact channel
62
+ | 'duplicate' // same contact, same form, seconds apart
63
+ | 'rate_limited' // burst cap tripped
64
+ | 'unavailable' // backend not configured or unreachable
65
+
66
+ export class LeadSubmitError extends Error {
67
+ readonly kind: LeadSubmitErrorKind
68
+ constructor(kind: LeadSubmitErrorKind, message: string) {
69
+ super(message)
70
+ this.name = 'LeadSubmitError'
71
+ this.kind = kind
72
+ }
73
+ }
74
+
75
+ /** UTM/attribution captured from the browser, merged into every submission. */
76
+ export interface LeadAttribution {
77
+ utm_source?: string
78
+ utm_medium?: string
79
+ utm_campaign?: string
80
+ utm_term?: string
81
+ utm_content?: string
82
+ /** Path the form was submitted from. */
83
+ landing_page?: string
84
+ referrer?: string
85
+ }
86
+
87
+ /** The transport a submission goes through. Swappable for tests. */
88
+ export interface PublicLeadDataProvider {
89
+ createLead(input: {
90
+ formId: string
91
+ formName: string
92
+ name: string
93
+ phone?: string
94
+ email?: string
95
+ notes?: string
96
+ fields: LeadFields
97
+ attribution: LeadAttribution
98
+ }): Promise<{ leadId: string; createdAt: string }>
99
+ }
100
+
101
+ /** Notifies the site's admin that a lead arrived. */
102
+ export interface LeadNotifier {
103
+ notify(input: {
104
+ formId: string
105
+ formName: string
106
+ leadName: string
107
+ phone?: string
108
+ email?: string
109
+ fields: LeadFields
110
+ labels?: Record<string, string>
111
+ attribution: LeadAttribution
112
+ }): Promise<void>
113
+ }
@@ -5,6 +5,7 @@ import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, S
5
5
  import { PersonLink } from '@fayz-ai/saas'
6
6
  import { useCrmProvider, useCrmConfig, formatCurrency } from '../CrmContext'
7
7
  import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
8
+ import { answerEntries, humanizeKey, renderFieldValue } from '../lib/form-answers'
8
9
  import type { Deal, Lead, Quote, Activity } from '../types'
9
10
 
10
11
  // ---------------------------------------------------------------------------
@@ -60,6 +61,33 @@ function TabBar({ active, counts, onChange }: { active: TabId; counts: { activit
60
61
  // Overview tab
61
62
  // ---------------------------------------------------------------------------
62
63
 
64
+ /** Whatever the public form captured, in the card. Same opaque-bag rendering
65
+ * the lead detail page uses — shared so the two cannot drift. */
66
+ function FormAnswers({ lead }: { lead: Lead | null }) {
67
+ const t = useTranslation()
68
+ const entries = answerEntries(lead?.metadata?.fields)
69
+ if (entries.length === 0) return null
70
+
71
+ const formId = lead?.metadata?.formId
72
+ return (
73
+ <div className="space-y-2">
74
+ <h4 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
75
+ {formId ? `${t('crm.leadDetail.formAnswers')} · ${formId}` : t('crm.leadDetail.formAnswers')}
76
+ </h4>
77
+ <div className="rounded-xl border divide-y">
78
+ {entries.map(([key, value]) => (
79
+ <div key={key} className="flex items-start gap-3 px-4 py-2.5">
80
+ <span className="text-[11px] text-muted-foreground shrink-0 min-w-24">{humanizeKey(key)}</span>
81
+ <span className="text-xs text-right flex-1 break-words">
82
+ {renderFieldValue(value) ?? <span className="text-muted-foreground/50">—</span>}
83
+ </span>
84
+ </div>
85
+ ))}
86
+ </div>
87
+ </div>
88
+ )
89
+ }
90
+
63
91
  function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null; currency: { code: string; locale: string; symbol: string } }) {
64
92
  const t = useTranslation()
65
93
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase()
@@ -143,6 +171,9 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
143
171
  </div>
144
172
  )}
145
173
 
174
+ {/* Form answers */}
175
+ <FormAnswers lead={lead} />
176
+
146
177
  {/* Tags */}
147
178
  {deal.tags && deal.tags.length > 0 && (
148
179
  <div className="space-y-2">
@@ -16,6 +16,21 @@ const STATUS_COLORS: Record<string, string> = {
16
16
  }
17
17
 
18
18
 
19
+ /** "hair_remaining" → "Hair remaining". Form answers arrive keyed by whatever
20
+ * the landing page called them, so they get humanized rather than shown raw. */
21
+ function humanizeKey(key: string): string {
22
+ const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\d])([A-Z])/g, '$1 $2')
23
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
24
+ }
25
+
26
+ function renderFieldValue(value: unknown): React.ReactNode {
27
+ if (value === null || value === undefined || value === '') return null
28
+ if (Array.isArray(value)) return value.length ? value.join(', ') : null
29
+ if (typeof value === 'boolean') return value ? 'Sim' : 'Não'
30
+ if (typeof value === 'object') return JSON.stringify(value)
31
+ return String(value)
32
+ }
33
+
19
34
  function FieldRow({ label, value }: { label: string; value: React.ReactNode }) {
20
35
  return (
21
36
  <div className="grid grid-cols-3 gap-4 py-3">
@@ -159,6 +174,44 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
159
174
  </div>
160
175
  </div>
161
176
 
177
+ {/* Form answers — whatever the landing page asked. Rendered generically
178
+ so a new form never needs a change here. */}
179
+ {(() => {
180
+ const meta = (lead.metadata ?? {}) as {
181
+ fields?: Record<string, unknown>
182
+ utm?: Record<string, unknown>
183
+ }
184
+ const fields = Object.entries(meta.fields ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
185
+ const utm = Object.entries(meta.utm ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
186
+ if (!fields.length && !utm.length) return null
187
+ return (
188
+ <div>
189
+ <h3 className="text-sm font-semibold text-foreground mb-1">
190
+ {t('crm.leadDetail.formAnswers')}
191
+ </h3>
192
+ <div className="rounded-xl border bg-card shadow-sm">
193
+ <dl className="grid divide-y md:grid-cols-2 md:divide-y-0">
194
+ {fields.map(([key, value]) => (
195
+ <div key={key} className="px-5 md:border-b md:last:border-b-0">
196
+ <FieldRow label={humanizeKey(key)} value={renderFieldValue(value)} />
197
+ </div>
198
+ ))}
199
+ </dl>
200
+ {utm.length > 0 && (
201
+ <div className="border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1">
202
+ {utm.map(([key, value]) => (
203
+ <span key={key} className="text-xs text-muted-foreground">
204
+ {humanizeKey(key.replace(/^utm_/, ''))}:{' '}
205
+ <span className="text-foreground">{renderFieldValue(value)}</span>
206
+ </span>
207
+ ))}
208
+ </div>
209
+ )}
210
+ </div>
211
+ </div>
212
+ )
213
+ })()}
214
+
162
215
  {/* Pipeline / Deal */}
163
216
  {deal && (
164
217
  <div>