@fayz-ai/plugin-crm 0.8.4 → 0.9.0-next.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.
Files changed (59) hide show
  1. package/dist/components/BoardFilters.d.ts +23 -0
  2. package/dist/components/BoardFilters.d.ts.map +1 -0
  3. package/dist/components/TagChips.d.ts +16 -0
  4. package/dist/components/TagChips.d.ts.map +1 -0
  5. package/dist/data/mock.d.ts.map +1 -1
  6. package/dist/data/supabase.d.ts.map +1 -1
  7. package/dist/data/types.d.ts +4 -2
  8. package/dist/data/types.d.ts.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +461 -84
  12. package/dist/index.js.map +1 -1
  13. package/dist/locales/en.d.ts.map +1 -1
  14. package/dist/locales/pt-BR.d.ts.map +1 -1
  15. package/dist/migrations/index.d.ts +4 -0
  16. package/dist/migrations/index.d.ts.map +1 -1
  17. package/dist/public/context.d.ts +3 -3
  18. package/dist/public/context.d.ts.map +1 -1
  19. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  20. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  21. package/dist/public/data.supabase.d.ts.map +1 -1
  22. package/dist/public/index.js +29 -5
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/public/types.d.ts +27 -0
  25. package/dist/public/types.d.ts.map +1 -1
  26. package/dist/registries.d.ts.map +1 -1
  27. package/dist/store.d.ts +7 -2
  28. package/dist/store.d.ts.map +1 -1
  29. package/dist/types.d.ts +37 -0
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/views/DealSidebar.d.ts.map +1 -1
  32. package/dist/views/PipelineView.d.ts.map +1 -1
  33. package/package.json +15 -14
  34. package/src/components/BoardFilters.tsx +190 -0
  35. package/src/components/TagChips.tsx +80 -0
  36. package/src/data/mock.ts +31 -4
  37. package/src/data/supabase.ts +72 -5
  38. package/src/data/types.ts +6 -3
  39. package/src/index.ts +94 -0
  40. package/src/locales/en.ts +9 -0
  41. package/src/locales/pt-BR.ts +9 -0
  42. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  43. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  44. package/src/migrations/013_tag_slugs.sql +177 -0
  45. package/src/migrations/014_public_lead_tags.sql +172 -0
  46. package/src/migrations/index.ts +643 -1
  47. package/src/public/context.tsx +4 -4
  48. package/src/public/createPublicFormsPlugin.ts +72 -2
  49. package/src/public/data.supabase.ts +1 -0
  50. package/src/public/types.ts +28 -0
  51. package/src/registries.ts +12 -3
  52. package/src/store.ts +78 -57
  53. package/src/types.ts +40 -0
  54. package/src/views/DealSidebar.tsx +9 -6
  55. package/src/views/PipelineView.tsx +92 -9
  56. package/dist/index.cjs +0 -5354
  57. package/dist/index.cjs.map +0 -1
  58. package/dist/public/index.cjs +0 -306
  59. package/dist/public/index.cjs.map +0 -1
