@fayz-ai/plugin-crm 0.9.0-next.1 → 0.9.1
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 +3 -3
- package/dist/components/AutomationBolt.d.ts +22 -0
- package/dist/components/AutomationBolt.d.ts.map +1 -0
- package/dist/{CrmContext.d.ts → context.d.ts} +4 -2
- package/dist/context.d.ts.map +1 -0
- package/dist/data/registries.d.ts.map +1 -0
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +573 -488
- package/dist/index.js.map +1 -1
- package/dist/{cascade.d.ts → lib/cascade.d.ts} +1 -1
- package/dist/lib/cascade.d.ts.map +1 -0
- package/dist/lib/message-events.d.ts +13 -0
- package/dist/lib/message-events.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/public/context.d.ts +1 -1
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/{data.supabase.d.ts → data/supabase.d.ts} +2 -2
- package/dist/public/data/supabase.d.ts.map +1 -0
- package/dist/public/index.d.ts +6 -6
- package/dist/public/index.d.ts.map +1 -1
- package/dist/public/index.js +2 -2
- package/dist/public/index.js.map +1 -1
- package/dist/public/{inbox.d.ts → lib/inbox.d.ts} +1 -1
- package/dist/public/lib/inbox.d.ts.map +1 -0
- package/dist/public/{uploads.d.ts → lib/uploads.d.ts} +1 -1
- package/dist/public/lib/uploads.d.ts.map +1 -0
- package/dist/store.d.ts +9 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/{CrmPage.d.ts → views/CrmPage.d.ts} +3 -3
- package/dist/views/CrmPage.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadListView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts +3 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteDetailView.d.ts.map +1 -1
- package/dist/views/QuoteFormView.d.ts.map +1 -1
- package/dist/views/QuoteListView.d.ts.map +1 -1
- package/dist/views/dashboardWidgets.d.ts +1 -1
- package/dist/views/dashboardWidgets.d.ts.map +1 -1
- package/package.json +6 -10
- package/dist/CrmContext.d.ts.map +0 -1
- package/dist/CrmPage.d.ts.map +0 -1
- package/dist/cascade.d.ts.map +0 -1
- package/dist/public/data.supabase.d.ts.map +0 -1
- package/dist/public/inbox.d.ts.map +0 -1
- package/dist/public/uploads.d.ts.map +0 -1
- package/dist/registries.d.ts.map +0 -1
- package/src/CrmContext.tsx +0 -30
- package/src/CrmPage.tsx +0 -150
- package/src/README.md +0 -97
- package/src/cascade.ts +0 -26
- package/src/components/BoardFilters.tsx +0 -190
- package/src/components/CrmGeneralSettings.tsx +0 -56
- package/src/components/CrmOnboarding.tsx +0 -52
- package/src/components/LeadAttachments.tsx +0 -140
- package/src/components/PipelineSettings.tsx +0 -45
- package/src/components/QuoteStatusDropdown.tsx +0 -226
- package/src/components/TagChips.tsx +0 -80
- package/src/data/index.ts +0 -2
- package/src/data/mock.ts +0 -559
- package/src/data/supabase.ts +0 -928
- package/src/data/tables.ts +0 -11
- package/src/data/types.ts +0 -61
- package/src/index.ts +0 -429
- package/src/lib/access.ts +0 -11
- package/src/lib/form-answers.tsx +0 -80
- package/src/lib/relative-time.ts +0 -84
- package/src/lib/tenant.ts +0 -4
- package/src/locales/en.ts +0 -307
- package/src/locales/index.ts +0 -7
- package/src/locales/pt-BR.ts +0 -307
- package/src/migrations/000_plg_rename.sql +0 -28
- package/src/migrations/001_crm_base.sql +0 -73
- package/src/migrations/002_activities.sql +0 -33
- package/src/migrations/003_crm_views_rls.sql +0 -69
- package/src/migrations/004_seed_default_pipeline.sql +0 -31
- package/src/migrations/005_public_lead.sql +0 -189
- package/src/migrations/006_lead_enters_pipeline.sql +0 -265
- package/src/migrations/007_activity_log.sql +0 -55
- package/src/migrations/008_view_field_aliases.sql +0 -43
- package/src/migrations/009_deal_archived_status.sql +0 -30
- package/src/migrations/010_quote_archived_status.sql +0 -40
- package/src/migrations/011_agent_rpc_update_lead.sql +0 -153
- package/src/migrations/012_agent_rpc_create_lead.sql +0 -128
- package/src/migrations/013_tag_slugs.sql +0 -177
- package/src/migrations/014_public_lead_tags.sql +0 -172
- package/src/migrations/015_lead_attachments.sql +0 -357
- package/src/migrations/016_public_lead_activity.sql +0 -123
- package/src/migrations/index.ts +0 -2023
- package/src/public/context.tsx +0 -150
- package/src/public/createPublicFormsPlugin.ts +0 -282
- package/src/public/data.supabase.ts +0 -92
- package/src/public/inbox.ts +0 -143
- package/src/public/index.ts +0 -51
- package/src/public/types.ts +0 -173
- package/src/public/uploads.ts +0 -205
- package/src/registries.ts +0 -162
- package/src/schema/index.ts +0 -104
- package/src/store.ts +0 -472
- package/src/types.ts +0 -337
- package/src/views/ActivityListView.tsx +0 -264
- package/src/views/DashboardView.tsx +0 -12
- package/src/views/DealSidebar.tsx +0 -482
- package/src/views/LeadDetailView.tsx +0 -378
- package/src/views/LeadFormView.tsx +0 -66
- package/src/views/LeadListView.tsx +0 -100
- package/src/views/PipelineView.tsx +0 -446
- package/src/views/QuoteDetailView.tsx +0 -412
- package/src/views/QuoteFormView.tsx +0 -494
- package/src/views/QuoteListView.tsx +0 -115
- package/src/views/dashboardWidgets.tsx +0 -248
- /package/dist/{registries.d.ts → data/registries.d.ts} +0 -0
package/src/public/context.tsx
DELETED
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from 'react'
|
|
2
|
-
import {
|
|
3
|
-
LeadSubmitError,
|
|
4
|
-
type LeadAttachment,
|
|
5
|
-
type LeadFields,
|
|
6
|
-
type LeadSubmitOptions,
|
|
7
|
-
type LeadSubmitResult,
|
|
8
|
-
type PublicFormDef,
|
|
9
|
-
} from './types'
|
|
10
|
-
import { newSubmissionId, type LeadUploader } from './uploads'
|
|
11
|
-
|
|
12
|
-
interface PublicFormsContextValue {
|
|
13
|
-
forms: Map<string, PublicFormDef>
|
|
14
|
-
submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>
|
|
15
|
-
/** Null quando o app desligou anexos (`uploads: false`). */
|
|
16
|
-
uploader: LeadUploader | null
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const PublicFormsContext = createContext<PublicFormsContextValue | null>(null)
|
|
20
|
-
|
|
21
|
-
export interface PublicFormsProviderProps extends PublicFormsContextValue {
|
|
22
|
-
children: ReactNode
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function PublicFormsProvider({ forms, submit, uploader, children }: PublicFormsProviderProps) {
|
|
26
|
-
const value = useMemo(() => ({ forms, submit, uploader }), [forms, submit, uploader])
|
|
27
|
-
return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** The hook a site's own form component calls. Owns only the submission
|
|
31
|
-
* lifecycle — the markup, the fields and the validation copy stay the site's. */
|
|
32
|
-
export function useLeadForm(formId: string) {
|
|
33
|
-
const ctx = useContext(PublicFormsContext)
|
|
34
|
-
if (!ctx) {
|
|
35
|
-
throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
const [submitting, setSubmitting] = useState(false)
|
|
39
|
-
const [error, setError] = useState<LeadSubmitError | null>(null)
|
|
40
|
-
const [result, setResult] = useState<LeadSubmitResult | null>(null)
|
|
41
|
-
|
|
42
|
-
const submit = useCallback(
|
|
43
|
-
async (values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult | null> => {
|
|
44
|
-
if (submitting) return null
|
|
45
|
-
setSubmitting(true)
|
|
46
|
-
setError(null)
|
|
47
|
-
try {
|
|
48
|
-
const res = await ctx.submit(formId, values, options)
|
|
49
|
-
setResult(res)
|
|
50
|
-
return res
|
|
51
|
-
} catch (err) {
|
|
52
|
-
const e =
|
|
53
|
-
err instanceof LeadSubmitError
|
|
54
|
-
? err
|
|
55
|
-
: new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')
|
|
56
|
-
setError(e)
|
|
57
|
-
return null
|
|
58
|
-
} finally {
|
|
59
|
-
setSubmitting(false)
|
|
60
|
-
}
|
|
61
|
-
},
|
|
62
|
-
[ctx, formId, submitting],
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
const reset = useCallback(() => {
|
|
66
|
-
setError(null)
|
|
67
|
-
setResult(null)
|
|
68
|
-
}, [])
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
submit,
|
|
72
|
-
reset,
|
|
73
|
-
submitting,
|
|
74
|
-
error,
|
|
75
|
-
result,
|
|
76
|
-
success: result !== null,
|
|
77
|
-
form: ctx.forms.get(formId) ?? null,
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Anexos de um formulário público.
|
|
83
|
-
*
|
|
84
|
-
* Separado de `useLeadForm` de propósito, porque os dois tempos são diferentes:
|
|
85
|
-
* o arquivo sobe ENQUANTO a pessoa preenche (é o passo lento, e ela precisa ver
|
|
86
|
-
* acontecer), e o lead é criado no fim. Amarrar os dois obrigaria a segurar
|
|
87
|
-
* megabytes em memória até o envio — que é exatamente o que este desenho
|
|
88
|
-
* substitui.
|
|
89
|
-
*
|
|
90
|
-
* Todos os anexos de um preenchimento compartilham um `submissionId`, então
|
|
91
|
-
* caem na mesma pasta do Storage.
|
|
92
|
-
*/
|
|
93
|
-
export function useLeadUploads(formId: string) {
|
|
94
|
-
const ctx = useContext(PublicFormsContext)
|
|
95
|
-
if (!ctx) {
|
|
96
|
-
throw new Error('[plugin-crm] useLeadUploads must be used within <PublicFormsProvider>.')
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
// Um id por montagem do formulário: os arquivos deste preenchimento
|
|
100
|
-
// pertencem à mesma pasta, mesmo enviados minutos depois um do outro.
|
|
101
|
-
const submissionIdRef = useRef<string | null>(null)
|
|
102
|
-
if (submissionIdRef.current === null) submissionIdRef.current = newSubmissionId()
|
|
103
|
-
|
|
104
|
-
const [uploading, setUploading] = useState(false)
|
|
105
|
-
const [error, setError] = useState<LeadSubmitError | null>(null)
|
|
106
|
-
|
|
107
|
-
const upload = useCallback(
|
|
108
|
-
async (slot: string, file: File | Blob): Promise<LeadAttachment | null> => {
|
|
109
|
-
if (!ctx.uploader) {
|
|
110
|
-
setError(new LeadSubmitError('unavailable', 'Envio de arquivos não está habilitado neste site.'))
|
|
111
|
-
return null
|
|
112
|
-
}
|
|
113
|
-
setUploading(true)
|
|
114
|
-
setError(null)
|
|
115
|
-
try {
|
|
116
|
-
return await ctx.uploader.upload({
|
|
117
|
-
formId,
|
|
118
|
-
slot,
|
|
119
|
-
file,
|
|
120
|
-
submissionId: submissionIdRef.current!,
|
|
121
|
-
})
|
|
122
|
-
} catch (err) {
|
|
123
|
-
const e =
|
|
124
|
-
err instanceof LeadSubmitError
|
|
125
|
-
? err
|
|
126
|
-
: new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar o arquivo.')
|
|
127
|
-
setError(e)
|
|
128
|
-
return null
|
|
129
|
-
} finally {
|
|
130
|
-
setUploading(false)
|
|
131
|
-
}
|
|
132
|
-
},
|
|
133
|
-
[ctx.uploader, formId],
|
|
134
|
-
)
|
|
135
|
-
|
|
136
|
-
/** Começa um novo preenchimento — chame depois de um envio bem-sucedido. */
|
|
137
|
-
const reset = useCallback(() => {
|
|
138
|
-
submissionIdRef.current = newSubmissionId()
|
|
139
|
-
setError(null)
|
|
140
|
-
}, [])
|
|
141
|
-
|
|
142
|
-
return {
|
|
143
|
-
upload,
|
|
144
|
-
reset,
|
|
145
|
-
uploading,
|
|
146
|
-
error,
|
|
147
|
-
enabled: ctx.uploader !== null,
|
|
148
|
-
submissionId: submissionIdRef.current!,
|
|
149
|
-
}
|
|
150
|
-
}
|
|
@@ -1,282 +0,0 @@
|
|
|
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 { createSupabaseLeadUploader, MAX_LEAD_ATTACHMENTS, type LeadUploader } from './uploads'
|
|
20
|
-
import {
|
|
21
|
-
LeadSubmitError,
|
|
22
|
-
type LeadAttribution,
|
|
23
|
-
type LeadFields,
|
|
24
|
-
type LeadNotifier,
|
|
25
|
-
type LeadSubmitOptions,
|
|
26
|
-
type LeadSubmitResult,
|
|
27
|
-
type PublicFormDef,
|
|
28
|
-
type PublicLeadDataProvider,
|
|
29
|
-
} from './types'
|
|
30
|
-
|
|
31
|
-
export interface PublicFormsOptions {
|
|
32
|
-
/**
|
|
33
|
-
* Tenant the leads land in. REQUIRED — this is the whole point of the
|
|
34
|
-
* abstraction: the site never names a table, only a tenant.
|
|
35
|
-
*/
|
|
36
|
-
tenantId: string
|
|
37
|
-
/** The forms this site exposes, keyed by id. */
|
|
38
|
-
forms: PublicFormDef[]
|
|
39
|
-
/**
|
|
40
|
-
* Notify the site owner in the Fayz project inbox. Default true; resolves the
|
|
41
|
-
* project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.
|
|
42
|
-
*/
|
|
43
|
-
inbox?: boolean | { projectId?: string; apiBaseUrl?: string }
|
|
44
|
-
/** Inject a custom transport (tests, or a non-Supabase backend). */
|
|
45
|
-
dataProvider?: PublicLeadDataProvider
|
|
46
|
-
/** Inject a custom notifier (tests). */
|
|
47
|
-
notifier?: LeadNotifier
|
|
48
|
-
/**
|
|
49
|
-
* Anexos nos formulários (fotos, documentos). Ligado por padrão; o arquivo vai
|
|
50
|
-
* para o bucket que o plugin resolve, na pasta do tenant. `false` desliga —
|
|
51
|
-
* `useLeadUploads().enabled` fica falso e o site não oferece o campo.
|
|
52
|
-
*
|
|
53
|
-
* Injete um `LeadUploader` para testar sem rede.
|
|
54
|
-
*/
|
|
55
|
-
uploads?: boolean | LeadUploader
|
|
56
|
-
/**
|
|
57
|
-
* Marca o lead com a campanha que o trouxe, lendo a UTM da URL.
|
|
58
|
-
*
|
|
59
|
-
* Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag
|
|
60
|
-
* automática e tag curada convivem no mesmo array, e sem prefixo a primeira
|
|
61
|
-
* engole a segunda — em seis meses ninguém sabe mais quais tags alguém
|
|
62
|
-
* escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,
|
|
63
|
-
* relatar e limpar cada grupo separadamente.
|
|
64
|
-
*
|
|
65
|
-
* `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica
|
|
66
|
-
* desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.
|
|
67
|
-
*/
|
|
68
|
-
campaignTags?: boolean | { campaign?: boolean; source?: boolean }
|
|
69
|
-
scope?: PluginScope
|
|
70
|
-
verticalId?: VerticalId
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Teto por lead — o mesmo que o RPC aplica; aparar aqui evita mandar lixo. */
|
|
74
|
-
const MAX_TAGS = 10
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* Slug normalizado. O servidor normaliza de novo (é ele quem manda), mas fazer
|
|
78
|
-
* aqui também mantém `camp:` legível e evita gastar as 10 vagas com duplicata.
|
|
79
|
-
*/
|
|
80
|
-
function slugify(input: string): string {
|
|
81
|
-
return input
|
|
82
|
-
.normalize('NFD')
|
|
83
|
-
// Marcas combinantes: o NFD separa o acento da letra, e este range remove
|
|
84
|
-
// só o acento. Escapado em vez de literal — o caractere cru é invisível no
|
|
85
|
-
// editor e some em qualquer copy-paste.
|
|
86
|
-
.replace(/[\u0300-\u036f]/g, '')
|
|
87
|
-
.toLowerCase()
|
|
88
|
-
.replace(/[^a-z0-9:]+/g, '-')
|
|
89
|
-
.replace(/-{2,}/g, '-')
|
|
90
|
-
.replace(/^-+|-+$/g, '')
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Tags curadas do formulário + as automáticas da campanha, deduplicadas. */
|
|
94
|
-
function resolveTags(
|
|
95
|
-
formTags: string[] | undefined,
|
|
96
|
-
callTags: string[] | undefined,
|
|
97
|
-
attribution: LeadAttribution,
|
|
98
|
-
campaignTags: PublicFormsOptions['campaignTags'],
|
|
99
|
-
): string[] {
|
|
100
|
-
const cfg =
|
|
101
|
-
campaignTags === false
|
|
102
|
-
? { campaign: false, source: false }
|
|
103
|
-
: campaignTags === true || campaignTags === undefined
|
|
104
|
-
? { campaign: true, source: false }
|
|
105
|
-
: { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false }
|
|
106
|
-
|
|
107
|
-
const out: string[] = []
|
|
108
|
-
for (const raw of [...(formTags ?? []), ...(callTags ?? [])]) {
|
|
109
|
-
const slug = slugify(raw)
|
|
110
|
-
if (slug) out.push(slug)
|
|
111
|
-
}
|
|
112
|
-
if (cfg.campaign && attribution.utm_campaign) {
|
|
113
|
-
const slug = slugify(attribution.utm_campaign)
|
|
114
|
-
if (slug) out.push(`camp:${slug}`)
|
|
115
|
-
}
|
|
116
|
-
if (cfg.source && attribution.utm_source) {
|
|
117
|
-
const slug = slugify(attribution.utm_source)
|
|
118
|
-
if (slug) out.push(`src:${slug}`)
|
|
119
|
-
}
|
|
120
|
-
return [...new Set(out)].slice(0, MAX_TAGS)
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export interface PublicFormsPlugin {
|
|
124
|
-
manifest: PluginManifest
|
|
125
|
-
Provider: FC<{ children: ReactNode }>
|
|
126
|
-
/** Imperative submit, for code paths outside React. */
|
|
127
|
-
submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/** Reads UTM + page context off the browser. Safe to call during SSR. */
|
|
131
|
-
export function readAttribution(): LeadAttribution {
|
|
132
|
-
if (typeof window === 'undefined') return {}
|
|
133
|
-
const params = new URLSearchParams(window.location.search)
|
|
134
|
-
const pick = (k: string) => params.get(k) || undefined
|
|
135
|
-
return {
|
|
136
|
-
utm_source: pick('utm_source'),
|
|
137
|
-
utm_medium: pick('utm_medium'),
|
|
138
|
-
utm_campaign: pick('utm_campaign'),
|
|
139
|
-
utm_term: pick('utm_term'),
|
|
140
|
-
utm_content: pick('utm_content'),
|
|
141
|
-
landing_page: window.location.pathname,
|
|
142
|
-
referrer: document.referrer || undefined,
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function isEmpty(value: unknown): boolean {
|
|
147
|
-
if (value === null || value === undefined) return true
|
|
148
|
-
if (typeof value === 'string') return value.trim() === ''
|
|
149
|
-
if (Array.isArray(value)) return value.length === 0
|
|
150
|
-
return false
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function stripUndefined<T extends Record<string, unknown>>(obj: T): T {
|
|
154
|
-
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
export function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {
|
|
158
|
-
const { tenantId } = options
|
|
159
|
-
const formsById = new Map(options.forms.map((f) => [f.id, f]))
|
|
160
|
-
|
|
161
|
-
const provider: PublicLeadDataProvider =
|
|
162
|
-
options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })
|
|
163
|
-
|
|
164
|
-
const notifier: LeadNotifier | null =
|
|
165
|
-
options.notifier ??
|
|
166
|
-
(options.inbox === false
|
|
167
|
-
? null
|
|
168
|
-
: createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))
|
|
169
|
-
|
|
170
|
-
const uploader: LeadUploader | null =
|
|
171
|
-
options.uploads === false
|
|
172
|
-
? null
|
|
173
|
-
: typeof options.uploads === 'object'
|
|
174
|
-
? options.uploads
|
|
175
|
-
: createSupabaseLeadUploader({ tenantId })
|
|
176
|
-
|
|
177
|
-
async function submit(
|
|
178
|
-
formId: string,
|
|
179
|
-
values: LeadFields,
|
|
180
|
-
submitOptions?: LeadSubmitOptions,
|
|
181
|
-
): Promise<LeadSubmitResult> {
|
|
182
|
-
const form = formsById.get(formId)
|
|
183
|
-
if (!form) {
|
|
184
|
-
throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form "${formId}".`)
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
// Identity fields are pulled OUT of the bag; whatever remains is custom.
|
|
188
|
-
const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }
|
|
189
|
-
const name = String(values[idMap.name] ?? '').trim()
|
|
190
|
-
const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''
|
|
191
|
-
const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''
|
|
192
|
-
const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''
|
|
193
|
-
|
|
194
|
-
for (const key of form.required ?? []) {
|
|
195
|
-
if (isEmpty(values[key])) {
|
|
196
|
-
throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')
|
|
200
|
-
if (!phone && !email) {
|
|
201
|
-
throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])
|
|
205
|
-
const fields: LeadFields = Object.fromEntries(
|
|
206
|
-
Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),
|
|
207
|
-
)
|
|
208
|
-
|
|
209
|
-
const attribution = readAttribution()
|
|
210
|
-
const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags)
|
|
211
|
-
|
|
212
|
-
// Ponteiros para arquivos que JÁ subiram (useLeadUploads). Aparados no teto
|
|
213
|
-
// do RPC: mandar mais só faria o servidor recusar o envio inteiro.
|
|
214
|
-
const attachments = (submitOptions?.attachments ?? [])
|
|
215
|
-
.filter((a) => a && typeof a.path === 'string' && a.path.length > 0)
|
|
216
|
-
.slice(0, MAX_LEAD_ATTACHMENTS)
|
|
217
|
-
|
|
218
|
-
// 1. CRM — if this throws, the submission failed and the site says so.
|
|
219
|
-
const { leadId, createdAt } = await provider.createLead(
|
|
220
|
-
stripUndefined({
|
|
221
|
-
formId: form.id,
|
|
222
|
-
formName: form.name,
|
|
223
|
-
name,
|
|
224
|
-
phone: phone || undefined,
|
|
225
|
-
email: email || undefined,
|
|
226
|
-
notes: notes || undefined,
|
|
227
|
-
fields,
|
|
228
|
-
attribution,
|
|
229
|
-
tags: tags.length ? tags : undefined,
|
|
230
|
-
attachments: attachments.length ? attachments : undefined,
|
|
231
|
-
}),
|
|
232
|
-
)
|
|
233
|
-
|
|
234
|
-
// 2. Inbox — the lead is already safe; never fail the form over a notice.
|
|
235
|
-
let notified = false
|
|
236
|
-
if (notifier) {
|
|
237
|
-
try {
|
|
238
|
-
await notifier.notify({
|
|
239
|
-
formId: form.id,
|
|
240
|
-
formName: form.name,
|
|
241
|
-
leadName: name,
|
|
242
|
-
phone: phone || undefined,
|
|
243
|
-
email: email || undefined,
|
|
244
|
-
fields,
|
|
245
|
-
labels: form.labels,
|
|
246
|
-
attribution,
|
|
247
|
-
attachmentCount: attachments.length || undefined,
|
|
248
|
-
})
|
|
249
|
-
notified = true
|
|
250
|
-
} catch (err) {
|
|
251
|
-
if (typeof console !== 'undefined') {
|
|
252
|
-
console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
return { leadId, createdAt, notified }
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
const Provider: FC<{ children: ReactNode }> = ({ children }) =>
|
|
261
|
-
createElement(PublicFormsProvider, { forms: formsById, submit, uploader, children })
|
|
262
|
-
Provider.displayName = 'PublicFormsProvider'
|
|
263
|
-
|
|
264
|
-
const manifest: PluginManifest = {
|
|
265
|
-
id: 'public-forms',
|
|
266
|
-
name: 'Formulários',
|
|
267
|
-
icon: 'Inbox',
|
|
268
|
-
version: '0.1.0',
|
|
269
|
-
scope: options.scope ?? 'universal',
|
|
270
|
-
verticalId: options.verticalId,
|
|
271
|
-
scaffolds: ['website', 'landing_page'],
|
|
272
|
-
defaultEnabled: true,
|
|
273
|
-
dependencies: [],
|
|
274
|
-
// Headless: the site owns the markup, so this plugin mounts no route and
|
|
275
|
-
// contributes no navigation. It exists to be registered and provide context.
|
|
276
|
-
navigation: [],
|
|
277
|
-
routes: [],
|
|
278
|
-
widgets: [],
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
return { manifest, Provider, submit }
|
|
282
|
-
}
|
|
@@ -1,92 +0,0 @@
|
|
|
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
|
-
// Anexos (015) viajam como PONTEIRO: o arquivo já subiu para o Storage por
|
|
14
|
-
// `createSupabaseLeadUploader`, e aqui vai só o caminho. O RPC descarta o que
|
|
15
|
-
// não estiver na pasta deste tenant.
|
|
16
|
-
// ---------------------------------------------------------------------------
|
|
17
|
-
|
|
18
|
-
import { getSupabaseClientOptional } from '@fayz-ai/core'
|
|
19
|
-
import { LeadSubmitError, type PublicLeadDataProvider } from './types'
|
|
20
|
-
|
|
21
|
-
export interface SupabasePublicLeadOptions {
|
|
22
|
-
/** The tenant leads land in (RPC arg — required). */
|
|
23
|
-
tenantId: string
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
interface SupabaseLikeClient {
|
|
27
|
-
rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function getClient(): SupabaseLikeClient | null {
|
|
31
|
-
return getSupabaseClientOptional() as SupabaseLikeClient | null
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */
|
|
35
|
-
function toSubmitError(message: string): LeadSubmitError {
|
|
36
|
-
const m = message.toLowerCase()
|
|
37
|
-
if (m.includes('duplicate submission')) {
|
|
38
|
-
return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')
|
|
39
|
-
}
|
|
40
|
-
if (m.includes('too many submissions')) {
|
|
41
|
-
return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')
|
|
42
|
-
}
|
|
43
|
-
if (
|
|
44
|
-
m.includes('invalid') ||
|
|
45
|
-
m.includes('required') ||
|
|
46
|
-
m.includes('too many fields') ||
|
|
47
|
-
m.includes('fields too large')
|
|
48
|
-
) {
|
|
49
|
-
return new LeadSubmitError('validation', message)
|
|
50
|
-
}
|
|
51
|
-
return new LeadSubmitError('unavailable', message)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export function createSupabasePublicLeadProvider(
|
|
55
|
-
options: SupabasePublicLeadOptions,
|
|
56
|
-
): PublicLeadDataProvider {
|
|
57
|
-
const { tenantId } = options
|
|
58
|
-
|
|
59
|
-
return {
|
|
60
|
-
async createLead(input) {
|
|
61
|
-
const client = getClient()
|
|
62
|
-
if (!client) {
|
|
63
|
-
throw new LeadSubmitError(
|
|
64
|
-
'unavailable',
|
|
65
|
-
'[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',
|
|
66
|
-
)
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const { data, error } = await client.rpc('create_public_lead', {
|
|
70
|
-
p_tenant_id: tenantId,
|
|
71
|
-
p_name: input.name,
|
|
72
|
-
p_phone: input.phone ?? null,
|
|
73
|
-
p_email: input.email ?? null,
|
|
74
|
-
p_form_id: input.formId,
|
|
75
|
-
p_form_name: input.formName,
|
|
76
|
-
p_fields: input.fields,
|
|
77
|
-
p_notes: input.notes ?? null,
|
|
78
|
-
p_utm: input.attribution,
|
|
79
|
-
p_tags: input.tags ?? [],
|
|
80
|
-
p_attachments: input.attachments ?? [],
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
if (error) throw toSubmitError(error.message)
|
|
84
|
-
|
|
85
|
-
const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined
|
|
86
|
-
if (!row?.lead_id) {
|
|
87
|
-
throw new LeadSubmitError('unavailable', 'Lead não foi criado.')
|
|
88
|
-
}
|
|
89
|
-
return { leadId: String(row.lead_id), createdAt: String(row.created_at) }
|
|
90
|
-
},
|
|
91
|
-
}
|
|
92
|
-
}
|
package/src/public/inbox.ts
DELETED
|
@@ -1,143 +0,0 @@
|
|
|
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
|
-
// Só a contagem: o aviso é um e-mail, e o anexo mora num bucket privado que
|
|
79
|
-
// só quem está logado no tenant pode abrir. Mandar link aqui seria vazar o
|
|
80
|
-
// arquivo para fora do controle de acesso — o CRM é onde ele se vê.
|
|
81
|
-
if (input.attachmentCount) {
|
|
82
|
-
payload['Anexos'] = String(input.attachmentCount)
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution
|
|
86
|
-
if (utm_source) payload['Origem'] = utm_source
|
|
87
|
-
if (utm_medium) payload['Mídia'] = utm_medium
|
|
88
|
-
if (utm_campaign) payload['Campanha'] = utm_campaign
|
|
89
|
-
if (landing_page) payload['Página'] = landing_page
|
|
90
|
-
|
|
91
|
-
return payload
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* A notifier that posts to the Fayz project inbox. Returns a no-op notifier
|
|
96
|
-
* (with one loud warning) when no project id is resolvable, so a site running
|
|
97
|
-
* outside Fayz still submits leads normally.
|
|
98
|
-
*/
|
|
99
|
-
export function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {
|
|
100
|
-
const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')
|
|
101
|
-
const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\/$/, '')
|
|
102
|
-
const timeoutMs = options.timeoutMs ?? 4000
|
|
103
|
-
|
|
104
|
-
if (!projectId) {
|
|
105
|
-
let warned = false
|
|
106
|
-
return {
|
|
107
|
-
async notify() {
|
|
108
|
-
if (!warned && typeof console !== 'undefined') {
|
|
109
|
-
warned = true
|
|
110
|
-
console.warn(
|
|
111
|
-
'[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +
|
|
112
|
-
'site owner is NOT notified in the Fayz inbox.',
|
|
113
|
-
)
|
|
114
|
-
}
|
|
115
|
-
},
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
return {
|
|
120
|
-
async notify(input) {
|
|
121
|
-
const controller = typeof AbortController !== 'undefined' ? new AbortController() : null
|
|
122
|
-
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
|
|
123
|
-
try {
|
|
124
|
-
const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {
|
|
125
|
-
method: 'POST',
|
|
126
|
-
headers: { 'Content-Type': 'application/json' },
|
|
127
|
-
signal: controller?.signal,
|
|
128
|
-
body: JSON.stringify({
|
|
129
|
-
source: 'form',
|
|
130
|
-
subject: `Novo lead: ${input.leadName} — ${input.formName}`,
|
|
131
|
-
payload: buildPayload(input),
|
|
132
|
-
metadata: { formId: input.formId, formName: input.formName, ...input.attribution },
|
|
133
|
-
}),
|
|
134
|
-
})
|
|
135
|
-
if (!res.ok) {
|
|
136
|
-
throw new Error(`inbox responded ${res.status}`)
|
|
137
|
-
}
|
|
138
|
-
} finally {
|
|
139
|
-
if (timer) clearTimeout(timer)
|
|
140
|
-
}
|
|
141
|
-
},
|
|
142
|
-
}
|
|
143
|
-
}
|