@fayz-ai/plugin-crm 0.9.0 → 0.9.2

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 (122) hide show
  1. package/README.md +3 -3
  2. package/dist/components/AutomationBolt.d.ts +22 -0
  3. package/dist/components/AutomationBolt.d.ts.map +1 -0
  4. package/dist/{CrmContext.d.ts → context.d.ts} +4 -2
  5. package/dist/context.d.ts.map +1 -0
  6. package/dist/data/mock.d.ts.map +1 -1
  7. package/dist/data/registries.d.ts.map +1 -0
  8. package/dist/data/types.d.ts +4 -1
  9. package/dist/data/types.d.ts.map +1 -1
  10. package/dist/index.d.ts +16 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +609 -493
  13. package/dist/index.js.map +1 -1
  14. package/dist/{cascade.d.ts → lib/cascade.d.ts} +1 -1
  15. package/dist/lib/cascade.d.ts.map +1 -0
  16. package/dist/lib/message-events.d.ts +13 -0
  17. package/dist/lib/message-events.d.ts.map +1 -0
  18. package/dist/lib/timeline-source.d.ts +10 -0
  19. package/dist/lib/timeline-source.d.ts.map +1 -0
  20. package/dist/locales/en.d.ts.map +1 -1
  21. package/dist/locales/pt-BR.d.ts.map +1 -1
  22. package/dist/public/context.d.ts +1 -1
  23. package/dist/public/context.d.ts.map +1 -1
  24. package/dist/public/createPublicFormsPlugin.d.ts +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  26. package/dist/public/{data.supabase.d.ts → data/supabase.d.ts} +2 -2
  27. package/dist/public/data/supabase.d.ts.map +1 -0
  28. package/dist/public/index.d.ts +6 -6
  29. package/dist/public/index.d.ts.map +1 -1
  30. package/dist/public/index.js +2 -2
  31. package/dist/public/index.js.map +1 -1
  32. package/dist/public/{inbox.d.ts → lib/inbox.d.ts} +1 -1
  33. package/dist/public/lib/inbox.d.ts.map +1 -0
  34. package/dist/public/{uploads.d.ts → lib/uploads.d.ts} +1 -1
  35. package/dist/public/lib/uploads.d.ts.map +1 -0
  36. package/dist/store.d.ts +9 -0
  37. package/dist/store.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts.map +1 -1
  39. package/dist/{CrmPage.d.ts → views/CrmPage.d.ts} +3 -3
  40. package/dist/views/CrmPage.d.ts.map +1 -0
  41. package/dist/views/DealSidebar.d.ts.map +1 -1
  42. package/dist/views/LeadListView.d.ts.map +1 -1
  43. package/dist/views/PipelineView.d.ts +3 -1
  44. package/dist/views/PipelineView.d.ts.map +1 -1
  45. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  46. package/dist/views/QuoteFormView.d.ts.map +1 -1
  47. package/dist/views/QuoteListView.d.ts.map +1 -1
  48. package/dist/views/dashboardWidgets.d.ts +1 -1
  49. package/dist/views/dashboardWidgets.d.ts.map +1 -1
  50. package/package.json +6 -10
  51. package/dist/CrmContext.d.ts.map +0 -1
  52. package/dist/CrmPage.d.ts.map +0 -1
  53. package/dist/cascade.d.ts.map +0 -1
  54. package/dist/public/data.supabase.d.ts.map +0 -1
  55. package/dist/public/inbox.d.ts.map +0 -1
  56. package/dist/public/uploads.d.ts.map +0 -1
  57. package/dist/registries.d.ts.map +0 -1
  58. package/src/CrmContext.tsx +0 -30
  59. package/src/CrmPage.tsx +0 -150
  60. package/src/README.md +0 -97
  61. package/src/cascade.ts +0 -26
  62. package/src/components/BoardFilters.tsx +0 -190
  63. package/src/components/CrmGeneralSettings.tsx +0 -56
  64. package/src/components/CrmOnboarding.tsx +0 -52
  65. package/src/components/LeadAttachments.tsx +0 -140
  66. package/src/components/PipelineSettings.tsx +0 -45
  67. package/src/components/QuoteStatusDropdown.tsx +0 -226
  68. package/src/components/TagChips.tsx +0 -80
  69. package/src/data/index.ts +0 -2
  70. package/src/data/mock.ts +0 -559
  71. package/src/data/supabase.ts +0 -928
  72. package/src/data/tables.ts +0 -11
  73. package/src/data/types.ts +0 -61
  74. package/src/index.ts +0 -429
  75. package/src/lib/access.ts +0 -11
  76. package/src/lib/form-answers.tsx +0 -80
  77. package/src/lib/relative-time.ts +0 -84
  78. package/src/lib/tenant.ts +0 -4
  79. package/src/locales/en.ts +0 -307
  80. package/src/locales/index.ts +0 -7
  81. package/src/locales/pt-BR.ts +0 -307
  82. package/src/migrations/000_plg_rename.sql +0 -28
  83. package/src/migrations/001_crm_base.sql +0 -73
  84. package/src/migrations/002_activities.sql +0 -33
  85. package/src/migrations/003_crm_views_rls.sql +0 -69
  86. package/src/migrations/004_seed_default_pipeline.sql +0 -31
  87. package/src/migrations/005_public_lead.sql +0 -189
  88. package/src/migrations/006_lead_enters_pipeline.sql +0 -265
  89. package/src/migrations/007_activity_log.sql +0 -55
  90. package/src/migrations/008_view_field_aliases.sql +0 -43
  91. package/src/migrations/009_deal_archived_status.sql +0 -30
  92. package/src/migrations/010_quote_archived_status.sql +0 -40
  93. package/src/migrations/011_agent_rpc_update_lead.sql +0 -153
  94. package/src/migrations/012_agent_rpc_create_lead.sql +0 -128
  95. package/src/migrations/013_tag_slugs.sql +0 -177
  96. package/src/migrations/014_public_lead_tags.sql +0 -172
  97. package/src/migrations/015_lead_attachments.sql +0 -357
  98. package/src/migrations/016_public_lead_activity.sql +0 -123
  99. package/src/migrations/index.ts +0 -2023
  100. package/src/public/context.tsx +0 -150
  101. package/src/public/createPublicFormsPlugin.ts +0 -282
  102. package/src/public/data.supabase.ts +0 -92
  103. package/src/public/inbox.ts +0 -143
  104. package/src/public/index.ts +0 -51
  105. package/src/public/types.ts +0 -173
  106. package/src/public/uploads.ts +0 -205
  107. package/src/registries.ts +0 -162
  108. package/src/schema/index.ts +0 -104
  109. package/src/store.ts +0 -472
  110. package/src/types.ts +0 -337
  111. package/src/views/ActivityListView.tsx +0 -264
  112. package/src/views/DashboardView.tsx +0 -12
  113. package/src/views/DealSidebar.tsx +0 -482
  114. package/src/views/LeadDetailView.tsx +0 -378
  115. package/src/views/LeadFormView.tsx +0 -66
  116. package/src/views/LeadListView.tsx +0 -100
  117. package/src/views/PipelineView.tsx +0 -446
  118. package/src/views/QuoteDetailView.tsx +0 -412
  119. package/src/views/QuoteFormView.tsx +0 -494
  120. package/src/views/QuoteListView.tsx +0 -115
  121. package/src/views/dashboardWidgets.tsx +0 -248
  122. /package/dist/{registries.d.ts → data/registries.d.ts} +0 -0
