@fayz-ai/plugin-crm 0.8.5 → 0.9.0-next.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/dist/components/LeadAttachments.d.ts +8 -0
- package/dist/components/LeadAttachments.d.ts.map +1 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/index.js +244 -30
- package/dist/index.js.map +1 -1
- package/dist/lib/form-answers.d.ts +21 -0
- package/dist/lib/form-answers.d.ts.map +1 -1
- package/dist/lib/relative-time.d.ts +10 -0
- package/dist/lib/relative-time.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/migrations/index.d.ts +2 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/context.d.ts +25 -2
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +9 -0
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/data.supabase.d.ts.map +1 -1
- package/dist/public/inbox.d.ts.map +1 -1
- package/dist/public/index.d.ts +4 -2
- package/dist/public/index.d.ts.map +1 -1
- package/dist/public/index.js +150 -8
- package/dist/public/index.js.map +1 -1
- package/dist/public/types.d.ts +32 -1
- package/dist/public/types.d.ts.map +1 -1
- package/dist/public/uploads.d.ts +61 -0
- package/dist/public/uploads.d.ts.map +1 -0
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadDetailView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/package.json +6 -6
- package/src/components/LeadAttachments.tsx +140 -0
- package/src/data/supabase.ts +3 -0
- package/src/lib/form-answers.tsx +41 -0
- package/src/lib/relative-time.ts +84 -0
- package/src/locales/en.ts +1 -0
- package/src/locales/pt-BR.ts +1 -0
- package/src/migrations/015_lead_attachments.sql +357 -0
- package/src/migrations/016_public_lead_activity.sql +123 -0
- package/src/migrations/index.ts +487 -1
- package/src/public/context.tsx +85 -4
- package/src/public/createPublicFormsPlugin.ts +25 -1
- package/src/public/data.supabase.ts +5 -0
- package/src/public/inbox.ts +7 -0
- package/src/public/index.ts +22 -1
- package/src/public/types.ts +33 -1
- package/src/public/uploads.ts +205 -0
- package/src/views/ActivityListView.tsx +16 -3
- package/src/views/DealSidebar.tsx +47 -19
- package/src/views/LeadDetailView.tsx +47 -5
- package/src/views/PipelineView.tsx +13 -0
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
// Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.
|
|
10
10
|
//
|
|
11
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.
|
|
12
16
|
// ---------------------------------------------------------------------------
|
|
13
17
|
|
|
14
18
|
import { getSupabaseClientOptional } from '@fayz-ai/core'
|
|
@@ -73,6 +77,7 @@ export function createSupabasePublicLeadProvider(
|
|
|
73
77
|
p_notes: input.notes ?? null,
|
|
74
78
|
p_utm: input.attribution,
|
|
75
79
|
p_tags: input.tags ?? [],
|
|
80
|
+
p_attachments: input.attachments ?? [],
|
|
76
81
|
})
|
|
77
82
|
|
|
78
83
|
if (error) throw toSubmitError(error.message)
|
package/src/public/inbox.ts
CHANGED
|
@@ -75,6 +75,13 @@ function buildPayload(
|
|
|
75
75
|
payload[humanize(key, input.labels)] = renderValue(value)
|
|
76
76
|
}
|
|
77
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
|
+
|
|
78
85
|
const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution
|
|
79
86
|
if (utm_source) payload['Origem'] = utm_source
|
|
80
87
|
if (utm_medium) payload['Mídia'] = utm_medium
|
package/src/public/index.ts
CHANGED
|
@@ -4,26 +4,47 @@
|
|
|
4
4
|
// Headless: the site keeps its own form UI and calls useLeadForm(formId).submit
|
|
5
5
|
// with a bag of values. The SDK resolves where that goes (the tenant's CRM) and
|
|
6
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).
|
|
7
10
|
// ---------------------------------------------------------------------------
|
|
8
11
|
|
|
9
12
|
export { createPublicFormsPlugin, readAttribution } from './createPublicFormsPlugin'
|
|
10
13
|
export type { PublicFormsOptions, PublicFormsPlugin } from './createPublicFormsPlugin'
|
|
11
14
|
|
|
12
|
-
export { PublicFormsProvider, useLeadForm } from './context'
|
|
15
|
+
export { PublicFormsProvider, useLeadForm, useLeadUploads } from './context'
|
|
13
16
|
|
|
14
17
|
export { createSupabasePublicLeadProvider } from './data.supabase'
|
|
15
18
|
export type { SupabasePublicLeadOptions } from './data.supabase'
|
|
16
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
|
+
|
|
17
36
|
export { createFayzInboxNotifier } from './inbox'
|
|
18
37
|
export type { FayzInboxNotifierOptions } from './inbox'
|
|
19
38
|
|
|
20
39
|
export { LeadSubmitError } from './types'
|
|
21
40
|
export type {
|
|
41
|
+
LeadAttachment,
|
|
22
42
|
LeadAttribution,
|
|
23
43
|
LeadFieldValue,
|
|
24
44
|
LeadFields,
|
|
25
45
|
LeadNotifier,
|
|
26
46
|
LeadSubmitErrorKind,
|
|
47
|
+
LeadSubmitOptions,
|
|
27
48
|
LeadSubmitResult,
|
|
28
49
|
PublicFormDef,
|
|
29
50
|
PublicLeadDataProvider,
|
package/src/public/types.ts
CHANGED
|
@@ -9,9 +9,28 @@
|
|
|
9
9
|
|
|
10
10
|
/** What a form field may carry. Scalars and scalar lists — anything a checkbox
|
|
11
11
|
* group, a select or a text input produces. Files are out of scope: a lead
|
|
12
|
-
* form links to an upload, it does not embed one. */
|
|
12
|
+
* form links to an upload (see `LeadAttachment`), it does not embed one. */
|
|
13
13
|
export type LeadFieldValue = string | number | boolean | null | string[] | number[]
|
|
14
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
|
+
|
|
15
34
|
/** The values a site collects, keyed by field id. Free-form on purpose: a new
|
|
16
35
|
* landing page adds keys without touching the schema. */
|
|
17
36
|
export type LeadFields = Record<string, LeadFieldValue>
|
|
@@ -72,6 +91,15 @@ export interface PublicFormDef {
|
|
|
72
91
|
export interface LeadSubmitOptions {
|
|
73
92
|
/** Somadas às `tags` do formulário e às automáticas da campanha. */
|
|
74
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[]
|
|
75
103
|
}
|
|
76
104
|
|
|
77
105
|
/** Result of a submission — enough for the site to show its own success state. */
|
|
@@ -123,6 +151,8 @@ export interface PublicLeadDataProvider {
|
|
|
123
151
|
attribution: LeadAttribution
|
|
124
152
|
/** Slugs já resolvidos (curados do formulário + automáticos da campanha). */
|
|
125
153
|
tags?: string[]
|
|
154
|
+
/** Ponteiros para arquivos já no Storage. */
|
|
155
|
+
attachments?: LeadAttachment[]
|
|
126
156
|
}): Promise<{ leadId: string; createdAt: string }>
|
|
127
157
|
}
|
|
128
158
|
|
|
@@ -137,5 +167,7 @@ export interface LeadNotifier {
|
|
|
137
167
|
fields: LeadFields
|
|
138
168
|
labels?: Record<string, string>
|
|
139
169
|
attribution: LeadAttribution
|
|
170
|
+
/** Só a contagem interessa ao aviso: o inbox não serve arquivo privado. */
|
|
171
|
+
attachmentCount?: number
|
|
140
172
|
}): Promise<void>
|
|
141
173
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
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
|
+
}
|
|
@@ -3,10 +3,11 @@ import {
|
|
|
3
3
|
Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Clock, Filter, Calendar,
|
|
4
4
|
UserPlus, ArrowRightLeft, Target, MoveRight, Trophy, XCircle, FilePlus2, Send, FileCheck2, FileX2, Sparkles, ArrowRight, Archive,
|
|
5
5
|
} from 'lucide-react'
|
|
6
|
-
import { useCrmStore, useCrmProvider } from '../CrmContext'
|
|
6
|
+
import { useCrmStore, useCrmProvider, useCrmConfig } from '../CrmContext'
|
|
7
7
|
import { useTranslation } from '@fayz-ai/core'
|
|
8
8
|
import { SubpageHeader } from '@fayz-ai/ui'
|
|
9
9
|
import { DealSidebar } from './DealSidebar'
|
|
10
|
+
import { formatDateTime, formatRelativeTime } from '../lib/relative-time'
|
|
10
11
|
import { SYSTEM_ACTIVITY_TYPES, type ActivityType } from '../types'
|
|
11
12
|
|
|
12
13
|
const TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; label: string }> = {
|
|
@@ -64,6 +65,8 @@ export function ActivityListView({ onOpenLead, onOpenQuote }: {
|
|
|
64
65
|
} = {}) {
|
|
65
66
|
const t = useTranslation()
|
|
66
67
|
const provider = useCrmProvider()
|
|
68
|
+
// Mesmo idioma configurado para dinheiro — as datas não podem sair em outro.
|
|
69
|
+
const { currency } = useCrmConfig()
|
|
67
70
|
// Clicking a row opens the SAME right-hand deal sheet the pipeline uses —
|
|
68
71
|
// the timeline stays underneath instead of navigating away.
|
|
69
72
|
const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
|
|
@@ -227,8 +230,18 @@ export function ActivityListView({ onOpenLead, onOpenQuote }: {
|
|
|
227
230
|
)}
|
|
228
231
|
</div>
|
|
229
232
|
</div>
|
|
230
|
-
|
|
231
|
-
|
|
233
|
+
{/* Quando aconteceu. A lista mostrava só o dia, e numa linha do
|
|
234
|
+
tempo o horário é metade da informação — "chegou hoje" não
|
|
235
|
+
diz se foi antes ou depois da última ligação. Idade em
|
|
236
|
+
destaque (é como se lê uma timeline), data e hora embaixo. */}
|
|
237
|
+
<span
|
|
238
|
+
className="flex items-center gap-1.5 text-[10px] text-muted-foreground shrink-0 pt-1"
|
|
239
|
+
title={formatDateTime(a.createdAt, currency.locale)}
|
|
240
|
+
>
|
|
241
|
+
<span className="text-right leading-tight">
|
|
242
|
+
<span className="block">{formatRelativeTime(a.createdAt, currency.locale)}</span>
|
|
243
|
+
<span className="block opacity-70">{formatDateTime(a.createdAt, currency.locale)}</span>
|
|
244
|
+
</span>
|
|
232
245
|
{openRecord && (
|
|
233
246
|
<ArrowRight className="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" />
|
|
234
247
|
)}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import React, { useEffect, useState } from 'react'
|
|
2
2
|
import { Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Calendar, DollarSign, User, Target, Clock, ArrowRight, UserPlus, ArrowRightLeft, MoveRight, Trophy, XCircle, FilePlus2, Send, FileCheck2, FileX2, Archive } from 'lucide-react'
|
|
3
3
|
import { useTranslation } from '@fayz-ai/core'
|
|
4
|
-
import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription, SegmentedControl } from '@fayz-ai/ui'
|
|
4
|
+
import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription, SegmentedControl, PhoneLink, normalizePhone } from '@fayz-ai/ui'
|
|
5
5
|
import { PersonLink } from '@fayz-ai/saas'
|
|
6
6
|
import { useCrmProvider, useCrmConfig, useCrmStore, formatCurrency } from '../CrmContext'
|
|
7
7
|
import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
|
|
8
8
|
import { TagChips } from '../components/TagChips'
|
|
9
|
-
import { answerEntries, humanizeKey, renderFieldValue } from '../lib/form-answers'
|
|
9
|
+
import { answerEntries, humanizeKey, leadAttachments, renderFieldValue } from '../lib/form-answers'
|
|
10
|
+
import { LeadAttachments } from '../components/LeadAttachments'
|
|
11
|
+
import { formatDateTime, formatRelativeTime } from '../lib/relative-time'
|
|
10
12
|
import type { Deal, Lead, Quote, Activity } from '../types'
|
|
11
13
|
|
|
12
14
|
// ---------------------------------------------------------------------------
|
|
@@ -69,24 +71,32 @@ function TabBar({ active, counts, onChange }: { active: TabId; counts: { activit
|
|
|
69
71
|
function FormAnswers({ lead }: { lead: Lead | null }) {
|
|
70
72
|
const t = useTranslation()
|
|
71
73
|
const entries = answerEntries(lead?.metadata?.fields)
|
|
72
|
-
|
|
74
|
+
const attachments = leadAttachments(lead?.metadata)
|
|
75
|
+
if (entries.length === 0 && attachments.length === 0) return null
|
|
73
76
|
|
|
74
77
|
const formId = lead?.metadata?.formId
|
|
75
78
|
return (
|
|
76
|
-
<div className="space-y-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
<div
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
79
|
+
<div className="space-y-3">
|
|
80
|
+
{entries.length > 0 && (
|
|
81
|
+
<div className="space-y-2">
|
|
82
|
+
<h4 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
|
|
83
|
+
{formId ? `${t('crm.leadDetail.formAnswers')} · ${formId}` : t('crm.leadDetail.formAnswers')}
|
|
84
|
+
</h4>
|
|
85
|
+
<div className="rounded-xl border divide-y">
|
|
86
|
+
{entries.map(([key, value]) => (
|
|
87
|
+
<div key={key} className="flex items-start gap-3 px-4 py-2.5">
|
|
88
|
+
<span className="text-[11px] text-muted-foreground shrink-0 min-w-24">{humanizeKey(key)}</span>
|
|
89
|
+
<span className="text-xs text-right flex-1 break-words">
|
|
90
|
+
{renderFieldValue(value) ?? <span className="text-muted-foreground/50">—</span>}
|
|
91
|
+
</span>
|
|
92
|
+
</div>
|
|
93
|
+
))}
|
|
87
94
|
</div>
|
|
88
|
-
|
|
89
|
-
|
|
95
|
+
</div>
|
|
96
|
+
)}
|
|
97
|
+
{/* As fotos vêm DEPOIS das respostas: quem abre o card lê primeiro quem é
|
|
98
|
+
a pessoa e o que ela pediu, e só então olha o material que ela mandou. */}
|
|
99
|
+
<LeadAttachments attachments={attachments} variant="compact" />
|
|
90
100
|
</div>
|
|
91
101
|
)
|
|
92
102
|
}
|
|
@@ -158,6 +168,20 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
|
|
|
158
168
|
<span className="text-xs font-medium">{deal.assignedToName}</span>
|
|
159
169
|
</div>
|
|
160
170
|
)}
|
|
171
|
+
{/* Quando entrou. Data e hora com a idade ao lado — o card mostra só o
|
|
172
|
+
relativo, e é aqui que se confere o horário exato antes de ligar. */}
|
|
173
|
+
{deal.createdAt && (
|
|
174
|
+
<div className="flex items-center gap-3 px-4 py-3">
|
|
175
|
+
<Clock className="h-4 w-4 text-muted-foreground shrink-0" />
|
|
176
|
+
<span className="text-xs text-muted-foreground flex-1">{t('crm.dealSidebar.created')}</span>
|
|
177
|
+
<span className="text-xs font-medium text-right">
|
|
178
|
+
{formatDateTime(deal.createdAt, currency.locale)}
|
|
179
|
+
<span className="ml-1.5 text-muted-foreground">
|
|
180
|
+
({formatRelativeTime(deal.createdAt, currency.locale)})
|
|
181
|
+
</span>
|
|
182
|
+
</span>
|
|
183
|
+
</div>
|
|
184
|
+
)}
|
|
161
185
|
</div>
|
|
162
186
|
|
|
163
187
|
{/* Contact links */}
|
|
@@ -171,9 +195,13 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
|
|
|
171
195
|
</a>
|
|
172
196
|
)}
|
|
173
197
|
{lead.phone && (
|
|
174
|
-
<
|
|
175
|
-
|
|
176
|
-
|
|
198
|
+
<PhoneLink
|
|
199
|
+
phone={lead.phone}
|
|
200
|
+
className="flex items-center gap-3 px-4 py-2.5 text-xs text-primary hover:bg-muted/30 transition-colors hover:no-underline"
|
|
201
|
+
>
|
|
202
|
+
<MessageCircle className="h-3.5 w-3.5 shrink-0" />
|
|
203
|
+
<span>{normalizePhone(lead.phone).display}</span>
|
|
204
|
+
</PhoneLink>
|
|
177
205
|
)}
|
|
178
206
|
</div>
|
|
179
207
|
</div>
|
|
@@ -4,7 +4,10 @@ import { useCrmProvider, useCrmConfig, formatCurrency, useCrmStore } from '../Cr
|
|
|
4
4
|
import { useCanArchive } from '../lib/access'
|
|
5
5
|
import { useTranslation } from '@fayz-ai/core'
|
|
6
6
|
import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
|
|
7
|
-
import {
|
|
7
|
+
import { LeadAttachments } from '../components/LeadAttachments'
|
|
8
|
+
import { leadAttachments } from '../lib/form-answers'
|
|
9
|
+
import { formatDateTime, formatRelativeTime } from '../lib/relative-time'
|
|
10
|
+
import { Breadcrumb, PhoneLink } from '@fayz-ai/ui'
|
|
8
11
|
import type { Lead, Deal, Quote } from '../types'
|
|
9
12
|
|
|
10
13
|
const STATUS_COLORS: Record<string, string> = {
|
|
@@ -49,6 +52,9 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
|
|
|
49
52
|
}) {
|
|
50
53
|
const provider = useCrmProvider()
|
|
51
54
|
const { currency } = useCrmConfig()
|
|
55
|
+
// Mesmo idioma do dinheiro: quem configurou pt-BR para o valor não quer
|
|
56
|
+
// "2 days ago" na data ao lado.
|
|
57
|
+
const locale = currency.locale
|
|
52
58
|
const t = useTranslation()
|
|
53
59
|
const archiveLead = useCrmStore((s) => s.archiveLead)
|
|
54
60
|
const canArchive = useCanArchive()
|
|
@@ -181,7 +187,10 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
|
|
|
181
187
|
<FieldRow label={t('crm.leadDetail.email')} value={lead.email ? <a href={`mailto:${lead.email}`} className="text-primary hover:underline">{lead.email}</a> : null} />
|
|
182
188
|
</div>
|
|
183
189
|
<div className="px-5 md:border-b">
|
|
184
|
-
<FieldRow
|
|
190
|
+
<FieldRow
|
|
191
|
+
label={t('crm.leadDetail.phone')}
|
|
192
|
+
value={lead.phone ? <PhoneLink phone={lead.phone} className="text-primary" /> : null}
|
|
193
|
+
/>
|
|
185
194
|
</div>
|
|
186
195
|
<div className="px-5 md:border-b md:last:border-b-0">
|
|
187
196
|
<FieldRow label={t('crm.leadDetail.company')} value={lead.company} />
|
|
@@ -202,7 +211,8 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
|
|
|
202
211
|
}
|
|
203
212
|
const fields = Object.entries(meta.fields ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
|
|
204
213
|
const utm = Object.entries(meta.utm ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
|
|
205
|
-
|
|
214
|
+
const attachments = leadAttachments(lead.metadata)
|
|
215
|
+
if (!fields.length && !utm.length && !attachments.length) return null
|
|
206
216
|
return (
|
|
207
217
|
<div>
|
|
208
218
|
<h3 className="text-sm font-semibold text-foreground mb-1">
|
|
@@ -216,6 +226,11 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
|
|
|
216
226
|
</div>
|
|
217
227
|
))}
|
|
218
228
|
</dl>
|
|
229
|
+
{attachments.length > 0 && (
|
|
230
|
+
<div className="border-t px-5 py-3">
|
|
231
|
+
<LeadAttachments attachments={attachments} />
|
|
232
|
+
</div>
|
|
233
|
+
)}
|
|
219
234
|
{utm.length > 0 && (
|
|
220
235
|
<div className="border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1">
|
|
221
236
|
{utm.map(([key, value]) => (
|
|
@@ -298,11 +313,38 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
|
|
|
298
313
|
<div className="px-5 md:border-b">
|
|
299
314
|
<FieldRow label={t('crm.leadDetail.assignedTo')} value={lead.assignedToName} />
|
|
300
315
|
</div>
|
|
316
|
+
{/* Data e hora completas, com a idade ao lado. `slice(0,10)` mostrava
|
|
317
|
+
só o dia — e num lead que chegou hoje de manhã, saber se foi às
|
|
318
|
+
8h ou às 18h é o que decide se ainda dá para ligar hoje. */}
|
|
301
319
|
<div className="px-5 md:border-b md:last:border-b-0">
|
|
302
|
-
<FieldRow
|
|
320
|
+
<FieldRow
|
|
321
|
+
label={t('crm.leadDetail.created')}
|
|
322
|
+
value={
|
|
323
|
+
lead.createdAt ? (
|
|
324
|
+
<span className="inline-flex flex-wrap items-baseline gap-x-1.5">
|
|
325
|
+
<span>{formatDateTime(lead.createdAt, locale)}</span>
|
|
326
|
+
<span className="text-xs text-muted-foreground">
|
|
327
|
+
({formatRelativeTime(lead.createdAt, locale)})
|
|
328
|
+
</span>
|
|
329
|
+
</span>
|
|
330
|
+
) : null
|
|
331
|
+
}
|
|
332
|
+
/>
|
|
303
333
|
</div>
|
|
304
334
|
<div className="px-5 md:border-b md:last:border-b-0">
|
|
305
|
-
<FieldRow
|
|
335
|
+
<FieldRow
|
|
336
|
+
label={t('crm.leadDetail.updated')}
|
|
337
|
+
value={
|
|
338
|
+
lead.updatedAt ? (
|
|
339
|
+
<span className="inline-flex flex-wrap items-baseline gap-x-1.5">
|
|
340
|
+
<span>{formatDateTime(lead.updatedAt, locale)}</span>
|
|
341
|
+
<span className="text-xs text-muted-foreground">
|
|
342
|
+
({formatRelativeTime(lead.updatedAt, locale)})
|
|
343
|
+
</span>
|
|
344
|
+
</span>
|
|
345
|
+
) : null
|
|
346
|
+
}
|
|
347
|
+
/>
|
|
306
348
|
</div>
|
|
307
349
|
</dl>
|
|
308
350
|
</div>
|
|
@@ -8,6 +8,7 @@ import { SubpageHeader } from '@fayz-ai/ui'
|
|
|
8
8
|
import { DealSidebar } from './DealSidebar'
|
|
9
9
|
import { TagChips } from '../components/TagChips'
|
|
10
10
|
import { BoardFilters, periodToRange } from '../components/BoardFilters'
|
|
11
|
+
import { formatDateTime, formatRelativeTime } from '../lib/relative-time'
|
|
11
12
|
import type { BoardPeriod, Deal, TagDef } from '../types'
|
|
12
13
|
|
|
13
14
|
/** Uma data em YYYY-MM-DD, no fuso de quem está olhando (o DatePicker fala isso). */
|
|
@@ -95,6 +96,18 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
|
|
|
95
96
|
<span className="text-xs font-semibold">{formatCurrency(deal.value, currency)}</span>
|
|
96
97
|
<span className="text-[10px] text-muted-foreground">{deal.probability}%</span>
|
|
97
98
|
</div>
|
|
99
|
+
{/* Idade do card. Sem ela, "parado há três semanas" e "chegou agora" são
|
|
100
|
+
visualmente idênticos — e é essa diferença que decide quem recebe o
|
|
101
|
+
próximo telefonema. A data exata fica no `title`, para quem precisar
|
|
102
|
+
dela sem abrir o card. */}
|
|
103
|
+
{deal.createdAt && (
|
|
104
|
+
<p
|
|
105
|
+
className="mt-1 text-[10px] text-muted-foreground"
|
|
106
|
+
title={formatDateTime(deal.createdAt, currency.locale)}
|
|
107
|
+
>
|
|
108
|
+
{formatRelativeTime(deal.createdAt, currency.locale)}
|
|
109
|
+
</p>
|
|
110
|
+
)}
|
|
98
111
|
</div>
|
|
99
112
|
)
|
|
100
113
|
}
|