Compare commits
7 Commits
b7ff3fe430
...
009466ac18
| Author | SHA1 | Date | |
|---|---|---|---|
| 009466ac18 | |||
| 9f5a6dcbe5 | |||
| b96b6a2083 | |||
| a46e8b0bc8 | |||
| 70a101ca98 | |||
| dc934fb04a | |||
| 3e10f97215 |
@@ -190,7 +190,12 @@ Plans:
|
|||||||
1. Esiste uno schema additivo `client_transcripts` (lead_id/client_id, testo, data, titolo/tipo, created_at)
|
1. Esiste uno schema additivo `client_transcripts` (lead_id/client_id, testo, data, titolo/tipo, created_at)
|
||||||
2. L'admin incolla un transcript con data dal dettaglio lead/cliente
|
2. L'admin incolla un transcript con data dal dettaglio lead/cliente
|
||||||
3. I transcript sono elencati in ordine cronologico nel profilo
|
3. I transcript sono elencati in ordine cronologico nel profilo
|
||||||
**Status**: Pending planning — `/gsd-plan-phase 20`
|
**Plans:** 3 plans
|
||||||
|
Plans:
|
||||||
|
- [ ] 20-01-PLAN.md — Migration SQL 0009_client_transcripts (BLOCKING checkpoint prod)
|
||||||
|
- [ ] 20-02-PLAN.md — Schema Drizzle + getTranscripts + addTranscript/deleteTranscript actions
|
||||||
|
- [ ] 20-03-PLAN.md — TranscriptModal + sezione LeadDetail + wiring page.tsx
|
||||||
|
**Status**: Planned (2026-06-19) — ready for `/gsd-execute-phase 20`
|
||||||
|
|
||||||
### Phase 21: Agente AI — generazione preventivo
|
### Phase 21: Agente AI — generazione preventivo
|
||||||
**Goal**: L'admin seleziona cliente + offerta; l'agente AI (Claude) legge i transcript + i dati dell'offerta e genera una bozza di preventivo personalizzata, che l'admin può rivedere ed editare.
|
**Goal**: L'admin seleziona cliente + offerta; l'agente AI (Claude) legge i transcript + i dati dell'offerta e genera una bozza di preventivo personalizzata, che l'admin può rivedere ed editare.
|
||||||
@@ -228,6 +233,6 @@ Plans:
|
|||||||
| 17. Proposal AI — Builder, Pagina Pubblica & Email | — | ❌ Ri-scopata (v2.2) | — |
|
| 17. Proposal AI — Builder, Pagina Pubblica & Email | — | ❌ Ri-scopata (v2.2) | — |
|
||||||
| 18 (R1). Cleanup & Consolidamento | 3/3 | ✅ Done | 2026-06-19 |
|
| 18 (R1). Cleanup & Consolidamento | 3/3 | ✅ Done | 2026-06-19 |
|
||||||
| 19 (R2). Pipeline CRM Kanban | 1/1 | ✅ Done | 2026-06-19 |
|
| 19 (R2). Pipeline CRM Kanban | 1/1 | ✅ Done | 2026-06-19 |
|
||||||
| 20 (R3). Knowledge Base Cliente (transcript) | — | Pending planning | — |
|
| 20 (R3). Knowledge Base Cliente (transcript) | 3 plans | Planned (2026-06-19) | — |
|
||||||
| 21 (R4). Agente AI — generazione preventivo | — | Pending planning | — |
|
| 21 (R4). Agente AI — generazione preventivo | — | Pending planning | — |
|
||||||
| 22 (R5). Pagina pubblica preventivo + email | — | Pending planning | — |
|
| 22 (R5). Pagina pubblica preventivo + email | — | Pending planning | — |
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: 01
|
||||||
|
type: execute
|
||||||
|
wave: 1
|
||||||
|
depends_on: []
|
||||||
|
files_modified:
|
||||||
|
- src/db/migrations/0009_client_transcripts.sql
|
||||||
|
autonomous: false
|
||||||
|
requirements:
|
||||||
|
- KB-01
|
||||||
|
must_haves:
|
||||||
|
truths:
|
||||||
|
- "Il file 0009_client_transcripts.sql esiste con DDL completo e idempotente"
|
||||||
|
- "La tabella client_transcripts è presente nel database di produzione"
|
||||||
|
- "Il codice schema-dipendente dei piani successivi non viene pushato prima che la migration sia applicata"
|
||||||
|
artifacts:
|
||||||
|
- path: "src/db/migrations/0009_client_transcripts.sql"
|
||||||
|
provides: "DDL CREATE TABLE IF NOT EXISTS client_transcripts con tutti i campi D-01/D-02"
|
||||||
|
contains: "CREATE TABLE IF NOT EXISTS client_transcripts"
|
||||||
|
key_links:
|
||||||
|
- from: "src/db/migrations/0009_client_transcripts.sql"
|
||||||
|
to: "database produzione"
|
||||||
|
via: "SSH tunnel + psql/docker exec"
|
||||||
|
pattern: "CREATE TABLE IF NOT EXISTS client_transcripts"
|
||||||
|
---
|
||||||
|
|
||||||
|
<objective>
|
||||||
|
Scrivere il file SQL della migration manuale per la tabella `client_transcripts` e applicarlo al database di produzione prima di pushare qualsiasi codice schema-dipendente.
|
||||||
|
|
||||||
|
Purpose: Il progetto ha `drizzle-kit generate` rotto (meta-snapshot fuori sync). Ogni schema change richiede SQL a mano applicato a prod via SSH PRIMA del codice dipendente — invariante bloccante LOCKED in CLAUDE.md.
|
||||||
|
|
||||||
|
Output: `src/db/migrations/0009_client_transcripts.sql` applicato a prod. Il checkpoint umano sblocca i piani 20-02 e 20-03.
|
||||||
|
</objective>
|
||||||
|
|
||||||
|
<execution_context>
|
||||||
|
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
|
||||||
|
@$HOME/.claude/get-shit-done/templates/summary.md
|
||||||
|
</execution_context>
|
||||||
|
|
||||||
|
<context>
|
||||||
|
@.planning/ROADMAP.md
|
||||||
|
@.planning/phases/20-knowledge-base-cliente/20-CONTEXT.md
|
||||||
|
|
||||||
|
<interfaces>
|
||||||
|
<!-- Pattern migration a mano — da src/db/migrations/0005 e 0008 -->
|
||||||
|
<!-- Convenzioni: CREATE TABLE IF NOT EXISTS, tipi Postgres espliciti, FK con ON DELETE CASCADE -->
|
||||||
|
<!-- nanoid PK: text NOT NULL — il valore viene inserito dall'applicazione, non da DEFAULT -->
|
||||||
|
<!-- Struttura 0008: header commento, istruzioni additive, CREATE INDEX IF NOT EXISTS -->
|
||||||
|
|
||||||
|
Da 0005_phase_10_crm_leads_activities_reminders.sql:
|
||||||
|
```sql
|
||||||
|
CREATE TABLE IF NOT EXISTS "activities" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"lead_id" text NOT NULL,
|
||||||
|
...
|
||||||
|
FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE cascade
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS "activities_lead_id" ON "activities"("lead_id");
|
||||||
|
```
|
||||||
|
|
||||||
|
Da 0008_offer_tier_schema.sql (header):
|
||||||
|
```sql
|
||||||
|
-- Phase 12: Offer Editor — additive schema ...
|
||||||
|
-- All statements additive/idempotent. No drops/truncates (Data Safety LOCKED).
|
||||||
|
```
|
||||||
|
</interfaces>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<tasks>
|
||||||
|
|
||||||
|
<task type="auto">
|
||||||
|
<name>Task 1: Scrivere src/db/migrations/0009_client_transcripts.sql</name>
|
||||||
|
<files>src/db/migrations/0009_client_transcripts.sql</files>
|
||||||
|
<read_first>
|
||||||
|
- src/db/migrations/0008_offer_tier_schema.sql (pattern header + CREATE TABLE IF NOT EXISTS)
|
||||||
|
- src/db/migrations/0005_phase_10_crm_leads_activities_reminders.sql (pattern FK + index per tabelle CRM)
|
||||||
|
- .planning/phases/20-knowledge-base-cliente/20-CONTEXT.md (D-01 e D-02 — campi esatti)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
Creare il file `src/db/migrations/0009_client_transcripts.sql` con il seguente contenuto esatto:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- Phase 20: Knowledge Base Cliente — tabella transcript datati per lead/cliente
|
||||||
|
-- Additive only. No drops/truncates (Data Safety LOCKED).
|
||||||
|
-- Applicare a prod via SSH tunnel PRIMA di pushare il codice dipendente (D-03).
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS client_transcripts (
|
||||||
|
id text PRIMARY KEY NOT NULL,
|
||||||
|
lead_id text REFERENCES leads(id) ON DELETE CASCADE,
|
||||||
|
client_id text REFERENCES clients(id) ON DELETE CASCADE,
|
||||||
|
title text,
|
||||||
|
content text NOT NULL,
|
||||||
|
call_date date NOT NULL,
|
||||||
|
created_at timestamp with time zone NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_lead_id_idx
|
||||||
|
ON client_transcripts (lead_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_client_id_idx
|
||||||
|
ON client_transcripts (client_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_call_date_idx
|
||||||
|
ON client_transcripts (call_date DESC);
|
||||||
|
```
|
||||||
|
|
||||||
|
Note sui campi (da D-01/D-02):
|
||||||
|
- `id`: text PK NOT NULL — nanoid inserito dall'app, nessun DEFAULT SQL (pattern progetto)
|
||||||
|
- `lead_id`: nullable FK → leads(id) ON DELETE CASCADE (D-01)
|
||||||
|
- `client_id`: nullable FK → clients(id) ON DELETE CASCADE (D-01)
|
||||||
|
- `title`: text nullable (D-02) — titolo libero opzionale
|
||||||
|
- `content`: text NOT NULL (D-02) — testo grezzo illimitato
|
||||||
|
- `call_date`: date NOT NULL (D-02) — giorno della call, non timestamp
|
||||||
|
- `created_at`: timestamp with time zone NOT NULL DEFAULT now() (D-02)
|
||||||
|
|
||||||
|
Gli indici su lead_id, client_id e call_date ottimizzano le query per lead (Phase 20) e future query per client_id (Phase 21+).
|
||||||
|
</action>
|
||||||
|
<verify>
|
||||||
|
<automated>grep -c "CREATE TABLE IF NOT EXISTS client_transcripts" /Users/simonecavalli/Vault/IAMCAVALLI/src/db/migrations/0009_client_transcripts.sql</automated>
|
||||||
|
</verify>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- File `src/db/migrations/0009_client_transcripts.sql` esiste
|
||||||
|
- Contiene `CREATE TABLE IF NOT EXISTS client_transcripts`
|
||||||
|
- Contiene `lead_id text REFERENCES leads(id) ON DELETE CASCADE`
|
||||||
|
- Contiene `client_id text REFERENCES clients(id) ON DELETE CASCADE`
|
||||||
|
- Contiene `content text NOT NULL`
|
||||||
|
- Contiene `call_date date NOT NULL`
|
||||||
|
- Contiene `created_at timestamp with time zone NOT NULL DEFAULT now()`
|
||||||
|
- Contiene 3 `CREATE INDEX IF NOT EXISTS` (lead_id_idx, client_id_idx, call_date_idx)
|
||||||
|
- Nessun DROP o TRUNCATE nel file
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>File SQL completo e idempotente scritto, pronto per applicazione a prod.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
<task type="checkpoint:human-action" gate="blocking">
|
||||||
|
<name>Task 2: [BLOCKING] Applicare migration 0009 al database di produzione via SSH</name>
|
||||||
|
<read_first>
|
||||||
|
- src/db/migrations/0009_client_transcripts.sql (verificare il contenuto prima di applicare)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
La migration va applicata a prod via SSH tunnel PRIMA di eseguire i piani 20-02 e 20-03. Il database di produzione è accessibile solo tramite tunnel SSH.
|
||||||
|
|
||||||
|
**Passi:**
|
||||||
|
|
||||||
|
1. Aprire un terminale locale e avviare il tunnel SSH:
|
||||||
|
```bash
|
||||||
|
ssh -L 54321:localhost:54321 root@178.104.27.55
|
||||||
|
```
|
||||||
|
Lasciare questo terminale aperto per tutta la durata.
|
||||||
|
|
||||||
|
2. In un altro terminale, applicare la migration con psql (il DATABASE_URL del progetto punta a 127.0.0.1:54321):
|
||||||
|
```bash
|
||||||
|
cd /Users/simonecavalli/Vault/IAMCAVALLI
|
||||||
|
psql "$(grep DATABASE_URL .env.local | cut -d= -f2-)" -f src/db/migrations/0009_client_transcripts.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
Oppure, se il DATABASE_URL non funziona direttamente, applicare via docker exec sul server:
|
||||||
|
```bash
|
||||||
|
# Sul server (nella sessione SSH aperta al punto 1):
|
||||||
|
docker exec -i <nome_container_postgres> psql -U <db_user> -d <db_name> < /path/to/0009_client_transcripts.sql
|
||||||
|
```
|
||||||
|
(Il nome del container e le credenziali sono in `.env.local` o nei secret Coolify.)
|
||||||
|
|
||||||
|
3. Verificare che la tabella esista:
|
||||||
|
```bash
|
||||||
|
psql "$(grep DATABASE_URL .env.local | cut -d= -f2-)" -c "\d client_transcripts"
|
||||||
|
```
|
||||||
|
Deve mostrare le colonne: id, lead_id, client_id, title, content, call_date, created_at.
|
||||||
|
|
||||||
|
4. Chiudere il tunnel SSH solo dopo aver verificato il punto 3.
|
||||||
|
</action>
|
||||||
|
<what-built>Il file SQL 0009_client_transcripts.sql è stato scritto da Claude nel Task 1. Questo task richiede solo che tu applichi la migration a prod — nessun codice da scrivere.</what-built>
|
||||||
|
<how-to-verify>
|
||||||
|
Eseguire in locale (con tunnel attivo):
|
||||||
|
```bash
|
||||||
|
psql "$(grep DATABASE_URL .env.local | cut -d= -f2-)" -c "SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_name = 'client_transcripts' ORDER BY ordinal_position;"
|
||||||
|
```
|
||||||
|
Risultato atteso: 7 righe con le colonne id, lead_id, client_id, title, content, call_date, created_at.
|
||||||
|
</how-to-verify>
|
||||||
|
<resume-signal>Digita "migration applicata" dopo aver verificato che \d client_transcripts mostra le 7 colonne attese.</resume-signal>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- La tabella `client_transcripts` esiste nel database di produzione
|
||||||
|
- `\d client_transcripts` mostra 7 colonne: id (text), lead_id (text, nullable), client_id (text, nullable), title (text, nullable), content (text, NOT NULL), call_date (date, NOT NULL), created_at (timestamptz, NOT NULL)
|
||||||
|
- 3 indici presenti: client_transcripts_lead_id_idx, client_transcripts_client_id_idx, client_transcripts_call_date_idx
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>Database di produzione aggiornato con la tabella client_transcripts. I piani 20-02 e 20-03 sono sbloccati.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
</tasks>
|
||||||
|
|
||||||
|
<threat_model>
|
||||||
|
## Trust Boundaries
|
||||||
|
|
||||||
|
| Boundary | Descrizione |
|
||||||
|
|----------|-------------|
|
||||||
|
| developer → database prod | SQL applicato manualmente via SSH tunnel autenticato |
|
||||||
|
|
||||||
|
## STRIDE Threat Register
|
||||||
|
|
||||||
|
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|
||||||
|
|-----------|----------|-----------|-------------|-----------------|
|
||||||
|
| T-20-01 | Tampering | 0009_client_transcripts.sql | mitigate | Revisione manuale del contenuto prima dell'applicazione (Task 2 step 1); file in version control |
|
||||||
|
| T-20-02 | Repudiation | Applicazione migration prod | accept | L'operazione è tracciata nel git commit di questo piano; nessun audit log applicativo necessario per DDL |
|
||||||
|
| T-20-03 | Denial of Service | DROP/TRUNCATE accidentale | mitigate | Il file usa solo CREATE TABLE IF NOT EXISTS + CREATE INDEX IF NOT EXISTS; nessuna istruzione distruttiva presente |
|
||||||
|
</threat_model>
|
||||||
|
|
||||||
|
<verification>
|
||||||
|
```bash
|
||||||
|
# Verificare che il file SQL esista e contenga i campi obbligatori
|
||||||
|
grep -E "CREATE TABLE IF NOT EXISTS client_transcripts|content.*text NOT NULL|call_date.*date NOT NULL|lead_id.*REFERENCES leads|client_id.*REFERENCES clients" \
|
||||||
|
/Users/simonecavalli/Vault/IAMCAVALLI/src/db/migrations/0009_client_transcripts.sql
|
||||||
|
|
||||||
|
# Verificare assenza di istruzioni distruttive
|
||||||
|
grep -i "drop\|truncate" /Users/simonecavalli/Vault/IAMCAVALLI/src/db/migrations/0009_client_transcripts.sql | wc -l
|
||||||
|
# Atteso: 0
|
||||||
|
```
|
||||||
|
</verification>
|
||||||
|
|
||||||
|
<success_criteria>
|
||||||
|
- `src/db/migrations/0009_client_transcripts.sql` esiste con DDL completo e idempotente (KB-01)
|
||||||
|
- La tabella `client_transcripts` è presente nel database di produzione con le 7 colonne di D-02
|
||||||
|
- Nessuna istruzione distruttiva nel file SQL
|
||||||
|
- Il checkpoint umano è stato completato e segnalato con "migration applicata"
|
||||||
|
</success_criteria>
|
||||||
|
|
||||||
|
<output>
|
||||||
|
Dopo il completamento del Task 2, creare `.planning/phases/20-knowledge-base-cliente/20-01-SUMMARY.md` con:
|
||||||
|
- Migration file creato: `src/db/migrations/0009_client_transcripts.sql`
|
||||||
|
- Migration applicata a prod: sì/no
|
||||||
|
- Colonne verificate: lista delle 7 colonne confermate
|
||||||
|
</output>
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: "01"
|
||||||
|
status: complete
|
||||||
|
completed_at: "2026-06-20"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan 20-01 Summary: Migration client_transcripts
|
||||||
|
|
||||||
|
## What Was Built
|
||||||
|
|
||||||
|
Migration file `src/db/migrations/0009_client_transcripts.sql` scritto e applicato a produzione.
|
||||||
|
|
||||||
|
## Key Files
|
||||||
|
|
||||||
|
### Created
|
||||||
|
- `src/db/migrations/0009_client_transcripts.sql` — DDL completo e idempotente
|
||||||
|
|
||||||
|
## Migration Applied to Production
|
||||||
|
|
||||||
|
- **Metodo:** SSH tunnel (127.0.0.1:54321) + Node.js postgres client
|
||||||
|
- **Risultato:** ✓ applicata senza errori
|
||||||
|
|
||||||
|
## Colonne Verificate (7/7)
|
||||||
|
|
||||||
|
| column_name | data_type | nullable |
|
||||||
|
|-------------|--------------------------|----------|
|
||||||
|
| id | text | NO |
|
||||||
|
| lead_id | text | YES |
|
||||||
|
| client_id | text | YES |
|
||||||
|
| title | text | YES |
|
||||||
|
| content | text | NO |
|
||||||
|
| call_date | date | NO |
|
||||||
|
| created_at | timestamp with time zone | NO |
|
||||||
|
|
||||||
|
## Self-Check: PASSED
|
||||||
|
|
||||||
|
- ✓ File SQL esiste con DDL completo e idempotente
|
||||||
|
- ✓ Tabella `client_transcripts` presente nel database di produzione
|
||||||
|
- ✓ 7 colonne verificate (D-01/D-02)
|
||||||
|
- ✓ Nessun DROP/TRUNCATE nel file
|
||||||
|
- ✓ 3 indici creati (lead_id_idx, client_id_idx, call_date_idx)
|
||||||
@@ -0,0 +1,401 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: 02
|
||||||
|
type: execute
|
||||||
|
wave: 2
|
||||||
|
depends_on:
|
||||||
|
- 20-01
|
||||||
|
files_modified:
|
||||||
|
- src/db/schema.ts
|
||||||
|
- src/lib/lead-service.ts
|
||||||
|
- src/app/admin/leads/actions.ts
|
||||||
|
autonomous: true
|
||||||
|
requirements:
|
||||||
|
- KB-01
|
||||||
|
- KB-02
|
||||||
|
must_haves:
|
||||||
|
truths:
|
||||||
|
- "La tabella clientTranscripts è definita in schema.ts con le relazioni Drizzle corrette"
|
||||||
|
- "getTranscripts(leadId) restituisce i transcript in ordine call_date DESC"
|
||||||
|
- "addTranscript e deleteTranscript sono server actions con requireAdmin guard"
|
||||||
|
artifacts:
|
||||||
|
- path: "src/db/schema.ts"
|
||||||
|
provides: "Definizione tabella clientTranscripts + relazioni Drizzle per leads e clients"
|
||||||
|
contains: "export const clientTranscripts = pgTable"
|
||||||
|
- path: "src/lib/lead-service.ts"
|
||||||
|
provides: "Query getTranscripts(leadId) — tutti i campi incluso content completo"
|
||||||
|
exports: ["getTranscripts"]
|
||||||
|
- path: "src/app/admin/leads/actions.ts"
|
||||||
|
provides: "Server actions addTranscript e deleteTranscript con requireAdmin"
|
||||||
|
exports: ["addTranscript", "deleteTranscript"]
|
||||||
|
key_links:
|
||||||
|
- from: "src/app/admin/leads/actions.ts"
|
||||||
|
to: "src/db/schema.ts"
|
||||||
|
via: "import clientTranscripts"
|
||||||
|
pattern: "clientTranscripts"
|
||||||
|
- from: "src/lib/lead-service.ts"
|
||||||
|
to: "src/db/schema.ts"
|
||||||
|
via: "import clientTranscripts"
|
||||||
|
pattern: "getTranscripts"
|
||||||
|
---
|
||||||
|
|
||||||
|
<objective>
|
||||||
|
Aggiungere la definizione Drizzle della tabella `clientTranscripts` in schema.ts, la query `getTranscripts` in lead-service.ts e le server actions `addTranscript` / `deleteTranscript` in actions.ts.
|
||||||
|
|
||||||
|
Purpose: Fornisce il layer dati completo per la UI del piano 20-03. Phase 21 (AI) leggerà i transcript via `getTranscripts(leadId)` — la firma deve restituire tutti i campi incluso `content` completo.
|
||||||
|
|
||||||
|
Output: Schema Drizzle + query + actions pronte, build TypeScript senza errori.
|
||||||
|
</objective>
|
||||||
|
|
||||||
|
<execution_context>
|
||||||
|
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
|
||||||
|
@$HOME/.claude/get-shit-done/templates/summary.md
|
||||||
|
</execution_context>
|
||||||
|
|
||||||
|
<context>
|
||||||
|
@.planning/phases/20-knowledge-base-cliente/20-CONTEXT.md
|
||||||
|
@.planning/phases/20-knowledge-base-cliente/20-01-SUMMARY.md
|
||||||
|
|
||||||
|
<interfaces>
|
||||||
|
<!-- Pattern esistenti estratti da src/db/schema.ts (linee 464-643) -->
|
||||||
|
|
||||||
|
Pattern tabella CRM con FK lead_id (activities, linee 464-481):
|
||||||
|
```typescript
|
||||||
|
export const activities = pgTable("activities", {
|
||||||
|
id: text("id").primaryKey().$defaultFn(() => nanoid()),
|
||||||
|
lead_id: text("lead_id").notNull().references(() => leads.id, { onDelete: "cascade" }),
|
||||||
|
type: text("type").notNull(),
|
||||||
|
notes: text("notes").notNull(),
|
||||||
|
activity_date: timestamp("activity_date", { withTimezone: true }).notNull(),
|
||||||
|
created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Pattern relazioni (leadsRelations, linea 631-635):
|
||||||
|
```typescript
|
||||||
|
export const leadsRelations = relations(leads, ({ many }) => ({
|
||||||
|
quotes: many(quotes),
|
||||||
|
activities: many(activities),
|
||||||
|
reminders: many(reminders),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const activitiesRelations = relations(activities, ({ one }) => ({
|
||||||
|
lead: one(leads, { fields: [activities.lead_id], references: [leads.id] }),
|
||||||
|
}));
|
||||||
|
```
|
||||||
|
|
||||||
|
Pattern TypeScript types (fine file):
|
||||||
|
```typescript
|
||||||
|
export type Activity = typeof activities.$inferSelect;
|
||||||
|
export type NewActivity = typeof activities.$inferInsert;
|
||||||
|
```
|
||||||
|
|
||||||
|
Pattern query (lead-service.ts linee 51-57):
|
||||||
|
```typescript
|
||||||
|
export async function getActivityLog(leadId: string) {
|
||||||
|
return await db
|
||||||
|
.select()
|
||||||
|
.from(activities)
|
||||||
|
.where(eq(activities.lead_id, leadId))
|
||||||
|
.orderBy(desc(activities.activity_date));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Pattern requireAdmin + server action (actions.ts linee 164-205):
|
||||||
|
```typescript
|
||||||
|
async function requireAdmin() {
|
||||||
|
const session = await getServerSession(authOptions);
|
||||||
|
if (!session) throw new Error("Non autorizzato");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateLeadField(leadId: string, ...) {
|
||||||
|
await requireAdmin();
|
||||||
|
// ... validazione ...
|
||||||
|
await db.update(leads).set({...}).where(eq(leads.id, leadId));
|
||||||
|
revalidatePath("/admin/leads");
|
||||||
|
revalidatePath(`/admin/leads/${leadId}`);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Import correnti in actions.ts (linee 1-16):
|
||||||
|
```typescript
|
||||||
|
"use server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { leads, quotes, tags } from "@/db/schema";
|
||||||
|
import { eq, and } from "drizzle-orm";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { getServerSession } from "next-auth";
|
||||||
|
import { authOptions } from "@/lib/auth";
|
||||||
|
```
|
||||||
|
|
||||||
|
Import correnti in lead-service.ts (linee 1-4):
|
||||||
|
```typescript
|
||||||
|
import { eq, and, isNull, desc, gte, lte, ilike, or } from "drizzle-orm";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import { leads, activities, reminders, quotes } from "@/db/schema";
|
||||||
|
```
|
||||||
|
</interfaces>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<tasks>
|
||||||
|
|
||||||
|
<task type="auto">
|
||||||
|
<name>Task 1: Aggiungere clientTranscripts a src/db/schema.ts</name>
|
||||||
|
<files>src/db/schema.ts</files>
|
||||||
|
<read_first>
|
||||||
|
- src/db/schema.ts (leggere tutto il file per capire dove inserire la nuova tabella e come aggiornare le relations esistenti)
|
||||||
|
- .planning/phases/20-knowledge-base-cliente/20-CONTEXT.md (D-01, D-02 — campi esatti)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
Aggiungere in `src/db/schema.ts` tre blocchi, rispettando la struttura esistente del file:
|
||||||
|
|
||||||
|
**1. Definizione tabella** — aggiungere dopo `// ============ REMINDERS TABLE` (dopo la chiusura della definizione reminders a linea ~499) e prima di `// ============ RELATIONS`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ============ CLIENT TRANSCRIPTS TABLE (Knowledge Base — Phase 20) ============
|
||||||
|
// Transcript datati delle call, multipli per lead o cliente.
|
||||||
|
// lead_id e client_id sono entrambi nullable (D-01): un transcript può appartenere
|
||||||
|
// a un lead pre-conversione (Phase 20 UI) o a un cliente post-conversione (futuro).
|
||||||
|
// onDelete cascade su entrambe le FK — se il lead/cliente viene eliminato, i transcript vengono eliminati.
|
||||||
|
export const clientTranscripts = pgTable("client_transcripts", {
|
||||||
|
id: text("id")
|
||||||
|
.primaryKey()
|
||||||
|
.$defaultFn(() => nanoid()),
|
||||||
|
lead_id: text("lead_id")
|
||||||
|
.references(() => leads.id, { onDelete: "cascade" }),
|
||||||
|
client_id: text("client_id")
|
||||||
|
.references(() => clients.id, { onDelete: "cascade" }),
|
||||||
|
title: text("title"), // opzionale — es. "Discovery call 12 giugno"
|
||||||
|
content: text("content").notNull(), // testo grezzo illimitato (PostgreSQL text)
|
||||||
|
call_date: text("call_date").notNull(), // DATE come text "YYYY-MM-DD" — coerente col pattern date nel progetto
|
||||||
|
created_at: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Nota su `call_date`: usare `text` invece di un tipo `date` Drizzle — il progetto gestisce le date come string ISO nei form e nel DB (vedi `activity_date` che è timestamp, ma `call_date` è date pura). Se Drizzle pg-core espone `date` nativo, usarlo; altrimenti usare `text("call_date").notNull()` per coerenza con i pattern di input da `<input type="date">` che restituisce stringhe "YYYY-MM-DD".
|
||||||
|
|
||||||
|
**2. Relazioni** — aggiungere nei blocchi relations esistenti:
|
||||||
|
|
||||||
|
Aggiornare `leadsRelations` (attuale linea ~631):
|
||||||
|
```typescript
|
||||||
|
export const leadsRelations = relations(leads, ({ many }) => ({
|
||||||
|
quotes: many(quotes),
|
||||||
|
activities: many(activities),
|
||||||
|
reminders: many(reminders),
|
||||||
|
transcripts: many(clientTranscripts), // ← aggiungere questa riga
|
||||||
|
}));
|
||||||
|
```
|
||||||
|
|
||||||
|
Aggiornare `clientsRelations` (attuale linea ~503):
|
||||||
|
```typescript
|
||||||
|
export const clientsRelations = relations(clients, ({ many }) => ({
|
||||||
|
projects: many(projects),
|
||||||
|
transcripts: many(clientTranscripts), // ← aggiungere questa riga
|
||||||
|
}));
|
||||||
|
```
|
||||||
|
|
||||||
|
Aggiungere le nuove relations dopo `remindersRelations`:
|
||||||
|
```typescript
|
||||||
|
export const clientTranscriptsRelations = relations(clientTranscripts, ({ one }) => ({
|
||||||
|
lead: one(leads, {
|
||||||
|
fields: [clientTranscripts.lead_id],
|
||||||
|
references: [leads.id],
|
||||||
|
}),
|
||||||
|
client: one(clients, {
|
||||||
|
fields: [clientTranscripts.client_id],
|
||||||
|
references: [clients.id],
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. TypeScript types** — aggiungere in fondo al file dopo `export type Reminder`:
|
||||||
|
```typescript
|
||||||
|
export type ClientTranscript = typeof clientTranscripts.$inferSelect;
|
||||||
|
export type NewClientTranscript = typeof clientTranscripts.$inferInsert;
|
||||||
|
```
|
||||||
|
</action>
|
||||||
|
<verify>
|
||||||
|
<automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | head -20</automated>
|
||||||
|
</verify>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- `grep -c "export const clientTranscripts = pgTable" src/db/schema.ts` restituisce 1
|
||||||
|
- `grep -c "transcripts: many(clientTranscripts)" src/db/schema.ts` restituisce 2 (leadsRelations + clientsRelations)
|
||||||
|
- `grep -c "export const clientTranscriptsRelations" src/db/schema.ts` restituisce 1
|
||||||
|
- `grep -c "export type ClientTranscript" src/db/schema.ts` restituisce 1
|
||||||
|
- `npx tsc --noEmit` passa senza errori TypeScript relativi a schema.ts
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>clientTranscripts definita in schema.ts con relazioni Drizzle bidirezionali e TypeScript types esportati.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
<task type="auto">
|
||||||
|
<name>Task 2: Aggiungere getTranscripts a lead-service.ts e addTranscript/deleteTranscript ad actions.ts</name>
|
||||||
|
<files>src/lib/lead-service.ts, src/app/admin/leads/actions.ts</files>
|
||||||
|
<read_first>
|
||||||
|
- src/lib/lead-service.ts (leggere per vedere gli import correnti e dove appendere getTranscripts)
|
||||||
|
- src/app/admin/leads/actions.ts (leggere per vedere gli import correnti e la posizione di requireAdmin)
|
||||||
|
- src/db/schema.ts (dopo il Task 1 — per verificare il nome esatto dell'export clientTranscripts)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
**In src/lib/lead-service.ts:**
|
||||||
|
|
||||||
|
Aggiungere `clientTranscripts` agli import esistenti:
|
||||||
|
```typescript
|
||||||
|
import { leads, activities, reminders, quotes, clientTranscripts } from "@/db/schema";
|
||||||
|
```
|
||||||
|
|
||||||
|
Appendere in fondo al file (dopo `getQuotesByLeadId`):
|
||||||
|
```typescript
|
||||||
|
// Get transcript log for a lead — call_date DESC (D-05)
|
||||||
|
// Restituisce tutti i campi incluso content completo (Phase 21 li legge in blocco).
|
||||||
|
export async function getTranscripts(leadId: string) {
|
||||||
|
return await db
|
||||||
|
.select()
|
||||||
|
.from(clientTranscripts)
|
||||||
|
.where(eq(clientTranscripts.lead_id, leadId))
|
||||||
|
.orderBy(desc(clientTranscripts.call_date));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**In src/app/admin/leads/actions.ts:**
|
||||||
|
|
||||||
|
Aggiungere `clientTranscripts` agli import dal DB schema:
|
||||||
|
```typescript
|
||||||
|
import { leads, quotes, tags, clientTranscripts } from "@/db/schema";
|
||||||
|
```
|
||||||
|
|
||||||
|
Aggiungere `nanoid` agli import (serve per generare l'id del transcript):
|
||||||
|
```typescript
|
||||||
|
import { nanoid } from "nanoid";
|
||||||
|
```
|
||||||
|
|
||||||
|
Definire lo schema Zod per il transcript e appendere le due actions dopo le tag actions esistenti (dopo `renameLeadTag`):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ── Transcript actions (Phase 20 — KB-02) ────────────────────────────────────
|
||||||
|
|
||||||
|
const addTranscriptSchema = z.object({
|
||||||
|
lead_id: z.string().min(1),
|
||||||
|
title: z.string().optional(),
|
||||||
|
content: z.string().min(1, "Il testo del transcript è obbligatorio"),
|
||||||
|
call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida (YYYY-MM-DD)"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function addTranscript(data: z.infer<typeof addTranscriptSchema>) {
|
||||||
|
await requireAdmin();
|
||||||
|
|
||||||
|
const parsed = addTranscriptSchema.safeParse(data);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return { success: false, error: parsed.error.issues[0].message };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [transcript] = await db
|
||||||
|
.insert(clientTranscripts)
|
||||||
|
.values({
|
||||||
|
id: nanoid(),
|
||||||
|
lead_id: parsed.data.lead_id,
|
||||||
|
title: parsed.data.title || null,
|
||||||
|
content: parsed.data.content,
|
||||||
|
call_date: parsed.data.call_date,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
revalidatePath(`/admin/leads/${parsed.data.lead_id}`);
|
||||||
|
return { success: true, transcript };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("addTranscript error:", error);
|
||||||
|
return { success: false, error: "Errore nel salvataggio del transcript" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteTranscript(transcriptId: string, leadId: string) {
|
||||||
|
await requireAdmin();
|
||||||
|
|
||||||
|
if (!transcriptId) throw new Error("ID transcript richiesto");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db
|
||||||
|
.delete(clientTranscripts)
|
||||||
|
.where(eq(clientTranscripts.id, transcriptId));
|
||||||
|
|
||||||
|
revalidatePath(`/admin/leads/${leadId}`);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("deleteTranscript error:", error);
|
||||||
|
return { success: false, error: "Errore nell'eliminazione del transcript" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</action>
|
||||||
|
<verify>
|
||||||
|
<automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | grep -E "lead-service|actions" | head -10</automated>
|
||||||
|
</verify>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- `grep -c "export async function getTranscripts" src/lib/lead-service.ts` restituisce 1
|
||||||
|
- `grep -c "orderBy(desc(clientTranscripts.call_date))" src/lib/lead-service.ts` restituisce 1
|
||||||
|
- `grep -c "export async function addTranscript" src/app/admin/leads/actions.ts` restituisce 1
|
||||||
|
- `grep -c "export async function deleteTranscript" src/app/admin/leads/actions.ts` restituisce 1
|
||||||
|
- `grep -c "await requireAdmin()" src/app/admin/leads/actions.ts` è >= 3 (addTranscript e deleteTranscript devono averlo, più le actions esistenti)
|
||||||
|
- `grep -c "revalidatePath" src/app/admin/leads/actions.ts` aumenta di 2 rispetto al file originale (una per addTranscript, una per deleteTranscript)
|
||||||
|
- `npx tsc --noEmit` passa senza errori su lead-service.ts e actions.ts
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>getTranscripts esportata da lead-service.ts, addTranscript e deleteTranscript aggiunte ad actions.ts con requireAdmin guard e revalidatePath.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
</tasks>
|
||||||
|
|
||||||
|
<threat_model>
|
||||||
|
## Trust Boundaries
|
||||||
|
|
||||||
|
| Boundary | Descrizione |
|
||||||
|
|----------|-------------|
|
||||||
|
| browser → server action | addTranscript e deleteTranscript sono "use server" — input non trusted |
|
||||||
|
| server action → database | Query Drizzle con parametri typed |
|
||||||
|
|
||||||
|
## STRIDE Threat Register
|
||||||
|
|
||||||
|
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|
||||||
|
|-----------|----------|-----------|-------------|-----------------|
|
||||||
|
| T-20-04 | Elevation of Privilege | addTranscript / deleteTranscript | mitigate | `await requireAdmin()` come prima istruzione in entrambe le actions — lancia Error se sessione assente, blocca esecuzione |
|
||||||
|
| T-20-05 | Tampering | addTranscript — content | accept | Nessuna sanitization HTML richiesta (testo grezzo, non renderizzato come HTML — CONTEXT.md security note); Zod valida presenza e tipo |
|
||||||
|
| T-20-06 | Tampering | deleteTranscript — transcriptId | mitigate | L'ID viene passato dalla UI admin-only (protetta da requireAdmin); Drizzle usa query parametrizzata — no SQL injection |
|
||||||
|
| T-20-07 | Information Disclosure | getTranscripts | mitigate | Funzione usata solo in server components admin (`/admin/leads/[id]/page.tsx`); non esposta su API client (D-04 — client_id FK presente ma non UI client in Phase 20) |
|
||||||
|
</threat_model>
|
||||||
|
|
||||||
|
<verification>
|
||||||
|
```bash
|
||||||
|
cd /Users/simonecavalli/Vault/IAMCAVALLI
|
||||||
|
|
||||||
|
# Schema: tabella e relazioni presenti
|
||||||
|
grep -E "clientTranscripts|ClientTranscript" src/db/schema.ts | grep -v "^//"
|
||||||
|
|
||||||
|
# lead-service: query con ordinamento corretto
|
||||||
|
grep -A 6 "getTranscripts" src/lib/lead-service.ts
|
||||||
|
|
||||||
|
# actions: requireAdmin su entrambe le nuove actions
|
||||||
|
grep -B 1 "requireAdmin" src/app/admin/leads/actions.ts
|
||||||
|
|
||||||
|
# Build TypeScript
|
||||||
|
npx tsc --noEmit 2>&1 | tail -5
|
||||||
|
```
|
||||||
|
</verification>
|
||||||
|
|
||||||
|
<success_criteria>
|
||||||
|
- schema.ts contiene `clientTranscripts` table, relazioni bidirezionali (leads + clients), e TypeScript types (KB-01)
|
||||||
|
- lead-service.ts esporta `getTranscripts(leadId)` che ordina per `call_date DESC` (KB-02, D-05)
|
||||||
|
- actions.ts ha `addTranscript` e `deleteTranscript` entrambe con `requireAdmin()` guard (KB-02)
|
||||||
|
- `npx tsc --noEmit` passa senza errori sui file modificati
|
||||||
|
</success_criteria>
|
||||||
|
|
||||||
|
<output>
|
||||||
|
Dopo il completamento, creare `.planning/phases/20-knowledge-base-cliente/20-02-SUMMARY.md` con:
|
||||||
|
- Tabella Drizzle aggiunta: clientTranscripts con 7 campi
|
||||||
|
- Query aggiunta: getTranscripts(leadId) in lead-service.ts
|
||||||
|
- Actions aggiunte: addTranscript, deleteTranscript in actions.ts
|
||||||
|
- TypeScript check: passed/failed
|
||||||
|
</output>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: "02"
|
||||||
|
status: complete
|
||||||
|
completed_at: "2026-06-20"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan 20-02 Summary: Data Layer client_transcripts
|
||||||
|
|
||||||
|
## What Was Built
|
||||||
|
|
||||||
|
Drizzle schema, query layer e server actions per i transcript delle call.
|
||||||
|
|
||||||
|
## Key Files Modified
|
||||||
|
|
||||||
|
- `src/db/schema.ts` — tabella `clientTranscripts` + relazioni bidirezionali + TypeScript types
|
||||||
|
- `src/lib/lead-service.ts` — `getTranscripts(leadId)` con orderBy call_date DESC
|
||||||
|
- `src/app/admin/leads/actions.ts` — `addTranscript` + `deleteTranscript` con requireAdmin
|
||||||
|
|
||||||
|
## Self-Check: PASSED
|
||||||
|
|
||||||
|
- ✓ `export const clientTranscripts = pgTable("client_transcripts", ...)` in schema.ts
|
||||||
|
- ✓ `leadsRelations` aggiornato con `transcripts: many(clientTranscripts)`
|
||||||
|
- ✓ `clientsRelations` aggiornato con `transcripts: many(clientTranscripts)`
|
||||||
|
- ✓ `clientTranscriptsRelations` con one(leads) + one(clients)
|
||||||
|
- ✓ `export type ClientTranscript` e `NewClientTranscript` esportati
|
||||||
|
- ✓ `getTranscripts(leadId)` ordinato per `call_date DESC`
|
||||||
|
- ✓ `addTranscript` con requireAdmin + Zod + revalidatePath
|
||||||
|
- ✓ `deleteTranscript` con requireAdmin + revalidatePath
|
||||||
|
- ✓ `npx tsc --noEmit` → no errors
|
||||||
@@ -0,0 +1,626 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: 03
|
||||||
|
type: execute
|
||||||
|
wave: 3
|
||||||
|
depends_on:
|
||||||
|
- 20-01
|
||||||
|
- 20-02
|
||||||
|
files_modified:
|
||||||
|
- src/components/admin/leads/TranscriptModal.tsx
|
||||||
|
- src/components/admin/leads/LeadDetail.tsx
|
||||||
|
- src/app/admin/leads/[id]/page.tsx
|
||||||
|
autonomous: true
|
||||||
|
requirements:
|
||||||
|
- KB-02
|
||||||
|
must_haves:
|
||||||
|
truths:
|
||||||
|
- "L'admin può aggiungere un transcript dalla pagina dettaglio lead via modal"
|
||||||
|
- "I transcript sono elencati in call_date DESC con titolo, data formattata e anteprima del testo"
|
||||||
|
- "Il testo completo di ogni transcript è espandibile/collassabile"
|
||||||
|
- "L'admin può eliminare un transcript con un bottone 'Elimina'"
|
||||||
|
- "La sezione Transcript appare dopo lo Storico Attività nel LeadDetail"
|
||||||
|
artifacts:
|
||||||
|
- path: "src/components/admin/leads/TranscriptModal.tsx"
|
||||||
|
provides: "Modal form per aggiungere transcript (call_date, title opzionale, content textarea)"
|
||||||
|
exports: ["TranscriptModal"]
|
||||||
|
- path: "src/components/admin/leads/LeadDetail.tsx"
|
||||||
|
provides: "Sezione Transcript con lista collassabile e azione Elimina"
|
||||||
|
contains: "Transcript"
|
||||||
|
- path: "src/app/admin/leads/[id]/page.tsx"
|
||||||
|
provides: "getTranscripts(id) nel Promise.all + prop transcripts passato a LeadDetail"
|
||||||
|
contains: "getTranscripts"
|
||||||
|
key_links:
|
||||||
|
- from: "src/components/admin/leads/TranscriptModal.tsx"
|
||||||
|
to: "src/app/admin/leads/actions.ts"
|
||||||
|
via: "import addTranscript"
|
||||||
|
pattern: "addTranscript"
|
||||||
|
- from: "src/components/admin/leads/LeadDetail.tsx"
|
||||||
|
to: "src/app/admin/leads/actions.ts"
|
||||||
|
via: "import deleteTranscript"
|
||||||
|
pattern: "deleteTranscript"
|
||||||
|
- from: "src/app/admin/leads/[id]/page.tsx"
|
||||||
|
to: "src/lib/lead-service.ts"
|
||||||
|
via: "import getTranscripts"
|
||||||
|
pattern: "getTranscripts"
|
||||||
|
---
|
||||||
|
|
||||||
|
<objective>
|
||||||
|
Creare il componente `TranscriptModal` (form per aggiungere transcript) e integrare la sezione Transcript in `LeadDetail`, con wiring nella page server.
|
||||||
|
|
||||||
|
Purpose: Completa il loop KB-02 — l'admin può incollare transcript datati e vederli elencati in ordine cronologico nel profilo lead. I dati sono pronti per essere letti dall'agente AI in Phase 21.
|
||||||
|
|
||||||
|
Output: UI completa funzionante — modal di aggiunta + lista con expand/collapse + elimina.
|
||||||
|
</objective>
|
||||||
|
|
||||||
|
<execution_context>
|
||||||
|
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
|
||||||
|
@$HOME/.claude/get-shit-done/templates/summary.md
|
||||||
|
</execution_context>
|
||||||
|
|
||||||
|
<context>
|
||||||
|
@.planning/phases/20-knowledge-base-cliente/20-CONTEXT.md
|
||||||
|
@.planning/phases/20-knowledge-base-cliente/20-02-SUMMARY.md
|
||||||
|
|
||||||
|
<interfaces>
|
||||||
|
<!-- Pattern estratti da file esistenti — l'executor NON deve rileggere questi file -->
|
||||||
|
|
||||||
|
Da LogActivityModal.tsx — pattern modal con react-hook-form + zod + shadcn Dialog:
|
||||||
|
```typescript
|
||||||
|
"use client";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { z } from "zod";
|
||||||
|
// ... action import ...
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||||
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
export function LogActivityModal({ leadId }: { leadId: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const form = useForm<any>({
|
||||||
|
resolver: zodResolver(schema),
|
||||||
|
defaultValues: { lead_id: leadId, activity_date: new Date().toISOString().split("T")[0], ... },
|
||||||
|
});
|
||||||
|
async function onSubmit(data) {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await logActivity(data);
|
||||||
|
if (result.success) { setOpen(false); form.reset({...}); }
|
||||||
|
} finally { setLoading(false); }
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild><Button variant="outline" size="sm">...</Button></DialogTrigger>
|
||||||
|
<DialogContent className="max-w-sm">
|
||||||
|
...
|
||||||
|
<Input type="date" {...field} value={field.value || ""} />
|
||||||
|
<Textarea className="resize-none h-24" {...field} value={field.value || ""} />
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>...</Button>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Da LeadDetail.tsx — struttura esistente con Card shadcn + sezione attività (pattern da replicare per Transcript):
|
||||||
|
```typescript
|
||||||
|
"use client";
|
||||||
|
import { useState, useTransition } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Lead, Activity, Reminder } from "@/db/schema"; // ← aggiungere ClientTranscript
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { it } from "date-fns/locale";
|
||||||
|
|
||||||
|
// Signature attuale LeadDetail:
|
||||||
|
export function LeadDetail({
|
||||||
|
lead, activities, reminders, tags, tagOptions
|
||||||
|
}: {
|
||||||
|
lead: Lead; activities: Activity[]; reminders: Reminder[];
|
||||||
|
tags: string[]; tagOptions: string[];
|
||||||
|
})
|
||||||
|
|
||||||
|
// Sezione Attività (pattern da replicare per Transcript):
|
||||||
|
<Card>
|
||||||
|
<CardHeader><CardTitle>Storico Attività</CardTitle></CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{activities.length > 0 ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{activities.map((activity) => (
|
||||||
|
<div key={activity.id} className="border-l-4 border-blue-300 pl-4 pb-4">
|
||||||
|
...testo e date formattate con date-fns...
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-gray-500 text-sm">Nessuna attività registrata</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
|
||||||
|
Da page.tsx — pattern Promise.all e passaggio props:
|
||||||
|
```typescript
|
||||||
|
import { getActivityLog, getUpcomingReminders } from "@/lib/lead-service";
|
||||||
|
// ← aggiungere: import { getTranscripts } from "@/lib/lead-service";
|
||||||
|
|
||||||
|
const activities = await getActivityLog(id);
|
||||||
|
const reminders = await getUpcomingReminders(id);
|
||||||
|
// ← aggiungere nel Promise.all oppure sequenzialmente dopo
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LeadDetail
|
||||||
|
lead={lead}
|
||||||
|
activities={activities}
|
||||||
|
reminders={reminders}
|
||||||
|
tags={lead.tags}
|
||||||
|
tagOptions={options.tags}
|
||||||
|
// ← aggiungere: transcripts={transcripts}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Tipo ClientTranscript (da schema.ts dopo Plan 02):
|
||||||
|
```typescript
|
||||||
|
export type ClientTranscript = typeof clientTranscripts.$inferSelect;
|
||||||
|
// Campi: id, lead_id, client_id, title, content, call_date, created_at
|
||||||
|
```
|
||||||
|
|
||||||
|
Formattazione date italiana con date-fns (già usato nel progetto):
|
||||||
|
```typescript
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { it } from "date-fns/locale";
|
||||||
|
// call_date è string "YYYY-MM-DD" — usare new Date(t.call_date + "T00:00:00") per evitare timezone shift
|
||||||
|
format(new Date(t.call_date + "T00:00:00"), "d MMMM yyyy", { locale: it })
|
||||||
|
// → "12 giugno 2026"
|
||||||
|
```
|
||||||
|
</interfaces>
|
||||||
|
</context>
|
||||||
|
|
||||||
|
<tasks>
|
||||||
|
|
||||||
|
<task type="auto">
|
||||||
|
<name>Task 1: Creare TranscriptModal.tsx e aggiornare page.tsx</name>
|
||||||
|
<files>src/components/admin/leads/TranscriptModal.tsx, src/app/admin/leads/[id]/page.tsx</files>
|
||||||
|
<read_first>
|
||||||
|
- src/components/admin/leads/LogActivityModal.tsx (pattern esatto del modal da replicare)
|
||||||
|
- src/app/admin/leads/[id]/page.tsx (vedere la struttura attuale per capire dove aggiungere getTranscripts)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
**Creare src/components/admin/leads/TranscriptModal.tsx:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { addTranscript } from "@/app/admin/leads/actions";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
FormControl,
|
||||||
|
FormField,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormMessage,
|
||||||
|
} from "@/components/ui/form";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
const transcriptSchema = z.object({
|
||||||
|
lead_id: z.string().min(1),
|
||||||
|
title: z.string().optional(),
|
||||||
|
content: z.string().min(1, "Il testo del transcript è obbligatorio"),
|
||||||
|
call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida"),
|
||||||
|
});
|
||||||
|
|
||||||
|
type TranscriptInput = z.infer<typeof transcriptSchema>;
|
||||||
|
|
||||||
|
export function TranscriptModal({ leadId }: { leadId: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const form = useForm<TranscriptInput>({
|
||||||
|
resolver: zodResolver(transcriptSchema),
|
||||||
|
defaultValues: {
|
||||||
|
lead_id: leadId,
|
||||||
|
title: "",
|
||||||
|
content: "",
|
||||||
|
call_date: new Date().toISOString().split("T")[0],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function onSubmit(data: TranscriptInput) {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await addTranscript(data);
|
||||||
|
if (result.success) {
|
||||||
|
setOpen(false);
|
||||||
|
form.reset({
|
||||||
|
lead_id: leadId,
|
||||||
|
title: "",
|
||||||
|
content: "",
|
||||||
|
call_date: new Date().toISOString().split("T")[0],
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setError(result.error ?? "Errore nel salvataggio");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm">
|
||||||
|
Aggiungi Transcript
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Aggiungi Transcript Call</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="call_date"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Data call</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input type="date" {...field} value={field.value || ""} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="title"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Titolo (opzionale)</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
placeholder="es. Discovery call"
|
||||||
|
{...field}
|
||||||
|
value={field.value || ""}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="content"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Transcript</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Textarea
|
||||||
|
placeholder="Incolla qui il testo del transcript..."
|
||||||
|
className="min-h-48 resize-y"
|
||||||
|
{...field}
|
||||||
|
value={field.value || ""}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||||
|
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Salvataggio..." : "Salva Transcript"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Aggiornare src/app/admin/leads/[id]/page.tsx:**
|
||||||
|
|
||||||
|
Aggiungere `getTranscripts` all'import da lead-service:
|
||||||
|
```typescript
|
||||||
|
import { getActivityLog, getUpcomingReminders, getTranscripts } from "@/lib/lead-service";
|
||||||
|
```
|
||||||
|
|
||||||
|
Aggiungere la fetch nel corpo del componente. La page attualmente fa due call sequenziali dopo il Promise.all. Aggiungere `getTranscripts(id)` in parallelo con le altre:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const [leads, options, transcripts] = await Promise.all([
|
||||||
|
getLeadsWithTags(),
|
||||||
|
getLeadFieldOptions(),
|
||||||
|
getTranscripts(id),
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
Oppure, se la struttura attuale non usa Promise.all per tutte le chiamate, aggiungere sequenzialmente dopo `reminders`:
|
||||||
|
```typescript
|
||||||
|
const transcripts = await getTranscripts(id);
|
||||||
|
```
|
||||||
|
|
||||||
|
Passare la prop al componente:
|
||||||
|
```typescript
|
||||||
|
return (
|
||||||
|
<LeadDetail
|
||||||
|
lead={lead}
|
||||||
|
activities={activities}
|
||||||
|
reminders={reminders}
|
||||||
|
tags={lead.tags}
|
||||||
|
tagOptions={options.tags}
|
||||||
|
transcripts={transcripts}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
```
|
||||||
|
</action>
|
||||||
|
<verify>
|
||||||
|
<automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | grep -E "TranscriptModal|page" | head -10</automated>
|
||||||
|
</verify>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- File `src/components/admin/leads/TranscriptModal.tsx` esiste
|
||||||
|
- `grep -c "export function TranscriptModal" src/components/admin/leads/TranscriptModal.tsx` restituisce 1
|
||||||
|
- `grep -c "min-h-48" src/components/admin/leads/TranscriptModal.tsx` restituisce 1 (textarea generosa)
|
||||||
|
- `grep -c "Aggiungi Transcript" src/components/admin/leads/TranscriptModal.tsx` restituisce almeno 1
|
||||||
|
- `grep -c "getTranscripts" src/app/admin/leads/[id]/page.tsx` restituisce almeno 2 (import + chiamata)
|
||||||
|
- `grep -c "transcripts={transcripts}" src/app/admin/leads/[id]/page.tsx` restituisce 1
|
||||||
|
- `npx tsc --noEmit` passa senza errori su questi file
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>TranscriptModal creato, page.tsx aggiornata con getTranscripts e prop transcripts passata a LeadDetail.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
<task type="auto">
|
||||||
|
<name>Task 2: Aggiornare LeadDetail.tsx — aggiungere prop transcripts e sezione Transcript</name>
|
||||||
|
<files>src/components/admin/leads/LeadDetail.tsx</files>
|
||||||
|
<read_first>
|
||||||
|
- src/components/admin/leads/LeadDetail.tsx (leggere per vedere la struttura attuale — dove finisce la sezione Attività e dove inserire Transcript)
|
||||||
|
</read_first>
|
||||||
|
<action>
|
||||||
|
Aggiornare `src/components/admin/leads/LeadDetail.tsx` con le seguenti modifiche:
|
||||||
|
|
||||||
|
**1. Aggiungere import:**
|
||||||
|
```typescript
|
||||||
|
import { ClientTranscript } from "@/db/schema";
|
||||||
|
import { useTransition } from "react"; // già importato — verificare che ci sia
|
||||||
|
import { TranscriptModal } from "./TranscriptModal";
|
||||||
|
import { deleteTranscript } from "@/app/admin/leads/actions";
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. Aggiungere `transcripts` alla prop interface:**
|
||||||
|
```typescript
|
||||||
|
export function LeadDetail({
|
||||||
|
lead,
|
||||||
|
activities,
|
||||||
|
reminders,
|
||||||
|
tags,
|
||||||
|
tagOptions,
|
||||||
|
transcripts, // ← aggiungere
|
||||||
|
}: {
|
||||||
|
lead: Lead;
|
||||||
|
activities: Activity[];
|
||||||
|
reminders: Reminder[];
|
||||||
|
tags: string[];
|
||||||
|
tagOptions: string[];
|
||||||
|
transcripts: ClientTranscript[]; // ← aggiungere
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. Aggiungere state per expand/collapse e delete nel corpo del componente:**
|
||||||
|
|
||||||
|
Aggiungere dopo gli useState esistenti:
|
||||||
|
```typescript
|
||||||
|
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
|
||||||
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
|
const [, startDeleteTransition] = useTransition();
|
||||||
|
|
||||||
|
function toggleExpand(id: string) {
|
||||||
|
setExpandedIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(id)) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDelete(transcriptId: string) {
|
||||||
|
setDeletingId(transcriptId);
|
||||||
|
startDeleteTransition(async () => {
|
||||||
|
try {
|
||||||
|
await deleteTranscript(transcriptId, lead.id);
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
console.error("deleteTranscript error:", e);
|
||||||
|
} finally {
|
||||||
|
setDeletingId(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. Aggiungere il pulsante TranscriptModal nell'header (accanto a LogActivityModal):**
|
||||||
|
```typescript
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<LogActivityModal leadId={lead.id} />
|
||||||
|
<TranscriptModal leadId={lead.id} /> {/* ← aggiungere */}
|
||||||
|
<SendQuoteModal leadId={lead.id} />
|
||||||
|
<EditLeadModal lead={lead} />
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
**5. Aggiungere la sezione Transcript dopo la sezione Storico Attività (dopo la chiusura del `</Card>` dell'attività):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
{/* Transcript */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between">
|
||||||
|
<CardTitle>Transcript Call</CardTitle>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
{transcripts.length} {transcripts.length === 1 ? "transcript" : "transcript"}
|
||||||
|
</span>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{transcripts.length > 0 ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{transcripts.map((t) => {
|
||||||
|
const isExpanded = expandedIds.has(t.id);
|
||||||
|
// Formattare call_date come "12 giugno 2026"
|
||||||
|
// call_date è string "YYYY-MM-DD" — aggiungere T00:00:00 per evitare timezone shift
|
||||||
|
const formattedDate = format(
|
||||||
|
new Date(t.call_date + "T00:00:00"),
|
||||||
|
"d MMMM yyyy",
|
||||||
|
{ locale: it }
|
||||||
|
);
|
||||||
|
// Anteprima: prime 3 righe o 200 caratteri (il primo valore raggiunto)
|
||||||
|
const preview = t.content
|
||||||
|
.split("\n")
|
||||||
|
.slice(0, 3)
|
||||||
|
.join("\n")
|
||||||
|
.slice(0, 200);
|
||||||
|
const hasMore = t.content.length > preview.length || t.content.split("\n").length > 3;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={t.id} className="border-l-4 border-purple-300 pl-4 pb-4">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="font-medium text-sm">{formattedDate}</span>
|
||||||
|
{t.title && (
|
||||||
|
<span className="text-gray-600 text-sm">— {t.title}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-sm text-gray-700 whitespace-pre-wrap">
|
||||||
|
{isExpanded ? t.content : preview}
|
||||||
|
{!isExpanded && hasMore && (
|
||||||
|
<span className="text-gray-400">...</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{hasMore && (
|
||||||
|
<button
|
||||||
|
onClick={() => toggleExpand(t.id)}
|
||||||
|
className="text-xs text-blue-600 hover:underline mt-1"
|
||||||
|
>
|
||||||
|
{isExpanded ? "Mostra meno" : "Mostra tutto"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-600 hover:text-red-700 shrink-0"
|
||||||
|
disabled={deletingId === t.id}
|
||||||
|
onClick={() => handleDelete(t.id)}
|
||||||
|
>
|
||||||
|
{deletingId === t.id ? "..." : "Elimina"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-gray-500 text-sm">Nessun transcript registrato</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
```
|
||||||
|
</action>
|
||||||
|
<verify>
|
||||||
|
<automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | grep "LeadDetail" | head -10</automated>
|
||||||
|
</verify>
|
||||||
|
<acceptance_criteria>
|
||||||
|
- `grep -c "transcripts: ClientTranscript\[\]" src/components/admin/leads/LeadDetail.tsx` restituisce 1
|
||||||
|
- `grep -c "TranscriptModal" src/components/admin/leads/LeadDetail.tsx` restituisce almeno 2 (import + uso nel JSX)
|
||||||
|
- `grep -c "deleteTranscript" src/components/admin/leads/LeadDetail.tsx` restituisce almeno 2 (import + uso in handleDelete)
|
||||||
|
- `grep -c "Transcript Call" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (titolo Card sezione)
|
||||||
|
- `grep -c "Mostra tutto" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (expand/collapse)
|
||||||
|
- `grep -c "T00:00:00" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (fix timezone per call_date)
|
||||||
|
- `grep -c "border-l-4 border-purple-300" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (stile sezione transcript, distinto dal blu delle attività)
|
||||||
|
- `npx tsc --noEmit` passa senza errori su LeadDetail.tsx
|
||||||
|
- `npm run build` completa senza errori (verificare alla fine)
|
||||||
|
</acceptance_criteria>
|
||||||
|
<done>LeadDetail aggiornato con prop transcripts, sezione Transcript con lista expand/collapse e azione Elimina posizionata dopo Storico Attività.</done>
|
||||||
|
</task>
|
||||||
|
|
||||||
|
</tasks>
|
||||||
|
|
||||||
|
<threat_model>
|
||||||
|
## Trust Boundaries
|
||||||
|
|
||||||
|
| Boundary | Descrizione |
|
||||||
|
|----------|-------------|
|
||||||
|
| browser → TranscriptModal form | Input utente admin non sanitizzato prima del submit |
|
||||||
|
| TranscriptModal → addTranscript server action | "use server" boundary — Zod valida il payload |
|
||||||
|
|
||||||
|
## STRIDE Threat Register
|
||||||
|
|
||||||
|
| Threat ID | Category | Component | Disposition | Mitigation Plan |
|
||||||
|
|-----------|----------|-----------|-------------|-----------------|
|
||||||
|
| T-20-08 | Tampering | TranscriptModal — content field | accept | Il content è testo grezzo (textarea), non renderizzato come HTML nella UI — nessun XSS possibile con `whitespace-pre-wrap` senza `dangerouslySetInnerHTML`; Zod valida min length 1 |
|
||||||
|
| T-20-09 | Elevation of Privilege | TranscriptModal — addTranscript call | mitigate | La route `/admin/leads/[id]` è protetta dal middleware Auth.js (sessione admin richiesta); `addTranscript` server action chiama `requireAdmin()` come prima istruzione |
|
||||||
|
| T-20-10 | Elevation of Privilege | deleteTranscript client call | mitigate | `deleteTranscript` server action chiama `requireAdmin()` come prima istruzione; il transcriptId viene dalla prop SSR, non da input utente libero |
|
||||||
|
| T-20-11 | Information Disclosure | Transcript content nel DOM | accept | La pagina è `/admin/*` — solo admin autenticato la vede; nessuna esposizione lato client pubblico |
|
||||||
|
</threat_model>
|
||||||
|
|
||||||
|
<verification>
|
||||||
|
```bash
|
||||||
|
cd /Users/simonecavalli/Vault/IAMCAVALLI
|
||||||
|
|
||||||
|
# Verificare che tutti i file esistano
|
||||||
|
ls -la src/components/admin/leads/TranscriptModal.tsx
|
||||||
|
grep -c "getTranscripts" src/app/admin/leads/\[id\]/page.tsx
|
||||||
|
grep -c "transcripts: ClientTranscript" src/components/admin/leads/LeadDetail.tsx
|
||||||
|
|
||||||
|
# Verificare struttura sezione Transcript
|
||||||
|
grep -n "Transcript\|deleteTranscript\|TranscriptModal" src/components/admin/leads/LeadDetail.tsx
|
||||||
|
|
||||||
|
# Build completo
|
||||||
|
npm run build 2>&1 | tail -15
|
||||||
|
```
|
||||||
|
</verification>
|
||||||
|
|
||||||
|
<success_criteria>
|
||||||
|
- `TranscriptModal.tsx` esiste con form: call_date (date input), title (optional text), content (textarea min-h-48) (KB-02)
|
||||||
|
- `LeadDetail.tsx` ha prop `transcripts: ClientTranscript[]` e sezione "Transcript Call" dopo "Storico Attività" (KB-02, D-05)
|
||||||
|
- Lista transcript mostra: data formattata in italiano, titolo se presente, anteprima testo con expand/collapse, bottone Elimina (KB-02)
|
||||||
|
- `page.tsx` chiama `getTranscripts(id)` e passa `transcripts` a `LeadDetail` (KB-02)
|
||||||
|
- `npm run build` completa senza errori TypeScript o di compilazione
|
||||||
|
</success_criteria>
|
||||||
|
|
||||||
|
<output>
|
||||||
|
Dopo il completamento, creare `.planning/phases/20-knowledge-base-cliente/20-03-SUMMARY.md` con:
|
||||||
|
- Componenti creati: TranscriptModal.tsx
|
||||||
|
- Componenti modificati: LeadDetail.tsx, page.tsx
|
||||||
|
- Features: modal aggiunta, lista con expand/collapse, eliminazione, data in italiano
|
||||||
|
- Build status: passed/failed
|
||||||
|
- Note su eventuali adattamenti ai pattern esistenti
|
||||||
|
</output>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
phase: 20-knowledge-base-cliente
|
||||||
|
plan: "03"
|
||||||
|
status: complete
|
||||||
|
completed_at: "2026-06-20"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Plan 20-03 Summary: UI Transcript Call
|
||||||
|
|
||||||
|
## What Was Built
|
||||||
|
|
||||||
|
UI completa per aggiungere, visualizzare ed eliminare i transcript delle call nel profilo lead.
|
||||||
|
|
||||||
|
## Key Files
|
||||||
|
|
||||||
|
### Created
|
||||||
|
- `src/components/admin/leads/TranscriptModal.tsx` — modal form (call_date + title + content textarea min-h-48)
|
||||||
|
|
||||||
|
### Modified
|
||||||
|
- `src/components/admin/leads/LeadDetail.tsx` — prop `transcripts: ClientTranscript[]`, sezione "Transcript Call" con expand/collapse e Elimina, TranscriptModal nel header
|
||||||
|
- `src/app/admin/leads/[id]/page.tsx` — `getTranscripts(id)` nel Promise.all, prop `transcripts` passato a LeadDetail
|
||||||
|
|
||||||
|
## Self-Check: PASSED
|
||||||
|
|
||||||
|
- ✓ `TranscriptModal.tsx` esiste con form call_date/title/content (min-h-48)
|
||||||
|
- ✓ `LeadDetail.tsx` ha prop `transcripts: ClientTranscript[]`
|
||||||
|
- ✓ Sezione "Transcript Call" appare dopo "Storico Attività"
|
||||||
|
- ✓ Data formattata in italiano con `new Date(t.call_date + "T00:00:00")` (fix TZ shift)
|
||||||
|
- ✓ Preview 3 righe/200 caratteri con toggle "Mostra tutto / Mostra meno"
|
||||||
|
- ✓ Bottone "Elimina" via `deleteTranscript` server action
|
||||||
|
- ✓ `border-l-4 border-purple-300` — stile distinto dal blu delle attività
|
||||||
|
- ✓ `getTranscripts(id)` nel Promise.all di page.tsx
|
||||||
|
- ✓ `npx tsc --noEmit` → no errors
|
||||||
|
- ✓ `npm run build` → clean
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Phase 20: Knowledge Base Cliente — Context
|
||||||
|
|
||||||
|
**Gathered:** 2026-06-19
|
||||||
|
**Status:** Ready for planning
|
||||||
|
|
||||||
|
<domain>
|
||||||
|
## Phase Boundary
|
||||||
|
|
||||||
|
Aggiungere uno store di transcript datati per lead: l'admin incolla il testo grezzo di ogni call con data e titolo libero, la lista appare in ordine cronologico nel dettaglio lead, e i dati sono pronti per essere letti dall'agente AI in Phase 21.
|
||||||
|
|
||||||
|
**In scope:** schema `client_transcripts` + server actions + UI nel LeadDetail
|
||||||
|
**Out of scope:** UI per clienti (client_id FK presente ma non esposta), ricerca full-text sui transcript, trascrizione automatica da audio
|
||||||
|
|
||||||
|
</domain>
|
||||||
|
|
||||||
|
<decisions>
|
||||||
|
## Implementation Decisions
|
||||||
|
|
||||||
|
### Schema — client_transcripts
|
||||||
|
|
||||||
|
- **D-01:** La tabella `client_transcripts` ha **entrambe** le FK nullable: `lead_id` (references leads, onDelete cascade) e `client_id` (references clients, onDelete cascade). Ragionamento: prepara la struttura per transcript post-conversione senza richiedere una migration futura.
|
||||||
|
- **D-02:** Campi: `id` (nanoid PK), `lead_id` (nullable FK), `client_id` (nullable FK), `title` (text, optional — titolo libero es. "Discovery call 12 giugno"), `content` (text NOT NULL — testo incollato, lunghezza illimitata), `call_date` (date NOT NULL — giorno della call, non timestamp), `created_at` (timestamp with timezone, defaultNow).
|
||||||
|
- **D-03:** Migration mano-scritta come 0009 — drizzle-kit generate è rotto. Applicata a prod via SSH **prima** di pushare il codice dipendente (invariante bloccante del progetto).
|
||||||
|
|
||||||
|
### UI — Solo lato lead in Phase 20
|
||||||
|
|
||||||
|
- **D-04:** In Phase 20 la UI espone solo il lato lead. La FK `client_id` è nello schema ma **non ha form o lista** in questa fase — si aggiunge in futuro se serve la pagina `/admin/clients/[id]`.
|
||||||
|
- **D-05:** I transcript sono listati in ordine `call_date DESC` nel dettaglio lead (chiamata più recente in cima).
|
||||||
|
|
||||||
|
### Claude's Discretion
|
||||||
|
|
||||||
|
Le seguenti aree non sono state discusse — Claude ha flessibilità:
|
||||||
|
|
||||||
|
- **Metadati:** No tipo enum — `title` libero (optional) è sufficiente. Il testo del transcript parla da solo.
|
||||||
|
- **Placement UI:** Nuova sezione "Transcript" collassabile in `LeadDetail`, dopo la sezione Attività esistente. Stessa convenzione visiva (Card + lista). Form/modal per aggiungere seguendo il pattern `LogActivityModal`.
|
||||||
|
- **Nessun limite di lunghezza:** `content` è `text` PostgreSQL (illimitato). Textarea nel form senza troncatura.
|
||||||
|
|
||||||
|
</decisions>
|
||||||
|
|
||||||
|
<canonical_refs>
|
||||||
|
## Canonical References
|
||||||
|
|
||||||
|
**Downstream agents MUST read these before planning or implementing.**
|
||||||
|
|
||||||
|
### Requirements & Roadmap
|
||||||
|
- `.planning/ROADMAP.md` — Phase 20 goal, success criteria, schema spec (`client_transcripts` con `lead_id/client_id, testo, data, titolo/tipo, created_at`)
|
||||||
|
- `.planning/REQUIREMENTS.md` — KB-01 (schema additivo transcript), KB-02 (UI incolla/elenca)
|
||||||
|
|
||||||
|
### Schema & Migrations
|
||||||
|
- `src/db/schema.ts` — pattern tabelle append-only CRM: `activities` (lead_id, type, notes, activity_date), `reminders` (lead_id, due_date). La nuova `client_transcripts` segue questo pattern.
|
||||||
|
- `src/db/migrations/0008_offer_tier_schema.sql` — ultimo esempio di SQL migration a mano (struttura e convenzioni da seguire)
|
||||||
|
- `src/db/migrations/0005_phase_10_crm_leads_activities_reminders.sql` — migration originale di `activities` e `reminders` (pattern più vicino alla nuova tabella)
|
||||||
|
|
||||||
|
### UI & Components
|
||||||
|
- `src/components/admin/leads/LeadDetail.tsx` — struttura UI esistente del dettaglio lead (dove va inserita la sezione Transcript)
|
||||||
|
- `src/components/admin/leads/LogActivityModal.tsx` — pattern modal per aggiungere dati CRM (da seguire per il form transcript)
|
||||||
|
- `src/app/admin/leads/[id]/page.tsx` — pattern page con `Promise.all` per fetch parallele (aggiungere `getTranscripts(id)`)
|
||||||
|
|
||||||
|
### Query & Actions Layer
|
||||||
|
- `src/lib/lead-service.ts` — pattern query layer CRM (`getActivityLog`, `getUpcomingReminders` — aggiungere `getTranscripts`)
|
||||||
|
- `src/app/admin/leads/actions.ts` — pattern server actions con `requireAdmin` guard (da seguire per `addTranscript`, `deleteTranscript`)
|
||||||
|
|
||||||
|
</canonical_refs>
|
||||||
|
|
||||||
|
<code_context>
|
||||||
|
## Existing Code Insights
|
||||||
|
|
||||||
|
### Reusable Assets
|
||||||
|
- `LogActivityModal.tsx` — modal con form controllato (date picker + textarea + submit), pronto da clonare per il form transcript
|
||||||
|
- `activities` / `reminders` pattern in `schema.ts` — FK `lead_id` con `onDelete: cascade`, `nanoid()` PK, `created_at` defaultNow — copia esatta per `client_transcripts`
|
||||||
|
- `getActivityLog(leadId)` in `lead-service.ts` — query Drizzle con `where(eq(activities.lead_id, leadId))` e `orderBy(desc(activities.activity_date))` — pattern identico per `getTranscripts`
|
||||||
|
- `Card`, `CardContent`, `CardHeader`, `CardTitle` da shadcn/ui — già usati nel LeadDetail per ogni sezione
|
||||||
|
|
||||||
|
### Established Patterns
|
||||||
|
- **Migration a mano**: ogni schema change è SQL scritto a mano (`CREATE TABLE IF NOT EXISTS`, tipi Postgres espliciti, FK con `ON DELETE CASCADE`). NON usare `drizzle-kit generate`.
|
||||||
|
- **requireAdmin guard**: tutte le server actions in `actions.ts` iniziano con `await requireAdmin()` — obbligatorio anche per le nuove actions transcript.
|
||||||
|
- **`revalidatePath`** dopo ogni mutation: `revalidatePath(\`/admin/leads/${leadId}\`)`.
|
||||||
|
- **Promise.all fetch**: `page.tsx` del dettaglio lead usa `await Promise.all([...])` per fetch parallele — aggiungere `getTranscripts(id)` nello stesso array.
|
||||||
|
|
||||||
|
### Integration Points
|
||||||
|
- `src/app/admin/leads/[id]/page.tsx` — aggiungere `getTranscripts(id)` nel `Promise.all`, passare `transcripts` a `<LeadDetail />`
|
||||||
|
- `src/components/admin/leads/LeadDetail.tsx` — aggiungere prop `transcripts` e sezione "Transcript" dopo `<ActivitySection>`
|
||||||
|
- `src/db/schema.ts` — aggiungere definizione `client_transcripts` + relazioni Drizzle
|
||||||
|
- `src/lib/lead-service.ts` — aggiungere `getTranscripts(leadId: string)`
|
||||||
|
- `src/app/admin/leads/actions.ts` — aggiungere `addTranscript(leadId, data)` e `deleteTranscript(transcriptId)`
|
||||||
|
|
||||||
|
</code_context>
|
||||||
|
|
||||||
|
<specifics>
|
||||||
|
## Specific Ideas
|
||||||
|
|
||||||
|
- Il testo del transcript può essere molto lungo (trascrizioni complete di call). Il form deve avere una `<textarea>` con altezza generosa (es. min-h-48 o più) senza limite di caratteri.
|
||||||
|
- Il `call_date` è una `date` (non timestamp) — l'admin sceglie il giorno della call, non l'ora. Nel DB: `DATE` type PostgreSQL.
|
||||||
|
- La lista transcript deve mostrare: `call_date` formattata (es. "12 giugno 2026"), `title` se presente, anteprima delle prime righe del `content`, e un'azione "Elimina". Espansione/collapse del testo completo.
|
||||||
|
- Phase 21 leggerà i transcript via `getTranscripts(leadId)` — la query deve restituire tutti i campi incluso `content` completo.
|
||||||
|
|
||||||
|
</specifics>
|
||||||
|
|
||||||
|
<deferred>
|
||||||
|
## Deferred Ideas
|
||||||
|
|
||||||
|
- **UI transcript per clienti** (`/admin/clients/[id]`): la FK `client_id` è nella tabella, ma la UI lato cliente è deferred a una fase futura (post v2.2 o su richiesta).
|
||||||
|
- **Ricerca full-text sui transcript**: fuori scope v2.2 — i transcript vengono letti dall'AI in blocco, non cercati dall'admin.
|
||||||
|
- **Trascrizione automatica da audio**: fuori scope — l'admin incolla manualmente il testo.
|
||||||
|
|
||||||
|
</deferred>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Phase: 20-Knowledge Base Cliente*
|
||||||
|
*Context gathered: 2026-06-19*
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Phase 20: Knowledge Base Cliente — Discussion Log
|
||||||
|
|
||||||
|
> **Audit trail only.** Do not use as input to planning, research, or execution agents.
|
||||||
|
> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered.
|
||||||
|
|
||||||
|
**Date:** 2026-06-19
|
||||||
|
**Phase:** 20-knowledge-base-cliente
|
||||||
|
**Areas discussed:** Lead-scoped o anche client?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lead-scoped o anche client?
|
||||||
|
|
||||||
|
### Q1 — FK scope della tabella
|
||||||
|
|
||||||
|
| Option | Description | Selected |
|
||||||
|
|--------|-------------|----------|
|
||||||
|
| Solo lead per ora | `client_transcripts` ha solo `lead_id`. Semplice, sufficiente per Phase 21. La FK `client_id` si aggiunge in futuro se serve. | |
|
||||||
|
| Prepara entrambe le FK ora | `lead_id` e `client_id` entrambi nullable nella tabella. Più lavoro ora, ma non serve una migration futura se vuoi trascrizioni anche per clienti esistenti. | ✓ |
|
||||||
|
|
||||||
|
**User's choice:** Prepara entrambe le FK ora
|
||||||
|
**Notes:** L'utente preferisce prepararsi alla flessibilità futura con una sola migration ora.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Q2 — UI Phase 20 per client_id
|
||||||
|
|
||||||
|
| Option | Description | Selected |
|
||||||
|
|--------|-------------|----------|
|
||||||
|
| Solo dal dettaglio lead per ora | La FK `client_id` c'è nello schema ma non è esposta in UI in Phase 20. Si usa quando un lead è convertito — per dopo. | ✓ |
|
||||||
|
| Anche dalla pagina admin cliente | Phase 20 aggiunge il blocco transcript sia nel LeadDetail che in `/admin/clients/[id]`. Più lavoro, ma copre subito clienti esistenti senza lead. | |
|
||||||
|
|
||||||
|
**User's choice:** Solo dal dettaglio lead per ora
|
||||||
|
**Notes:** L'UI Phase 20 è solo lato lead. `client_id` è nello schema ma non esposta.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Claude's Discretion
|
||||||
|
|
||||||
|
Le seguenti aree non sono state discusse e sono state lasciate al giudizio di Claude:
|
||||||
|
|
||||||
|
- **Metadati del transcript** — Scelto: `title` (text, optional) + `content` (text, illimitato) + `call_date` (date). No enum tipo — il titolo libero è sufficiente.
|
||||||
|
- **Collocazione UI nel LeadDetail** — Scelto: nuova sezione "Transcript" collassabile dopo le Attività, seguendo il pattern visivo esistente (Card + lista). Modal per aggiungere (come `LogActivityModal`).
|
||||||
|
- **Ordinamento** — `call_date DESC` (chiamata più recente in cima).
|
||||||
|
|
||||||
|
## Deferred Ideas
|
||||||
|
|
||||||
|
- UI transcript nella pagina admin cliente (`/admin/clients/[id]`) — la FK è pronta, la UI è deferred post-v2.2.
|
||||||
|
- Ricerca full-text sui transcript — fuori scope, i transcript vengono letti dall'AI in blocco.
|
||||||
|
- Trascrizione automatica da audio — fuori scope v2.2.
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { getActivityLog, getUpcomingReminders } from "@/lib/lead-service";
|
import { getActivityLog, getUpcomingReminders, getTranscripts } from "@/lib/lead-service";
|
||||||
import { getLeadsWithTags, getLeadFieldOptions } from "@/lib/admin-queries";
|
import { getLeadsWithTags, getLeadFieldOptions } from "@/lib/admin-queries";
|
||||||
import { LeadDetail } from "@/components/admin/leads/LeadDetail";
|
import { LeadDetail } from "@/components/admin/leads/LeadDetail";
|
||||||
|
|
||||||
@@ -17,8 +17,11 @@ export default async function LeadDetailPage({ params }: { params: Promise<{ id:
|
|||||||
notFound();
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
const activities = await getActivityLog(id);
|
const [activities, reminders, transcripts] = await Promise.all([
|
||||||
const reminders = await getUpcomingReminders(id);
|
getActivityLog(id),
|
||||||
|
getUpcomingReminders(id),
|
||||||
|
getTranscripts(id),
|
||||||
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LeadDetail
|
<LeadDetail
|
||||||
@@ -27,6 +30,7 @@ export default async function LeadDetailPage({ params }: { params: Promise<{ id:
|
|||||||
reminders={reminders}
|
reminders={reminders}
|
||||||
tags={lead.tags}
|
tags={lead.tags}
|
||||||
tagOptions={options.tags}
|
tagOptions={options.tags}
|
||||||
|
transcripts={transcripts}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { leads, quotes, tags } from "@/db/schema";
|
import { leads, quotes, tags, clientTranscripts } from "@/db/schema";
|
||||||
|
import { nanoid } from "nanoid";
|
||||||
import { eq, and } from "drizzle-orm";
|
import { eq, and } from "drizzle-orm";
|
||||||
import {
|
import {
|
||||||
createLeadSchema,
|
createLeadSchema,
|
||||||
@@ -252,3 +253,58 @@ export async function renameLeadTag(oldValue: string, newValue: string) {
|
|||||||
|
|
||||||
revalidatePath("/admin/leads");
|
revalidatePath("/admin/leads");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Transcript actions (Phase 20 — KB-02) ────────────────────────────────────
|
||||||
|
|
||||||
|
const addTranscriptSchema = z.object({
|
||||||
|
lead_id: z.string().min(1),
|
||||||
|
title: z.string().optional(),
|
||||||
|
content: z.string().min(1, "Il testo del transcript è obbligatorio"),
|
||||||
|
call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida (YYYY-MM-DD)"),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function addTranscript(data: z.infer<typeof addTranscriptSchema>) {
|
||||||
|
await requireAdmin();
|
||||||
|
|
||||||
|
const parsed = addTranscriptSchema.safeParse(data);
|
||||||
|
if (!parsed.success) {
|
||||||
|
return { success: false, error: parsed.error.issues[0].message };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [transcript] = await db
|
||||||
|
.insert(clientTranscripts)
|
||||||
|
.values({
|
||||||
|
id: nanoid(),
|
||||||
|
lead_id: parsed.data.lead_id,
|
||||||
|
title: parsed.data.title || null,
|
||||||
|
content: parsed.data.content,
|
||||||
|
call_date: parsed.data.call_date,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
revalidatePath(`/admin/leads/${parsed.data.lead_id}`);
|
||||||
|
return { success: true, transcript };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("addTranscript error:", error);
|
||||||
|
return { success: false, error: "Errore nel salvataggio del transcript" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteTranscript(transcriptId: string, leadId: string) {
|
||||||
|
await requireAdmin();
|
||||||
|
|
||||||
|
if (!transcriptId) throw new Error("ID transcript richiesto");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db
|
||||||
|
.delete(clientTranscripts)
|
||||||
|
.where(eq(clientTranscripts.id, transcriptId));
|
||||||
|
|
||||||
|
revalidatePath(`/admin/leads/${leadId}`);
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
console.error("deleteTranscript error:", error);
|
||||||
|
return { success: false, error: "Errore nell'eliminazione del transcript" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,17 +2,18 @@
|
|||||||
|
|
||||||
import { useState, useTransition } from "react";
|
import { useState, useTransition } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { Lead, Activity, Reminder } from "@/db/schema";
|
import { Lead, Activity, Reminder, ClientTranscript } from "@/db/schema";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { OptionMultiSelect } from "@/components/ui/option-multi-select";
|
import { OptionMultiSelect } from "@/components/ui/option-multi-select";
|
||||||
import { addLeadTag, removeLeadTag, renameLeadTag } from "@/app/admin/leads/actions";
|
import { addLeadTag, removeLeadTag, renameLeadTag, deleteTranscript } from "@/app/admin/leads/actions";
|
||||||
import { formatDistanceToNow, format } from "date-fns";
|
import { formatDistanceToNow, format } from "date-fns";
|
||||||
import { it } from "date-fns/locale";
|
import { it } from "date-fns/locale";
|
||||||
import { LogActivityModal } from "./LogActivityModal";
|
import { LogActivityModal } from "./LogActivityModal";
|
||||||
import { SendQuoteModal } from "./SendQuoteModal";
|
import { SendQuoteModal } from "./SendQuoteModal";
|
||||||
import { EditLeadModal } from "./LeadForm";
|
import { EditLeadModal } from "./LeadForm";
|
||||||
|
import { TranscriptModal } from "./TranscriptModal";
|
||||||
|
|
||||||
const ACTIVITY_ICON: Record<string, string> = {
|
const ACTIVITY_ICON: Record<string, string> = {
|
||||||
call: "📞",
|
call: "📞",
|
||||||
@@ -36,16 +37,20 @@ export function LeadDetail({
|
|||||||
reminders,
|
reminders,
|
||||||
tags,
|
tags,
|
||||||
tagOptions,
|
tagOptions,
|
||||||
|
transcripts,
|
||||||
}: {
|
}: {
|
||||||
lead: Lead;
|
lead: Lead;
|
||||||
activities: Activity[];
|
activities: Activity[];
|
||||||
reminders: Reminder[];
|
reminders: Reminder[];
|
||||||
tags: string[];
|
tags: string[];
|
||||||
tagOptions: string[];
|
tagOptions: string[];
|
||||||
|
transcripts: ClientTranscript[];
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [, startTransition] = useTransition();
|
const [, startTransition] = useTransition();
|
||||||
const [tagError, setTagError] = useState<string | null>(null);
|
const [tagError, setTagError] = useState<string | null>(null);
|
||||||
|
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
|
||||||
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
|
|
||||||
function run(fn: () => Promise<unknown>) {
|
function run(fn: () => Promise<unknown>) {
|
||||||
setTagError(null);
|
setTagError(null);
|
||||||
@@ -59,6 +64,29 @@ export function LeadDetail({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toggleExpand(id: string) {
|
||||||
|
setExpandedIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(id)) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDeleteTranscript(transcriptId: string) {
|
||||||
|
setDeletingId(transcriptId);
|
||||||
|
startTransition(async () => {
|
||||||
|
try {
|
||||||
|
await deleteTranscript(transcriptId, lead.id);
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
console.error("deleteTranscript error:", e);
|
||||||
|
} finally {
|
||||||
|
setDeletingId(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{/* Header + Actions */}
|
{/* Header + Actions */}
|
||||||
@@ -69,6 +97,7 @@ export function LeadDetail({
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<LogActivityModal leadId={lead.id} />
|
<LogActivityModal leadId={lead.id} />
|
||||||
|
<TranscriptModal leadId={lead.id} />
|
||||||
<SendQuoteModal leadId={lead.id} />
|
<SendQuoteModal leadId={lead.id} />
|
||||||
<EditLeadModal lead={lead} />
|
<EditLeadModal lead={lead} />
|
||||||
</div>
|
</div>
|
||||||
@@ -194,6 +223,73 @@ export function LeadDetail({
|
|||||||
)}
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Transcript Call */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="flex flex-row items-center justify-between">
|
||||||
|
<CardTitle>Transcript Call</CardTitle>
|
||||||
|
<span className="text-sm text-gray-500">
|
||||||
|
{transcripts.length} {transcripts.length === 1 ? "transcript" : "transcript"}
|
||||||
|
</span>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{transcripts.length > 0 ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{transcripts.map((t) => {
|
||||||
|
const isExpanded = expandedIds.has(t.id);
|
||||||
|
const formattedDate = format(
|
||||||
|
new Date(t.call_date + "T00:00:00"),
|
||||||
|
"d MMMM yyyy",
|
||||||
|
{ locale: it }
|
||||||
|
);
|
||||||
|
const lines = t.content.split("\n");
|
||||||
|
const preview = lines.slice(0, 3).join("\n").slice(0, 200);
|
||||||
|
const hasMore = t.content.length > preview.length || lines.length > 3;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={t.id} className="border-l-4 border-purple-300 pl-4 pb-4">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="font-medium text-sm">{formattedDate}</span>
|
||||||
|
{t.title && (
|
||||||
|
<span className="text-gray-600 text-sm">— {t.title}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-sm text-gray-700 whitespace-pre-wrap">
|
||||||
|
{isExpanded ? t.content : preview}
|
||||||
|
{!isExpanded && hasMore && (
|
||||||
|
<span className="text-gray-400">...</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{hasMore && (
|
||||||
|
<button
|
||||||
|
onClick={() => toggleExpand(t.id)}
|
||||||
|
className="text-xs text-blue-600 hover:underline mt-1"
|
||||||
|
>
|
||||||
|
{isExpanded ? "Mostra meno" : "Mostra tutto"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-600 hover:text-red-700 shrink-0"
|
||||||
|
disabled={deletingId === t.id}
|
||||||
|
onClick={() => handleDeleteTranscript(t.id)}
|
||||||
|
>
|
||||||
|
{deletingId === t.id ? "..." : "Elimina"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-gray-500 text-sm">Nessun transcript registrato</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { addTranscript } from "@/app/admin/leads/actions";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import {
|
||||||
|
Form,
|
||||||
|
FormControl,
|
||||||
|
FormField,
|
||||||
|
FormItem,
|
||||||
|
FormLabel,
|
||||||
|
FormMessage,
|
||||||
|
} from "@/components/ui/form";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
const transcriptSchema = z.object({
|
||||||
|
lead_id: z.string().min(1),
|
||||||
|
title: z.string().optional(),
|
||||||
|
content: z.string().min(1, "Il testo del transcript è obbligatorio"),
|
||||||
|
call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida"),
|
||||||
|
});
|
||||||
|
|
||||||
|
type TranscriptInput = z.infer<typeof transcriptSchema>;
|
||||||
|
|
||||||
|
export function TranscriptModal({ leadId }: { leadId: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const form = useForm<TranscriptInput>({
|
||||||
|
resolver: zodResolver(transcriptSchema),
|
||||||
|
defaultValues: {
|
||||||
|
lead_id: leadId,
|
||||||
|
title: "",
|
||||||
|
content: "",
|
||||||
|
call_date: new Date().toISOString().split("T")[0],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
async function onSubmit(data: TranscriptInput) {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const result = await addTranscript(data);
|
||||||
|
if (result.success) {
|
||||||
|
setOpen(false);
|
||||||
|
form.reset({
|
||||||
|
lead_id: leadId,
|
||||||
|
title: "",
|
||||||
|
content: "",
|
||||||
|
call_date: new Date().toISOString().split("T")[0],
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setError(result.error ?? "Errore nel salvataggio");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={setOpen}>
|
||||||
|
<DialogTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm">
|
||||||
|
Aggiungi Transcript
|
||||||
|
</Button>
|
||||||
|
</DialogTrigger>
|
||||||
|
<DialogContent className="max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Aggiungi Transcript Call</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="call_date"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Data call</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input type="date" {...field} value={field.value || ""} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="title"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Titolo (opzionale)</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input
|
||||||
|
placeholder="es. Discovery call"
|
||||||
|
{...field}
|
||||||
|
value={field.value || ""}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="content"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Transcript</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Textarea
|
||||||
|
placeholder="Incolla qui il testo del transcript..."
|
||||||
|
className="min-h-48 resize-y"
|
||||||
|
{...field}
|
||||||
|
value={field.value || ""}
|
||||||
|
/>
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error && <p className="text-sm text-red-600">{error}</p>}
|
||||||
|
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Salvataggio..." : "Salva Transcript"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
-- Phase 20: Knowledge Base Cliente — tabella transcript datati per lead/cliente
|
||||||
|
-- Additive only. No drops/truncates (Data Safety LOCKED).
|
||||||
|
-- Applicare a prod via SSH tunnel PRIMA di pushare il codice dipendente (D-03).
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS client_transcripts (
|
||||||
|
id text PRIMARY KEY NOT NULL,
|
||||||
|
lead_id text REFERENCES leads(id) ON DELETE CASCADE,
|
||||||
|
client_id text REFERENCES clients(id) ON DELETE CASCADE,
|
||||||
|
title text,
|
||||||
|
content text NOT NULL,
|
||||||
|
call_date date NOT NULL,
|
||||||
|
created_at timestamp with time zone NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_lead_id_idx
|
||||||
|
ON client_transcripts (lead_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_client_id_idx
|
||||||
|
ON client_transcripts (client_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS client_transcripts_call_date_idx
|
||||||
|
ON client_transcripts (call_date DESC);
|
||||||
@@ -498,10 +498,31 @@ export const reminders = pgTable("reminders", {
|
|||||||
.defaultNow(),
|
.defaultNow(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ============ CLIENT TRANSCRIPTS TABLE (Knowledge Base — Phase 20) ============
|
||||||
|
// Transcript datati delle call, multipli per lead o cliente.
|
||||||
|
// lead_id e client_id sono entrambi nullable (D-01): un transcript può appartenere
|
||||||
|
// a un lead pre-conversione (Phase 20 UI) o a un cliente post-conversione (futuro).
|
||||||
|
export const clientTranscripts = pgTable("client_transcripts", {
|
||||||
|
id: text("id")
|
||||||
|
.primaryKey()
|
||||||
|
.$defaultFn(() => nanoid()),
|
||||||
|
lead_id: text("lead_id")
|
||||||
|
.references(() => leads.id, { onDelete: "cascade" }),
|
||||||
|
client_id: text("client_id")
|
||||||
|
.references(() => clients.id, { onDelete: "cascade" }),
|
||||||
|
title: text("title"),
|
||||||
|
content: text("content").notNull(),
|
||||||
|
call_date: text("call_date").notNull(), // "YYYY-MM-DD" — coerente con <input type="date">
|
||||||
|
created_at: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
// ============ RELATIONS ============
|
// ============ RELATIONS ============
|
||||||
|
|
||||||
export const clientsRelations = relations(clients, ({ many }) => ({
|
export const clientsRelations = relations(clients, ({ many }) => ({
|
||||||
projects: many(projects),
|
projects: many(projects),
|
||||||
|
transcripts: many(clientTranscripts),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const projectsRelations = relations(projects, ({ one, many }) => ({
|
export const projectsRelations = relations(projects, ({ one, many }) => ({
|
||||||
@@ -632,6 +653,7 @@ export const leadsRelations = relations(leads, ({ many }) => ({
|
|||||||
quotes: many(quotes),
|
quotes: many(quotes),
|
||||||
activities: many(activities),
|
activities: many(activities),
|
||||||
reminders: many(reminders),
|
reminders: many(reminders),
|
||||||
|
transcripts: many(clientTranscripts),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
export const activitiesRelations = relations(activities, ({ one }) => ({
|
export const activitiesRelations = relations(activities, ({ one }) => ({
|
||||||
@@ -642,6 +664,17 @@ export const remindersRelations = relations(reminders, ({ one }) => ({
|
|||||||
lead: one(leads, { fields: [reminders.lead_id], references: [leads.id] }),
|
lead: one(leads, { fields: [reminders.lead_id], references: [leads.id] }),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
export const clientTranscriptsRelations = relations(clientTranscripts, ({ one }) => ({
|
||||||
|
lead: one(leads, {
|
||||||
|
fields: [clientTranscripts.lead_id],
|
||||||
|
references: [leads.id],
|
||||||
|
}),
|
||||||
|
client: one(clients, {
|
||||||
|
fields: [clientTranscripts.client_id],
|
||||||
|
references: [clients.id],
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
export const quotesRelations = relations(quotes, ({ one, many }) => ({
|
export const quotesRelations = relations(quotes, ({ one, many }) => ({
|
||||||
lead: one(leads, { fields: [quotes.lead_id], references: [leads.id] }),
|
lead: one(leads, { fields: [quotes.lead_id], references: [leads.id] }),
|
||||||
client: one(clients, { fields: [quotes.client_id], references: [clients.id] }),
|
client: one(clients, { fields: [quotes.client_id], references: [clients.id] }),
|
||||||
@@ -705,3 +738,5 @@ export type Activity = typeof activities.$inferSelect;
|
|||||||
export type NewActivity = typeof activities.$inferInsert;
|
export type NewActivity = typeof activities.$inferInsert;
|
||||||
export type Reminder = typeof reminders.$inferSelect;
|
export type Reminder = typeof reminders.$inferSelect;
|
||||||
export type NewReminder = typeof reminders.$inferInsert;
|
export type NewReminder = typeof reminders.$inferInsert;
|
||||||
|
export type ClientTranscript = typeof clientTranscripts.$inferSelect;
|
||||||
|
export type NewClientTranscript = typeof clientTranscripts.$inferInsert;
|
||||||
+11
-1
@@ -1,6 +1,6 @@
|
|||||||
import { eq, and, isNull, desc, gte, lte, ilike, or } from "drizzle-orm";
|
import { eq, and, isNull, desc, gte, lte, ilike, or } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { leads, activities, reminders, quotes } from "@/db/schema";
|
import { leads, activities, reminders, quotes, clientTranscripts } from "@/db/schema";
|
||||||
|
|
||||||
// Get all leads
|
// Get all leads
|
||||||
export async function getAllLeads(limit: number = 100, offset: number = 0) {
|
export async function getAllLeads(limit: number = 100, offset: number = 0) {
|
||||||
@@ -209,3 +209,13 @@ export async function getQuotesByLeadId(leadId: string) {
|
|||||||
.where(eq(quotes.lead_id, leadId))
|
.where(eq(quotes.lead_id, leadId))
|
||||||
.orderBy(desc(quotes.created_at));
|
.orderBy(desc(quotes.created_at));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get transcript log for a lead — call_date DESC (D-05)
|
||||||
|
// Returns all fields including full content (Phase 21 reads them in bulk).
|
||||||
|
export async function getTranscripts(leadId: string) {
|
||||||
|
return await db
|
||||||
|
.select()
|
||||||
|
.from(clientTranscripts)
|
||||||
|
.where(eq(clientTranscripts.lead_id, leadId))
|
||||||
|
.orderBy(desc(clientTranscripts.call_date));
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user