@@ -1,306 +0,0 @@
1
- 'use strict';
2
-
3
- var react = require('react');
4
- var core = require('@fayz-ai/core');
5
- var jsxRuntime = require('react/jsx-runtime');
6
-
7
- // src/public/createPublicFormsPlugin.ts
8
-
9
- // src/public/types.ts
10
- var LeadSubmitError = class extends Error {
11
- constructor(kind, message) {
12
- super(message);
13
- this.name = "LeadSubmitError";
14
- this.kind = kind;
15
- }
16
- };
17
-
18
- // src/public/data.supabase.ts
19
- function getClient() {
20
- return core.getSupabaseClientOptional();
21
- }
22
- function toSubmitError(message) {
23
- const m = message.toLowerCase();
24
- if (m.includes("duplicate submission")) {
25
- return new LeadSubmitError("duplicate", "Recebemos seu contato h\xE1 instantes.");
26
- }
27
- if (m.includes("too many submissions")) {
28
- return new LeadSubmitError("rate_limited", "Muitos envios agora h\xE1 pouco. Tente em instantes.");
29
- }
30
- if (m.includes("invalid") || m.includes("required") || m.includes("too many fields") || m.includes("fields too large")) {
31
- return new LeadSubmitError("validation", message);
32
- }
33
- return new LeadSubmitError("unavailable", message);
34
- }
35
- function createSupabasePublicLeadProvider(options) {
36
- const { tenantId } = options;
37
- return {
38
- async createLead(input) {
39
- const client = getClient();
40
- if (!client) {
41
- throw new LeadSubmitError(
42
- "unavailable",
43
- "[plugin-crm/public] no Supabase client \u2014 register one with setGlobalSupabaseClient."
44
- );
45
- }
46
- const { data, error } = await client.rpc("create_public_lead", {
47
- p_tenant_id: tenantId,
48
- p_name: input.name,
49
- p_phone: input.phone ?? null,
50
- p_email: input.email ?? null,
51
- p_form_id: input.formId,
52
- p_form_name: input.formName,
53
- p_fields: input.fields,
54
- p_notes: input.notes ?? null,
55
- p_utm: input.attribution
56
- });
57
- if (error) throw toSubmitError(error.message);
58
- const row = Array.isArray(data) ? data[0] : void 0;
59
- if (!row?.lead_id) {
60
- throw new LeadSubmitError("unavailable", "Lead n\xE3o foi criado.");
61
- }
62
- return { leadId: String(row.lead_id), createdAt: String(row.created_at) };
63
- }
64
- };
65
- }
66
-
67
- // src/public/inbox.ts
68
- function readEnv(key) {
69
- try {
70
- const env = undefined;
71
- return env?.[key];
72
- } catch {
73
- return void 0;
74
- }
75
- }
76
- function humanize(key, labels) {
77
- if (labels?.[key]) return labels[key];
78
- const spaced = key.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
79
- return spaced.charAt(0).toUpperCase() + spaced.slice(1);
80
- }
81
- function renderValue(value) {
82
- if (value === null || value === void 0 || value === "") return "\u2014";
83
- if (Array.isArray(value)) return value.length ? value.join(", ") : "\u2014";
84
- if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
85
- return String(value);
86
- }
87
- function buildPayload(input) {
88
- const payload = { Nome: input.leadName };
89
- if (input.phone) payload["Telefone"] = input.phone;
90
- if (input.email) payload["E-mail"] = input.email;
91
- for (const [key, value] of Object.entries(input.fields)) {
92
- payload[humanize(key, input.labels)] = renderValue(value);
93
- }
94
- const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution;
95
- if (utm_source) payload["Origem"] = utm_source;
96
- if (utm_medium) payload["M\xEDdia"] = utm_medium;
97
- if (utm_campaign) payload["Campanha"] = utm_campaign;
98
- if (landing_page) payload["P\xE1gina"] = landing_page;
99
- return payload;
100
- }
101
- function createFayzInboxNotifier(options = {}) {
102
- const projectId = options.projectId ?? readEnv("VITE_FAYZ_PROJECT_ID");
103
- const apiBaseUrl = (options.apiBaseUrl ?? readEnv("VITE_FAYZ_API_BASE_URL") ?? "/api").replace(/\/$/, "");
104
- const timeoutMs = options.timeoutMs ?? 4e3;
105
- if (!projectId) {
106
- let warned = false;
107
- return {
108
- async notify() {
109
- if (!warned && typeof console !== "undefined") {
110
- warned = true;
111
- console.warn(
112
- "[plugin-crm/public] no VITE_FAYZ_PROJECT_ID \u2014 leads are saved to the CRM but the site owner is NOT notified in the Fayz inbox."
113
- );
114
- }
115
- }
116
- };
117
- }
118
- return {
119
- async notify(input) {
120
- const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
121
- const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
122
- try {
123
- const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {
124
- method: "POST",
125
- headers: { "Content-Type": "application/json" },
126
- signal: controller?.signal,
127
- body: JSON.stringify({
128
- source: "form",
129
- subject: `Novo lead: ${input.leadName} \u2014 ${input.formName}`,
130
- payload: buildPayload(input),
131
- metadata: { formId: input.formId, formName: input.formName, ...input.attribution }
132
- })
133
- });
134
- if (!res.ok) {
135
- throw new Error(`inbox responded ${res.status}`);
136
- }
137
- } finally {
138
- if (timer) clearTimeout(timer);
139
- }
140
- }
141
- };
142
- }
143
- var PublicFormsContext = react.createContext(null);
144
- function PublicFormsProvider({ forms, submit, children }) {
145
- const value = react.useMemo(() => ({ forms, submit }), [forms, submit]);
146
- return /* @__PURE__ */ jsxRuntime.jsx(PublicFormsContext.Provider, { value, children });
147
- }
148
- function useLeadForm(formId) {
149
- const ctx = react.useContext(PublicFormsContext);
150
- if (!ctx) {
151
- throw new Error("[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.");
152
- }
153
- const [submitting, setSubmitting] = react.useState(false);
154
- const [error, setError] = react.useState(null);
155
- const [result, setResult] = react.useState(null);
156
- const submit = react.useCallback(
157
- async (values) => {
158
- if (submitting) return null;
159
- setSubmitting(true);
160
- setError(null);
161
- try {
162
- const res = await ctx.submit(formId, values);
163
- setResult(res);
164
- return res;
165
- } catch (err) {
166
- const e = err instanceof LeadSubmitError ? err : new LeadSubmitError("unavailable", err?.message ?? "Falha ao enviar.");
167
- setError(e);
168
- return null;
169
- } finally {
170
- setSubmitting(false);
171
- }
172
- },
173
- [ctx, formId, submitting]
174
- );
175
- const reset = react.useCallback(() => {
176
- setError(null);
177
- setResult(null);
178
- }, []);
179
- return {
180
- submit,
181
- reset,
182
- submitting,
183
- error,
184
- result,
185
- success: result !== null,
186
- form: ctx.forms.get(formId) ?? null
187
- };
188
- }
189
-
190
- // src/public/createPublicFormsPlugin.ts
191
- function readAttribution() {
192
- if (typeof window === "undefined") return {};
193
- const params = new URLSearchParams(window.location.search);
194
- const pick = (k) => params.get(k) || void 0;
195
- return {
196
- utm_source: pick("utm_source"),
197
- utm_medium: pick("utm_medium"),
198
- utm_campaign: pick("utm_campaign"),
199
- utm_term: pick("utm_term"),
200
- utm_content: pick("utm_content"),
201
- landing_page: window.location.pathname,
202
- referrer: document.referrer || void 0
203
- };
204
- }
205
- function isEmpty(value) {
206
- if (value === null || value === void 0) return true;
207
- if (typeof value === "string") return value.trim() === "";
208
- if (Array.isArray(value)) return value.length === 0;
209
- return false;
210
- }
211
- function stripUndefined(obj) {
212
- return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
213
- }
214
- function createPublicFormsPlugin(options) {
215
- const { tenantId } = options;
216
- const formsById = new Map(options.forms.map((f) => [f.id, f]));
217
- const provider = options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId });
218
- const notifier = options.notifier ?? (options.inbox === false ? null : createFayzInboxNotifier(typeof options.inbox === "object" ? options.inbox : {}));
219
- async function submit(formId, values) {
220
- const form = formsById.get(formId);
221
- if (!form) {
222
- throw new LeadSubmitError("validation", `[plugin-crm/public] unknown form "${formId}".`);
223
- }
224
- const idMap = { name: "name", phone: "phone", email: "email", ...form.identity };
225
- const name = String(values[idMap.name] ?? "").trim();
226
- const phone = idMap.phone ? String(values[idMap.phone] ?? "").trim() : "";
227
- const email = idMap.email ? String(values[idMap.email] ?? "").trim() : "";
228
- const notes = idMap.notes ? String(values[idMap.notes] ?? "").trim() : "";
229
- for (const key of form.required ?? []) {
230
- if (isEmpty(values[key])) {
231
- throw new LeadSubmitError("validation", `Campo obrigat\xF3rio: ${form.labels?.[key] ?? key}`);
232
- }
233
- }
234
- if (!name) throw new LeadSubmitError("validation", "Nome \xE9 obrigat\xF3rio.");
235
- if (!phone && !email) {
236
- throw new LeadSubmitError("validation", "Informe telefone ou e-mail.");
237
- }
238
- const identityKeys = new Set(Object.values(idMap).filter(Boolean));
239
- const fields = Object.fromEntries(
240
- Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v))
241
- );
242
- const attribution = readAttribution();
243
- const { leadId, createdAt } = await provider.createLead(
244
- stripUndefined({
245
- formId: form.id,
246
- formName: form.name,
247
- name,
248
- phone: phone || void 0,
249
- email: email || void 0,
250
- notes: notes || void 0,
251
- fields,
252
- attribution
253
- })
254
- );
255
- let notified = false;
256
- if (notifier) {
257
- try {
258
- await notifier.notify({
259
- formId: form.id,
260
- formName: form.name,
261
- leadName: name,
262
- phone: phone || void 0,
263
- email: email || void 0,
264
- fields,
265
- labels: form.labels,
266
- attribution
267
- });
268
- notified = true;
269
- } catch (err) {
270
- if (typeof console !== "undefined") {
271
- console.error("[plugin-crm/public] lead saved but inbox notification failed:", err);
272
- }
273
- }
274
- }
275
- return { leadId, createdAt, notified };
276
- }
277
- const Provider = ({ children }) => react.createElement(PublicFormsProvider, { forms: formsById, submit, children });
278
- Provider.displayName = "PublicFormsProvider";
279
- const manifest = {
280
- id: "public-forms",
281
- name: "Formul\xE1rios",
282
- icon: "Inbox",
283
- version: "0.1.0",
284
- scope: options.scope ?? "universal",
285
- verticalId: options.verticalId,
286
- scaffolds: ["website", "landing_page"],
287
- defaultEnabled: true,
288
- dependencies: [],
289
- // Headless: the site owns the markup, so this plugin mounts no route and
290
- // contributes no navigation. It exists to be registered and provide context.
291
- navigation: [],
292
- routes: [],
293
- widgets: []
294
- };
295
- return { manifest, Provider, submit };
296
- }
297
-
298
- exports.LeadSubmitError = LeadSubmitError;
299
- exports.PublicFormsProvider = PublicFormsProvider;
300
- exports.createFayzInboxNotifier = createFayzInboxNotifier;
301
- exports.createPublicFormsPlugin = createPublicFormsPlugin;
302
- exports.createSupabasePublicLeadProvider = createSupabasePublicLeadProvider;
303
- exports.readAttribution = readAttribution;
304
- exports.useLeadForm = useLeadForm;
305
- //# sourceMappingURL=index.cjs.map
306
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/public/types.ts","../../src/public/data.supabase.ts","../../src/public/inbox.ts","../../src/public/context.tsx","../../src/public/createPublicFormsPlugin.ts"],"names":["getSupabaseClientOptional","createContext","useMemo","jsx","useContext","useState","useCallback","createElement"],"mappings":";;;;;;;;;AAiEO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;;;AC/CA,SAAS,SAAA,GAAuC;AAC9C,EAAA,OAAOA,8BAAA,EAA0B;AACnC;AAGA,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,CAAE,QAAA,CAAS,sBAAsB,CAAA,EAAG;AACtC,IAAA,OAAO,IAAI,eAAA,CAAgB,WAAA,EAAa,wCAAqC,CAA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AAO,KAAA,IAAS,KAAA,CAAA;AAAA,UAChB,MAAA;AAAA,UACA,QAAQ,IAAA,CAAK,MAAA;AAAA,UACb;AAAA,SACD,CAAA;AACD,QAAA,QAAA,GAAW,IAAA;AAAA,MACb,SAAS,GAAA,EAAK;AACZ,QAAA,IAAI,OAAO,YAAY,WAAA,EAAa;AAClC,UAAA,OAAA,CAAQ,KAAA,CAAM,iEAAiE,GAAG,CAAA;AAAA,QACpF;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAA,EAAS;AAAA,EACvC;AAEA,EAAA,MAAM,QAAA,GAAwC,CAAC,EAAE,QAAA,EAAS,KACxDC,mBAAA,CAAc,mBAAA,EAAqB,EAAE,KAAA,EAAO,SAAA,EAAW,MAAA,EAAQ,QAAA,EAAU,CAAA;AAC3E,EAAA,QAAA,CAAS,WAAA,GAAc,qBAAA;AAEvB,EAAA,MAAM,QAAA,GAA2B;AAAA,IAC/B,EAAA,EAAI,cAAA;AAAA,IACJ,IAAA,EAAM,gBAAA;AAAA,IACN,IAAA,EAAM,OAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,KAAA,EAAO,QAAQ,KAAA,IAAS,WAAA;AAAA,IACxB,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,SAAA,EAAW,CAAC,SAAA,EAAW,cAAc,CAAA;AAAA,IACrC,cAAA,EAAgB,IAAA;AAAA,IAChB,cAAc,EAAC;AAAA;AAAA;AAAA,IAGf,YAAY,EAAC;AAAA,IACb,QAAQ,EAAC;AAAA,IACT,SAAS;AAAC,GACZ;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,EAAO;AACtC","file":"index.cjs","sourcesContent":["// ---------------------------------------------------------------------------\n// Public lead capture — types\n//\n// The contract between a marketing site's own form UI and the CRM. Sites keep\n// their bespoke layout and copy; all they hand over is a bag of values. Where\n// that lands (which tenant, which table, what status) is decided by the SDK and\n// the RPC behind it, never by the site.\n// ---------------------------------------------------------------------------\n\n/** What a form field may carry. Scalars and scalar lists — anything a checkbox\n * group, a select or a text input produces. Files are out of scope: a lead\n * form links to an upload, it does not embed one. */\nexport type LeadFieldValue = string | number | boolean | null | string[] | number[]\n\n/** The values a site collects, keyed by field id. Free-form on purpose: a new\n * landing page adds keys without touching the schema. */\nexport type LeadFields = Record<string, LeadFieldValue>\n\n/**\n * One form the site exposes. Registered up-front so submissions carry a stable\n * id (attribution) and a human name (what the operator reads in the CRM).\n */\nexport interface PublicFormDef {\n /** Stable id — the attribution key. Keep it stable across redesigns. */\n id: string\n /** Human name shown as the lead's source in the CRM. */\n name: string\n /**\n * Field ids that must be present and non-empty for the submission to be\n * attempted. Contact reachability (phone or email) is enforced server-side\n * regardless of what is declared here.\n */\n required?: string[]\n /**\n * Maps this form's field ids onto the lead's identity columns. Everything NOT\n * mapped stays in `fields` as a custom field.\n *\n * Defaults to { name: 'name', phone: 'phone', email: 'email' }.\n */\n identity?: {\n name?: string\n phone?: string\n email?: string\n /** Field whose value becomes the lead's free-text note. */\n notes?: string\n }\n /** Labels for custom fields, so the CRM shows \"Faixa etária\" not \"age_range\". */\n labels?: Record<string, string>\n}\n\n/** Result of a submission — enough for the site to show its own success state. */\nexport interface LeadSubmitResult {\n leadId: string\n createdAt: string\n /** False when the CRM write succeeded but the inbox notification did not. */\n notified: boolean\n}\n\n/** Thrown for problems the site should surface differently than a crash. */\nexport type LeadSubmitErrorKind =\n | 'validation' // missing required field / no contact channel\n | 'duplicate' // same contact, same form, seconds apart\n | 'rate_limited' // burst cap tripped\n | 'unavailable' // backend not configured or unreachable\n\nexport class LeadSubmitError extends Error {\n readonly kind: LeadSubmitErrorKind\n constructor(kind: LeadSubmitErrorKind, message: string) {\n super(message)\n this.name = 'LeadSubmitError'\n this.kind = kind\n }\n}\n\n/** UTM/attribution captured from the browser, merged into every submission. */\nexport interface LeadAttribution {\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n utm_term?: string\n utm_content?: string\n /** Path the form was submitted from. */\n landing_page?: string\n referrer?: string\n}\n\n/** The transport a submission goes through. Swappable for tests. */\nexport interface PublicLeadDataProvider {\n createLead(input: {\n formId: string\n formName: string\n name: string\n phone?: string\n email?: string\n notes?: string\n fields: LeadFields\n attribution: LeadAttribution\n }): Promise<{ leadId: string; createdAt: string }>\n}\n\n/** Notifies the site's admin that a lead arrived. */\nexport interface LeadNotifier {\n notify(input: {\n formId: string\n formName: string\n leadName: string\n phone?: string\n email?: string\n fields: LeadFields\n labels?: Record<string, string>\n attribution: LeadAttribution\n }): Promise<void>\n}\n","// ---------------------------------------------------------------------------\n// Supabase implementation of PublicLeadDataProvider — anon-safe.\n//\n// Public marketing pages run with the publishable (anon) key and NO user\n// session, so canonical tenant RLS yields nothing. This provider touches only\n// the one object designed for anon access:\n// - public.create_public_lead (SECURITY DEFINER RPC: validates, caps spam,\n// writes people[kind=lead] with the custom fields in metadata)\n// Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.\n//\n// The RPC never reads back — a form writes, it does not query the CRM.\n// ---------------------------------------------------------------------------\n\nimport { getSupabaseClientOptional } from '@fayz-ai/core'\nimport { LeadSubmitError, type PublicLeadDataProvider } from './types'\n\nexport interface SupabasePublicLeadOptions {\n /** The tenant leads land in (RPC arg — required). */\n tenantId: string\n}\n\ninterface SupabaseLikeClient {\n rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>\n}\n\nfunction getClient(): SupabaseLikeClient | null {\n return getSupabaseClientOptional() as SupabaseLikeClient | null\n}\n\n/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */\nfunction toSubmitError(message: string): LeadSubmitError {\n const m = message.toLowerCase()\n if (m.includes('duplicate submission')) {\n return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')\n }\n if (m.includes('too many submissions')) {\n return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')\n }\n if (\n m.includes('invalid') ||\n m.includes('required') ||\n m.includes('too many fields') ||\n m.includes('fields too large')\n ) {\n return new LeadSubmitError('validation', message)\n }\n return new LeadSubmitError('unavailable', message)\n}\n\nexport function createSupabasePublicLeadProvider(\n options: SupabasePublicLeadOptions,\n): PublicLeadDataProvider {\n const { tenantId } = options\n\n return {\n async createLead(input) {\n const client = getClient()\n if (!client) {\n throw new LeadSubmitError(\n 'unavailable',\n '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',\n )\n }\n\n const { data, error } = await client.rpc('create_public_lead', {\n p_tenant_id: tenantId,\n p_name: input.name,\n p_phone: input.phone ?? null,\n p_email: input.email ?? null,\n p_form_id: input.formId,\n p_form_name: input.formName,\n p_fields: input.fields,\n p_notes: input.notes ?? null,\n p_utm: input.attribution,\n })\n\n if (error) throw toSubmitError(error.message)\n\n const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined\n if (!row?.lead_id) {\n throw new LeadSubmitError('unavailable', 'Lead não foi criado.')\n }\n return { leadId: String(row.lead_id), createdAt: String(row.created_at) }\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Fayz inbox notifier — tells the site's owner a lead just arrived.\n//\n// The Fayz platform already ships a public ingest endpoint built for exactly\n// this (\"Deployed user-sites POST here\"): it stores an InboxRecord against the\n// project and emails the project owner. We only have to speak to it.\n//\n// POST <base>/public/projects/:projectId/inbox\n// { source, subject, payload, metadata }\n//\n// SAME-ORIGIN BY DEFAULT. In production the API's CORS allowlist is a single\n// origin (the editor), so a cross-origin POST from a published site would be\n// refused at preflight. Fayz's Caddy proxies `/api/*` to the API \"regardless of\n// host\", so a published site — custom domain included — reaches it same-origin\n// with no preflight at all. Hence the default base '/api' (relative). Only pass\n// an absolute base when the site is NOT served by Fayz, and expect to widen\n// CORS on the API before it works.\n//\n// Best-effort by contract: the lead is already safe in the CRM by the time this\n// runs. A failed notification is logged and swallowed — never a failed form.\n// ---------------------------------------------------------------------------\n\nimport type { LeadNotifier, LeadFields } from './types'\n\nexport interface FayzInboxNotifierOptions {\n /**\n * Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;\n * omit to read that env var automatically.\n */\n projectId?: string\n /**\n * API base. Defaults to '/api' (same-origin via Caddy) — see the note above\n * before changing it.\n */\n apiBaseUrl?: string\n /** Milliseconds before giving up. The visitor is waiting; keep it short. */\n timeoutMs?: number\n}\n\nfunction readEnv(key: string): string | undefined {\n try {\n const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env\n return env?.[key]\n } catch {\n return undefined\n }\n}\n\n/** \"age_range\" → \"Age range\", unless the form gave us a real label. */\nfunction humanize(key: string, labels?: Record<string, string>): string {\n if (labels?.[key]) return labels[key]\n const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\nfunction renderValue(value: unknown): string {\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value)) return value.length ? value.join(', ') : '—'\n if (typeof value === 'boolean') return value ? 'Sim' : 'Não'\n return String(value)\n}\n\n/**\n * Builds the flat, already-humanized payload the inbox renders. The editor\n * shows this verbatim, so it must read like a message — not like a database row.\n */\nfunction buildPayload(\n input: Parameters<LeadNotifier['notify']>[0],\n): Record<string, string> {\n const payload: Record<string, string> = { Nome: input.leadName }\n if (input.phone) payload['Telefone'] = input.phone\n if (input.email) payload['E-mail'] = input.email\n\n for (const [key, value] of Object.entries(input.fields as LeadFields)) {\n payload[humanize(key, input.labels)] = renderValue(value)\n }\n\n const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution\n if (utm_source) payload['Origem'] = utm_source\n if (utm_medium) payload['Mídia'] = utm_medium\n if (utm_campaign) payload['Campanha'] = utm_campaign\n if (landing_page) payload['Página'] = landing_page\n\n return payload\n}\n\n/**\n * A notifier that posts to the Fayz project inbox. Returns a no-op notifier\n * (with one loud warning) when no project id is resolvable, so a site running\n * outside Fayz still submits leads normally.\n */\nexport function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {\n const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')\n const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\\/$/, '')\n const timeoutMs = options.timeoutMs ?? 4000\n\n if (!projectId) {\n let warned = false\n return {\n async notify() {\n if (!warned && typeof console !== 'undefined') {\n warned = true\n console.warn(\n '[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +\n 'site owner is NOT notified in the Fayz inbox.',\n )\n }\n },\n }\n }\n\n return {\n async notify(input) {\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null\n try {\n const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: controller?.signal,\n body: JSON.stringify({\n source: 'form',\n subject: `Novo lead: ${input.leadName} — ${input.formName}`,\n payload: buildPayload(input),\n metadata: { formId: input.formId, formName: input.formName, ...input.attribution },\n }),\n })\n if (!res.ok) {\n throw new Error(`inbox responded ${res.status}`)\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n },\n }\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'\nimport { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types'\n\ninterface PublicFormsContextValue {\n forms: Map<string, PublicFormDef>\n submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>\n}\n\nconst PublicFormsContext = createContext<PublicFormsContextValue | null>(null)\n\nexport interface PublicFormsProviderProps extends PublicFormsContextValue {\n children: ReactNode\n}\n\nexport function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {\n const value = useMemo(() => ({ forms, submit }), [forms, submit])\n return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>\n}\n\n/** The hook a site's own form component calls. Owns only the submission\n * lifecycle — the markup, the fields and the validation copy stay the site's. */\nexport function useLeadForm(formId: string) {\n const ctx = useContext(PublicFormsContext)\n if (!ctx) {\n throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')\n }\n\n const [submitting, setSubmitting] = useState(false)\n const [error, setError] = useState<LeadSubmitError | null>(null)\n const [result, setResult] = useState<LeadSubmitResult | null>(null)\n\n const submit = useCallback(\n async (values: LeadFields): Promise<LeadSubmitResult | null> => {\n if (submitting) return null\n setSubmitting(true)\n setError(null)\n try {\n const res = await ctx.submit(formId, values)\n setResult(res)\n return res\n } catch (err) {\n const e =\n err instanceof LeadSubmitError\n ? err\n : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')\n setError(e)\n return null\n } finally {\n setSubmitting(false)\n }\n },\n [ctx, formId, submitting],\n )\n\n const reset = useCallback(() => {\n setError(null)\n setResult(null)\n }, [])\n\n return {\n submit,\n reset,\n submitting,\n error,\n result,\n success: result !== null,\n form: ctx.forms.get(formId) ?? null,\n }\n}\n","// ---------------------------------------------------------------------------\n// Public forms plugin — \"the site collects, the SDK decides where it goes\".\n//\n// Headless on purpose. Marketing sites have bespoke, brand-heavy forms; taking\n// over their markup would be a downgrade. So this ships no UI: a site keeps its\n// own inputs and calls submit() with a plain object of values.\n//\n// Every submission fans out to two places, in this order:\n// 1. the tenant's CRM (create_public_lead) — the record of truth\n// 2. the Fayz project inbox — so the site owner is told, and gets the email\n// Step 2 is best-effort: a notification outage must never cost a lead.\n// ---------------------------------------------------------------------------\n\nimport { createElement, type FC, type ReactNode } from 'react'\nimport type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'\nimport { createSupabasePublicLeadProvider } from './data.supabase'\nimport { createFayzInboxNotifier } from './inbox'\nimport { PublicFormsProvider } from './context'\nimport {\n LeadSubmitError,\n type LeadAttribution,\n type LeadFields,\n type LeadNotifier,\n type LeadSubmitResult,\n type PublicFormDef,\n type PublicLeadDataProvider,\n} from './types'\n\nexport interface PublicFormsOptions {\n /**\n * Tenant the leads land in. REQUIRED — this is the whole point of the\n * abstraction: the site never names a table, only a tenant.\n */\n tenantId: string\n /** The forms this site exposes, keyed by id. */\n forms: PublicFormDef[]\n /**\n * Notify the site owner in the Fayz project inbox. Default true; resolves the\n * project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.\n */\n inbox?: boolean | { projectId?: string; apiBaseUrl?: string }\n /** Inject a custom transport (tests, or a non-Supabase backend). */\n dataProvider?: PublicLeadDataProvider\n /** Inject a custom notifier (tests). */\n notifier?: LeadNotifier\n scope?: PluginScope\n verticalId?: VerticalId\n}\n\nexport interface PublicFormsPlugin {\n manifest: PluginManifest\n Provider: FC<{ children: ReactNode }>\n /** Imperative submit, for code paths outside React. */\n submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>\n}\n\n/** Reads UTM + page context off the browser. Safe to call during SSR. */\nexport function readAttribution(): LeadAttribution {\n if (typeof window === 'undefined') return {}\n const params = new URLSearchParams(window.location.search)\n const pick = (k: string) => params.get(k) || undefined\n return {\n utm_source: pick('utm_source'),\n utm_medium: pick('utm_medium'),\n utm_campaign: pick('utm_campaign'),\n utm_term: pick('utm_term'),\n utm_content: pick('utm_content'),\n landing_page: window.location.pathname,\n referrer: document.referrer || undefined,\n }\n}\n\nfunction isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T\n}\n\nexport function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {\n const { tenantId } = options\n const formsById = new Map(options.forms.map((f) => [f.id, f]))\n\n const provider: PublicLeadDataProvider =\n options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })\n\n const notifier: LeadNotifier | null =\n options.notifier ??\n (options.inbox === false\n ? null\n : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))\n\n async function submit(formId: string, values: LeadFields): Promise<LeadSubmitResult> {\n const form = formsById.get(formId)\n if (!form) {\n throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form \"${formId}\".`)\n }\n\n // Identity fields are pulled OUT of the bag; whatever remains is custom.\n const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }\n const name = String(values[idMap.name] ?? '').trim()\n const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''\n const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''\n const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''\n\n for (const key of form.required ?? []) {\n if (isEmpty(values[key])) {\n throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)\n }\n }\n if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')\n if (!phone && !email) {\n throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')\n }\n\n const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])\n const fields: LeadFields = Object.fromEntries(\n Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),\n )\n\n const attribution = readAttribution()\n\n // 1. CRM — if this throws, the submission failed and the site says so.\n const { leadId, createdAt } = await provider.createLead(\n stripUndefined({\n formId: form.id,\n formName: form.name,\n name,\n phone: phone || undefined,\n email: email || undefined,\n notes: notes || undefined,\n fields,\n attribution,\n }),\n )\n\n // 2. Inbox — the lead is already safe; never fail the form over a notice.\n let notified = false\n if (notifier) {\n try {\n await notifier.notify({\n formId: form.id,\n formName: form.name,\n leadName: name,\n phone: phone || undefined,\n email: email || undefined,\n fields,\n labels: form.labels,\n attribution,\n })\n notified = true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)\n }\n }\n }\n\n return { leadId, createdAt, notified }\n }\n\n const Provider: FC<{ children: ReactNode }> = ({ children }) =>\n createElement(PublicFormsProvider, { forms: formsById, submit, children })\n Provider.displayName = 'PublicFormsProvider'\n\n const manifest: PluginManifest = {\n id: 'public-forms',\n name: 'Formulários',\n icon: 'Inbox',\n version: '0.1.0',\n scope: options.scope ?? 'universal',\n verticalId: options.verticalId,\n scaffolds: ['website', 'landing_page'],\n defaultEnabled: true,\n dependencies: [],\n // Headless: the site owns the markup, so this plugin mounts no route and\n // contributes no navigation. It exists to be registered and provide context.\n navigation: [],\n routes: [],\n widgets: [],\n }\n\n return { manifest, Provider, submit }\n}\n"]}