@@ -1,51 +0,0 @@
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
- // Anexo segue a mesma divisão: o site diz "esta foto é a `frente`", e o plugin
9
- // resolve bucket, pasta e caminho (useLeadUploads → migrations/015).
10
- // ---------------------------------------------------------------------------
11
-
12
- export { createPublicFormsPlugin, readAttribution } from './createPublicFormsPlugin'
13
- export type { PublicFormsOptions, PublicFormsPlugin } from './createPublicFormsPlugin'
14
-
15
- export { PublicFormsProvider, useLeadForm, useLeadUploads } from './context'
16
-
17
- export { createSupabasePublicLeadProvider } from './data.supabase'
18
- export type { SupabasePublicLeadOptions } from './data.supabase'
19
-
20
- export {
21
- createSupabaseLeadUploader,
22
- buildLeadUploadPath,
23
- newSubmissionId,
24
- LEAD_UPLOADS_BUCKET,
25
- LEAD_ATTACHMENT_MIME_TYPES,
26
- MAX_LEAD_ATTACHMENTS,
27
- MAX_LEAD_ATTACHMENT_BYTES,
28
- } from './uploads'
29
- export type {
30
- LeadUploader,
31
- LeadUploadInput,
32
- LeadUploadPathInput,
33
- SupabaseLeadUploaderOptions,
34
- } from './uploads'
35
-
36
- export { createFayzInboxNotifier } from './inbox'
37
- export type { FayzInboxNotifierOptions } from './inbox'
38
-
39
- export { LeadSubmitError } from './types'
40
- export type {
41
- LeadAttachment,
42
- LeadAttribution,
43
- LeadFieldValue,
44
- LeadFields,
45
- LeadNotifier,
46
- LeadSubmitErrorKind,
47
- LeadSubmitOptions,
48
- LeadSubmitResult,
49
- PublicFormDef,
50
- PublicLeadDataProvider,
51
- } from './types'
@@ -1,173 +0,0 @@
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 (see `LeadAttachment`), it does not embed one. */
13
- export type LeadFieldValue = string | number | boolean | null | string[] | number[]
14
-
15
- /**
16
- * Um arquivo que veio junto com o lead — o PONTEIRO dele, não o conteúdo.
17
- *
18
- * Esta é a separação que faz o resto funcionar: o arquivo mora no Storage
19
- * (bucket `crm-lead-uploads`, pasta do tenant), e o lead guarda só o caminho.
20
- * O payload do formulário segue pequeno, o anexo herda os limites do bucket, e
21
- * apagar a foto não obriga a reescrever o lead.
22
- *
23
- * Produzido pelo `LeadUploader` — o site nunca monta este objeto na mão.
24
- */
25
- export interface LeadAttachment {
26
- /** Caminho dentro do bucket. Sempre começa pela pasta do tenant. */
27
- path: string
28
- /** Nome semântico ("frente", "nuca") — é o rótulo que o operador lê no card. */
29
- slot?: string
30
- mime?: string
31
- size?: number
32
- }
33
-
34
- /** The values a site collects, keyed by field id. Free-form on purpose: a new
35
- * landing page adds keys without touching the schema. */
36
- export type LeadFields = Record<string, LeadFieldValue>
37
-
38
- /**
39
- * One form the site exposes. Registered up-front so submissions carry a stable
40
- * id (attribution) and a human name (what the operator reads in the CRM).
41
- */
42
- export interface PublicFormDef {
43
- /** Stable id — the attribution key. Keep it stable across redesigns. */
44
- id: string
45
- /** Human name shown as the lead's source in the CRM. */
46
- name: string
47
- /**
48
- * Field ids that must be present and non-empty for the submission to be
49
- * attempted. Contact reachability (phone or email) is enforced server-side
50
- * regardless of what is declared here.
51
- */
52
- required?: string[]
53
- /**
54
- * Maps this form's field ids onto the lead's identity columns. Everything NOT
55
- * mapped stays in `fields` as a custom field.
56
- *
57
- * Defaults to { name: 'name', phone: 'phone', email: 'email' }.
58
- */
59
- identity?: {
60
- name?: string
61
- phone?: string
62
- email?: string
63
- /** Field whose value becomes the lead's free-text note. */
64
- notes?: string
65
- }
66
- /** Labels for custom fields, so the CRM shows "Faixa etária" not "age_range". */
67
- labels?: Record<string, string>
68
- /**
69
- * Tags every lead from this form carries into the CRM, and from there onto
70
- * the card no funil (o trigger de lead→deal copia).
71
- *
72
- * Isto é o vocabulário CURADO: o que a landing page É ("aluno-novo",
73
- * "parceria"), não de qual campanha veio. Escreva em slug; o servidor
74
- * normaliza de qualquer jeito (minúscula, sem acento, hifenizado) e descarta
75
- * o que não der para normalizar em vez de derrubar o envio.
76
- *
77
- * Máximo de 10 tags por lead, somando estas e as automáticas.
78
- */
79
- tags?: string[]
80
- }
81
-
82
- /**
83
- * O que a PÁGINA decide na hora do envio, e o formulário não sabe de antemão.
84
- *
85
- * Existe porque uma landing page costuma ter mais de uma porta de entrada para
86
- * o mesmo formulário (a home e uma campanha específica levam ao mesmo
87
- * `/quero-ser-aluno`). Sem isto, distinguir as duas exigiria declarar um
88
- * formulário por porta, e cada um vira uma "origem" diferente no CRM para o que
89
- * é o mesmo formulário.
90
- */
91
- export interface LeadSubmitOptions {
92
- /** Somadas às `tags` do formulário e às automáticas da campanha. */
93
- tags?: string[]
94
- /**
95
- * Anexos já enviados ao Storage — o retorno de `useLeadUploads().upload`.
96
- *
97
- * Vêm no envio, e não em `values`, porque não são resposta de campo: o
98
- * servidor os valida por outra regra (caminho dentro da pasta do tenant) e os
99
- * guarda em outro lugar do lead. Máximo de 10; os inválidos são descartados
100
- * pelo banco sem derrubar a submissão.
101
- */
102
- attachments?: LeadAttachment[]
103
- }
104
-
105
- /** Result of a submission — enough for the site to show its own success state. */
106
- export interface LeadSubmitResult {
107
- leadId: string
108
- createdAt: string
109
- /** False when the CRM write succeeded but the inbox notification did not. */
110
- notified: boolean
111
- }
112
-
113
- /** Thrown for problems the site should surface differently than a crash. */
114
- export type LeadSubmitErrorKind =
115
- | 'validation' // missing required field / no contact channel
116
- | 'duplicate' // same contact, same form, seconds apart
117
- | 'rate_limited' // burst cap tripped
118
- | 'unavailable' // backend not configured or unreachable
119
-
120
- export class LeadSubmitError extends Error {
121
- readonly kind: LeadSubmitErrorKind
122
- constructor(kind: LeadSubmitErrorKind, message: string) {
123
- super(message)
124
- this.name = 'LeadSubmitError'
125
- this.kind = kind
126
- }
127
- }
128
-
129
- /** UTM/attribution captured from the browser, merged into every submission. */
130
- export interface LeadAttribution {
131
- utm_source?: string
132
- utm_medium?: string
133
- utm_campaign?: string
134
- utm_term?: string
135
- utm_content?: string
136
- /** Path the form was submitted from. */
137
- landing_page?: string
138
- referrer?: string
139
- }
140
-
141
- /** The transport a submission goes through. Swappable for tests. */
142
- export interface PublicLeadDataProvider {
143
- createLead(input: {
144
- formId: string
145
- formName: string
146
- name: string
147
- phone?: string
148
- email?: string
149
- notes?: string
150
- fields: LeadFields
151
- attribution: LeadAttribution
152
- /** Slugs já resolvidos (curados do formulário + automáticos da campanha). */
153
- tags?: string[]
154
- /** Ponteiros para arquivos já no Storage. */
155
- attachments?: LeadAttachment[]
156
- }): Promise<{ leadId: string; createdAt: string }>
157
- }
158
-
159
- /** Notifies the site's admin that a lead arrived. */
160
- export interface LeadNotifier {
161
- notify(input: {
162
- formId: string
163
- formName: string
164
- leadName: string
165
- phone?: string
166
- email?: string
167
- fields: LeadFields
168
- labels?: Record<string, string>
169
- attribution: LeadAttribution
170
- /** Só a contagem interessa ao aviso: o inbox não serve arquivo privado. */
171
- attachmentCount?: number
172
- }): Promise<void>
173
- }
@@ -1,205 +0,0 @@
1
- // ---------------------------------------------------------------------------
2
- // Anexos de lead — onde o arquivo mora, e quem decide isso.
3
- //
4
- // O site NÃO nomeia bucket nem monta caminho. Ele diz "esta foto é a `frente`
5
- // do formulário `capilar`" e recebe de volta um ponteiro. É a mesma divisão do
6
- // resto deste módulo: a página coleta, o SDK decide onde vai parar.
7
- //
8
- // Vale insistir no porquê de um bucket só: num pool de indústria há centenas de
9
- // tenants no mesmo projeto Supabase. Bucket por tenant multiplicaria
10
- // configuração (mime, tamanho, política) por tenant, e provisionar um novo
11
- // cliente passaria a exigir criar bucket. Um bucket, o tenant como primeira
12
- // pasta, e o isolamento decidido por RLS no banco — nunca pelo cliente.
13
- //
14
- // A gramática do caminho é contrato compartilhado com a migration 015: o SDK
15
- // monta, o banco confere. Mudar de lado sozinho quebra o upload.
16
- // ---------------------------------------------------------------------------
17
-
18
- import { getSupabaseClientOptional } from '@fayz-ai/core'
19
- import { LeadSubmitError, type LeadAttachment } from './types'
20
-
21
- /**
22
- * O bucket dos anexos de lead. Compartilhado por todos os tenants do projeto e
23
- * por qualquer app de backoffice que leia o CRM — as pastas é que separam.
24
- *
25
- * Privado: anexo de lead é dado pessoal (numa clínica, dado de saúde). Leitura
26
- * é sempre por URL assinada, de curta duração, para quem está logado no tenant.
27
- */
28
- export const LEAD_UPLOADS_BUCKET = 'crm-lead-uploads'
29
-
30
- /** Teto por lead — o mesmo que o RPC aplica. */
31
- export const MAX_LEAD_ATTACHMENTS = 10
32
-
33
- /** 10 MB — igual ao limite do bucket; barrar aqui evita a viagem inútil. */
34
- export const MAX_LEAD_ATTACHMENT_BYTES = 10 * 1024 * 1024
35
-
36
- /** Os tipos que o bucket aceita. Rejeitar antes do upload dá erro legível. */
37
- export const LEAD_ATTACHMENT_MIME_TYPES = [
38
- 'image/jpeg',
39
- 'image/png',
40
- 'image/webp',
41
- 'image/heic',
42
- 'image/heif',
43
- 'application/pdf',
44
- ] as const
45
-
46
- const EXT_BY_MIME: Record<string, string> = {
47
- 'image/jpeg': 'jpg',
48
- 'image/png': 'png',
49
- 'image/webp': 'webp',
50
- 'image/heic': 'heic',
51
- 'image/heif': 'heif',
52
- 'application/pdf': 'pdf',
53
- }
54
-
55
- /** Segmento de caminho seguro: minúsculo, sem acento, sem barra, sem "..". */
56
- function pathSegment(input: string, fallback: string): string {
57
- const slug = input
58
- .normalize('NFD')
59
- // Marcas combinantes — o NFD separa o acento da letra e este range remove
60
- // só o acento. Escapado porque o caractere cru é invisível no editor.
61
- .replace(/[\u0300-\u036f]/g, '')
62
- .toLowerCase()
63
- .replace(/[^a-z0-9._-]+/g, '-')
64
- .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')
65
- .slice(0, 64)
66
- return slug || fallback
67
- }
68
-
69
- /**
70
- * uuid v4. `crypto.randomUUID` existe em todo browser que a stack suporta; o
71
- * fallback cobre contexto não-seguro (http em dev) onde ele some.
72
- */
73
- function uuid(): string {
74
- const c = typeof globalThis !== 'undefined' ? (globalThis.crypto as Crypto | undefined) : undefined
75
- if (c?.randomUUID) return c.randomUUID()
76
- const bytes = new Uint8Array(16)
77
- if (c?.getRandomValues) c.getRandomValues(bytes)
78
- else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)
79
- bytes[6] = (bytes[6] & 0x0f) | 0x40
80
- bytes[8] = (bytes[8] & 0x3f) | 0x80
81
- const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('')
82
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
83
- }
84
-
85
- /**
86
- * Um envio. Os arquivos de um mesmo preenchimento compartilham este id, então
87
- * ficam juntos numa pasta — e como é aleatório, o caminho não se adivinha.
88
- */
89
- export function newSubmissionId(): string {
90
- return uuid()
91
- }
92
-
93
- export interface LeadUploadPathInput {
94
- tenantId: string
95
- formId: string
96
- /** Agrupa os arquivos de um mesmo preenchimento. */
97
- submissionId: string
98
- /** Nome semântico do anexo: "frente", "nuca", "documento". */
99
- slot: string
100
- /** Usado só para escolher a extensão. */
101
- mimeType?: string
102
- /** Data do envio — injetável para teste. */
103
- now?: Date
104
- }
105
-
106
- /**
107
- * `{tenant}/{form}/{yyyy}/{mm}/{submission}/{slot}.{ext}` — a gramática que a
108
- * policy do bucket confere. Ver o cabeçalho da migration 015 para o porquê de
109
- * cada segmento.
110
- */
111
- export function buildLeadUploadPath(input: LeadUploadPathInput): string {
112
- const at = input.now ?? new Date()
113
- const yyyy = String(at.getUTCFullYear())
114
- const mm = String(at.getUTCMonth() + 1).padStart(2, '0')
115
- const ext = EXT_BY_MIME[input.mimeType ?? ''] ?? 'bin'
116
- const form = pathSegment(input.formId, 'form')
117
- const slot = pathSegment(input.slot, 'anexo')
118
- return `${input.tenantId}/${form}/${yyyy}/${mm}/${input.submissionId}/${slot}.${ext}`
119
- }
120
-
121
- export interface LeadUploadInput {
122
- formId: string
123
- /** Nome semântico do anexo — vira o nome do arquivo e o rótulo no CRM. */
124
- slot: string
125
- file: File | Blob
126
- /** Agrupa vários anexos do mesmo preenchimento. Um novo é criado se omitido. */
127
- submissionId?: string
128
- }
129
-
130
- /** O transporte do upload. Trocável em teste, como o provider de lead. */
131
- export interface LeadUploader {
132
- upload(input: LeadUploadInput): Promise<LeadAttachment>
133
- }
134
-
135
- export interface SupabaseLeadUploaderOptions {
136
- /** Tenant dono da pasta — o primeiro segmento do caminho. */
137
- tenantId: string
138
- }
139
-
140
- function mimeOf(file: File | Blob): string {
141
- return (file as File).type || 'application/octet-stream'
142
- }
143
-
144
- /** A fatia do cliente que este módulo usa — mesma abordagem estrutural do
145
- * provider de lead, que não depende do tipo completo do supabase-js. */
146
- interface StorageLikeClient {
147
- storage: {
148
- from(bucket: string): {
149
- upload(
150
- path: string,
151
- file: File | Blob,
152
- options?: { contentType?: string; upsert?: boolean },
153
- ): PromiseLike<{ error: { message: string } | null }>
154
- }
155
- }
156
- }
157
-
158
- /**
159
- * Sobe direto do browser para o Storage, com a chave publicável. A policy de
160
- * INSERT da migration 015 é quem autoriza — e ela só olha o caminho, porque é a
161
- * única coisa que um anônimo pode oferecer que o banco sabe verificar.
162
- */
163
- export function createSupabaseLeadUploader(options: SupabaseLeadUploaderOptions): LeadUploader {
164
- const { tenantId } = options
165
-
166
- return {
167
- async upload(input: LeadUploadInput): Promise<LeadAttachment> {
168
- const client = getSupabaseClientOptional() as StorageLikeClient | null
169
- if (!client) {
170
- throw new LeadSubmitError(
171
- 'unavailable',
172
- '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',
173
- )
174
- }
175
-
176
- const mime = mimeOf(input.file)
177
- if (!(LEAD_ATTACHMENT_MIME_TYPES as readonly string[]).includes(mime)) {
178
- throw new LeadSubmitError('validation', 'Formato não suportado. Use JPG, PNG, WebP, HEIC ou PDF.')
179
- }
180
- if (input.file.size > MAX_LEAD_ATTACHMENT_BYTES) {
181
- throw new LeadSubmitError('validation', 'Arquivo muito grande. Máximo 10MB.')
182
- }
183
-
184
- const path = buildLeadUploadPath({
185
- tenantId,
186
- formId: input.formId,
187
- submissionId: input.submissionId ?? newSubmissionId(),
188
- slot: input.slot,
189
- mimeType: mime,
190
- })
191
-
192
- const { error } = await client.storage.from(LEAD_UPLOADS_BUCKET).upload(path, input.file, {
193
- contentType: mime,
194
- // Sem upsert: não há policy de UPDATE no bucket, e o caminho carrega um
195
- // uuid novo a cada envio — sobrescrever seria sempre sinal de bug.
196
- upsert: false,
197
- })
198
- if (error) {
199
- throw new LeadSubmitError('unavailable', `Falha ao enviar o arquivo: ${error.message}`)
200
- }
201
-
202
- return { path, slot: input.slot, mime, size: input.file.size }
203
- },
204
- }
205
- }
package/src/registries.ts DELETED
@@ -1,162 +0,0 @@
1
- import type { PluginRegistryDef } from '@fayz-ai/core'
2
- import type { EntityDef } from '@fayz-ai/core'
3
- import { T } from './data/tables'
4
-
5
- const leadSourceEntity: EntityDef = {
6
- name: 'Lead Source',
7
- namePlural: 'Lead Sources',
8
- icon: 'Globe',
9
- displayField: 'name',
10
- defaultSort: 'name',
11
- fields: [
12
- { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
13
- { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true },
14
- ],
15
- data: { table: T.leadSources, tenantScoped: true },
16
- }
17
-
18
- const tagEntity: EntityDef = {
19
- name: 'Tag',
20
- namePlural: 'Tags',
21
- icon: 'Tag',
22
- displayField: 'name',
23
- defaultSort: 'name',
24
- fields: [
25
- { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
26
- // O slug é o que vive em people.tags/orders.tags — renomear a tag NÃO o
27
- // muda (o trigger só o deriva quando está vazio), e é por isso que renomear
28
- // não órfã registro. Exposto porque, quando um chip não aparece onde
29
- // deveria, a resposta está sempre aqui.
30
- { key: 'slug', label: 'Slug', type: 'text', showInTable: true },
31
- { key: 'color', label: 'Color', type: 'color', showInTable: true, defaultValue: '#6366f1' },
32
- { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true },
33
- ],
34
- data: { table: T.tags, tenantScoped: true },
35
- }
36
-
37
- const pipelineStageEntity: EntityDef = {
38
- name: 'Stage',
39
- namePlural: 'Stages',
40
- icon: 'Workflow',
41
- displayField: 'name',
42
- defaultSort: 'order',
43
- fields: [
44
- { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true, searchable: true },
45
- {
46
- key: 'pipelineId',
47
- label: 'Pipeline',
48
- type: 'relation',
49
- relation: { table: T.pipelines, labelField: 'name' },
50
- required: true,
51
- showInTable: true,
52
- },
53
- { key: 'order', label: 'Order', type: 'number', required: true, showInTable: true, defaultValue: 0 },
54
- { key: 'color', label: 'Color', type: 'color', showInTable: true, defaultValue: '#6366f1' },
55
- { key: 'probability', label: 'Probability %', type: 'number', min: 0, max: 100, showInTable: true, defaultValue: 0 },
56
- { key: 'isWon', label: 'Won Stage', type: 'boolean', showInTable: true, defaultValue: false },
57
- { key: 'isLost', label: 'Lost Stage', type: 'boolean', showInTable: true, defaultValue: false },
58
- ],
59
- data: { table: T.pipelineStages, tenantScoped: true },
60
- }
61
-
62
- const activityTypeEntity: EntityDef = {
63
- name: 'Activity Type',
64
- namePlural: 'Activity Types',
65
- icon: 'MessageCircle',
66
- displayField: 'name',
67
- defaultSort: 'name',
68
- fields: [
69
- { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
70
- { key: 'icon', label: 'Icon', type: 'text', showInTable: true },
71
- { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true, inlineToggle: true },
72
- ],
73
- data: { table: T.activityTypes, tenantScoped: true },
74
- }
75
-
76
- export const DEFAULT_ACTIVITY_TYPES: Array<{ value: string; label: string; icon?: string }> = [
77
- { value: 'call', label: 'Call', icon: 'Phone' },
78
- { value: 'email', label: 'Email', icon: 'Mail' },
79
- { value: 'meeting', label: 'Meeting', icon: 'Users' },
80
- { value: 'note', label: 'Note', icon: 'FileText' },
81
- { value: 'task', label: 'Task', icon: 'CheckSquare' },
82
- { value: 'whatsapp', label: 'WhatsApp', icon: 'MessageCircle' },
83
- ]
84
-
85
- export const crmRegistries: PluginRegistryDef[] = [
86
- {
87
- id: 'stages',
88
- entity: pipelineStageEntity,
89
- icon: 'Workflow',
90
- description: 'Pipeline stages used by CRM deals',
91
- display: 'table',
92
- seedData: [
93
- { id: 'stage-new', pipelineId: 'pipe-default', name: 'New Lead', order: 1, color: '#64748b', probability: 10, isWon: false, isLost: false },
94
- { id: 'stage-qualified', pipelineId: 'pipe-default', name: 'Qualified', order: 2, color: '#3b82f6', probability: 30, isWon: false, isLost: false },
95
- { id: 'stage-proposal', pipelineId: 'pipe-default', name: 'Proposal', order: 3, color: '#8b5cf6', probability: 60, isWon: false, isLost: false },
96
- { id: 'stage-negotiation', pipelineId: 'pipe-default', name: 'Negotiation', order: 4, color: '#f59e0b', probability: 80, isWon: false, isLost: false },
97
- { id: 'stage-won', pipelineId: 'pipe-default', name: 'Won', order: 5, color: '#10b981', probability: 100, isWon: true, isLost: false },
98
- { id: 'stage-lost', pipelineId: 'pipe-default', name: 'Lost', order: 6, color: '#ef4444', probability: 0, isWon: false, isLost: true },
99
- ],
100
- },
101
- {
102
- id: 'lead-sources',
103
- entity: leadSourceEntity,
104
- icon: 'Globe',
105
- description: 'Where your leads come from',
106
- display: 'table',
107
- seedData: [
108
- { id: 'src-instagram', name: 'Instagram', isActive: true },
109
- { id: 'src-whatsapp', name: 'WhatsApp', isActive: true },
110
- { id: 'src-referral', name: 'Referral', isActive: true },
111
- { id: 'src-google', name: 'Google', isActive: true },
112
- { id: 'src-website', name: 'Website', isActive: true },
113
- { id: 'src-walkin', name: 'Walk-in', isActive: true },
114
- ],
115
- },
116
- {
117
- id: 'tags',
118
- entity: tagEntity,
119
- icon: 'Tag',
120
- description: 'Tags for organizing leads and deals',
121
- display: 'table',
122
- // Só alimenta o provider MOCK (apps sem Supabase). Contra o banco, o
123
- // cadastro se alimenta do uso: `crm_register_tags` insere a linha quando
124
- // uma tag é gravada num lead. Semear vocabulário aqui encheria a tela de
125
- // tags que nenhum registro carrega.
126
- seedData: [
127
- { id: 'tag-vip', name: 'VIP', slug: 'vip', color: '#f59e0b', isActive: true },
128
- { id: 'tag-hot', name: 'Hot Lead', slug: 'hot-lead', color: '#ef4444', isActive: true },
129
- { id: 'tag-followup', name: 'Follow-up', slug: 'follow-up', color: '#3b82f6', isActive: true },
130
- ],
131
- },
132
- {
133
- id: 'activity-types',
134
- entity: activityTypeEntity,
135
- icon: 'MessageCircle',
136
- description: 'Types of activities and interactions',
137
- display: 'table',
138
- // Tenant-editable (the provider lazily seeds the app's set per tenant);
139
- // system timeline events (lead_created, stage_changed…) are product-defined
140
- // and never appear here.
141
- seedData: [
142
- ...DEFAULT_ACTIVITY_TYPES.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
143
- ],
144
- },
145
- ]
146
-
147
- /** Registries with the app's activity-type set replacing the default seed. */
148
- export function buildCrmRegistries(
149
- activityTypes?: Array<{ value: string; label: string; icon?: string }>,
150
- ): PluginRegistryDef[] {
151
- if (!activityTypes?.length) return crmRegistries
152
- return crmRegistries.map((registry) =>
153
- registry.id === 'activity-types'
154
- ? {
155
- ...registry,
156
- seedData: [
157
- ...activityTypes.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
158
- ],
159
- }
160
- : registry,
161
- )
162
- }