# Changelog - Gloria Platform

Todos los cambios notables del proyecto Gloria se documentarán en este archivo.

El formato se basa en [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
y este proyecto adhiere a [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.4.0] - 2026-02-01 - Sprint 4: Pagos y Roles (100% Completado)

### Added

#### Database Schema (100% Completado)

- **New Models:**
  - **User** - id, email, phone, name, role, password, timestamps
  - **Payment** - id, appointmentId, userId, amount, status, proofUrl, approvedBy, approvedAt, rejectedReason, rejectedAt, timestamps
  - **PatientFile** - id, patientId, type (ID_CARD, INSURANCE, OTHER), filename, url, expiresAt, timestamps
- **Updated Patient model** - Added files relation
  - **Updated Appointment model** - Added paymentId relation and payment relation

**Migrations:**

- Database schema updated with prisma db push
- Seed script created with test users (therapist, assistant, patient)

**Files:**

- `prisma/schema.prisma` - Updated schema
- `prisma/seed.ts` - Seed script with test users

#### RBAC & Authentication (100% Completado)

- `src/middleware/auth.ts` - Authentication middleware
  - `withAuth` function - Middleware for authentication
  - `setAuthCookies` - Set auth cookies
  - `clearAuthCookies` - Clear auth cookies
  - `checkRouteAccess` - Route configuration
  - Roles: PATIENT, ASSISTANT, THERAPIST

- **`src/lib/auth/rbac.ts`** - RBAC route configuration

#### Auth Endpoints (100% Completado)

- **POST /api/auth/login** - Login with phone/password
- **POST /api/auth/logout** - Logout
- **GET /api/users/me** - Get current user

**Files:**

- `src/app/api/auth/login/route.ts`
- `src/app/api/auth/logout/route.ts`
- `src/app/api/users/me/route.ts`

#### Dashboard Terapeuta (100% Completado)

**GET /api/dashboard/patients/[phone]/notes** - Patient clinical notes
**GET /api/dashboard/patients/[phone]/appointments** - Patient appointments

**Files:**

- `src/app/api/dashboard/patients/[phone]/notes/route.ts`
- `src/app/api/dashboard/patients/[phone]/appointments/route.ts`
- `src/app/dashboard/therapista/page.tsx` - Dashboard Therapist UI

#### Dashboard Asistente (100% Completado)

- **GET /api/dashboard/appointments** - List upcoming appointments
- **GET /api/dashboard/payments/pending** - List pending payments
- **POST /api/payments/validate** - Approve/reject payments

**Files:**

- `src/app/api/dashboard/appointments/route.ts`
- `src/app/api/dashboard/payments/pending/route.ts`
- `src/app/api/payments/validate/route.ts`
- `src/app/dashboard/assistant/page.tsx` - Dashboard Assistant UI

#### Pages (100% Completado)

- **Login page** (`/app/login/page.tsx`) - Form with test credentials shown
- **Servicios page** (`/app/servicios/page.tsx`) - Detailed services list
- **Privacidad page** (`/app/privacidad/page.tsx`) - Privacy policy
- **Cursos page** (`/app/cursos/page.tsx`) - Courses and workshops

**Files:**

- `src/app/login/page.tsx`
- `src/app/servicios/page.tsx`
- `src/app/privacidad/page.tsx`
- `src/app/cursos/page.tsx`

#### Header & Footer Updates

**Updated:**

- `src/components/layout/Header.tsx` - Added /cursos link to navigation
- `src/components/layout/Footer.tsx` - Added /servicios, /cursos, /privacidad links to footer

### Changed

#### Infrastructure

- `prisma/schema.prisma` - Added User, Payment, PatientFile models
- `src/middleware/auth.ts` - Created auth middleware with RBAC
- `src/lib/auth/rbac.ts` - Route configuration
- `prisma/seed.ts` - Seed script

#### Pages

- `src/app/login/page.tsx` - Created login page
- `src/app/servicios/page.tsx` - Created services page
- `src/app/privacidad/page.tsx` - Created privacy page
- `src/app/cursos/page.tsx` - Created courses page

#### Dashboard API

- `src/app/api/dashboard/appointments/route.ts` - Appointments API
- `src/app/api/dashboard/payments/pending/route.ts` - Pending payments API
- `src/app/api/payments/validate/route.ts` - Payment validation API
- `src/app/api/dashboard/patients/[phone]/notes/route.ts` - Patient notes API
- `src/app/api/dashboard/patients/[phone]/appointments/route.ts` - Patient appointments API

#### Dashboard Pages

- `src/app/dashboard/assistant/page.tsx` - Assistant dashboard
- `src/app/dashboard/therapist/page.tsx` - Therapist dashboard

### Components

- `src/components/layout/Hero.tsx` - Fixed "Ver Servicios" button colors

### Fixed

- Fixed TypeScript errors in auth middleware return types
- Fixed Hero button "Ver Servicios" text color on hover and active states

### Tests

- ✅ TypeScript typecheck - No errors
- ✅ Prisma schema valid
- ✅ Database seed executed successfully

---

## [Unreleased] - Sprint 5: Voz y Notas Clínicas

### Planned

- Audio sandbox implementation
- Clinical notes with rich text editor
- WhatsApp audio integration
- Auto-deletion of audio (7 days)

---

## [0.3.0] - 2026-02-01 - Sprint 3: Triaje de Crisis y Agenda

### Added

#### Crisis Evaluation Engine (100% Completado)

- **POST /api/crisis/evaluate** - Crisis evaluation endpoint
- Keyword detection algorithm with scoring system
- Pre-defined responses per crisis level
- Rate limiting by IP and phone

#### Google Calendar Integration (100% Completado)

- **POST /api/calendar/availability** - Get availability
- **POST /api/calendar/create-event** - Create calendar event
- Distributed lock system with 15min TTL
- Google Calendar API integration (googleapis 140.0.0, google-auth-library 9.7.0)

#### Frontend Calendar (100% Completado)

- Updated Booking.tsx with Steps 4-6
- Calendar interactive UI with week navigation
- Date input with validation
- Time slots display with status
- Success confirmation screen

### Files Created

- `src/app/api/crisis/evaluate/route.ts` - Crisis evaluation endpoint
- `src/app/api/calendar/availability/route.ts` - Availability API
- `src/app/api/calendar/create-event/route.ts` - Event creation API
- `src/infrastructure/external/calendar.ts` - Google Calendar client
- `src/infrastructure/cache/redis.ts` - Redis cache and locks
- Updated `src/components/layout/Booking.tsx` - Steps 4-6 added

### Fixed

- Fixed TypeScript errors in crisis/evaluate and calendar routes
- Fixed duplicate `score` field in crisis evaluation response
- Fixed `reminders` structure in calendar event creation

---

## [0.2.0] - 2026-02-01 - Sprint 2: Identidad Phone-First

### Added

#### Patient Registration (100% Completado)

- **POST /api/patients/register** - Register new patient
- **POST /api/patients/search** - Search patient by phone

#### Landing Page Components (100% Completado)

- Header component with navigation
- Hero section with call-to-action
- About section with Gloria's biography
- Services grid with 3 services
- Testimonials carousel
- Contact form
- Footer with links

### Files Created

- `src/app/api/patients/register/route.ts`
- `src/app/api/patients/search/route.ts`
- `src/components/layout/Header.tsx`
- `src/components/layout/Hero.tsx`
- `src/components/layout/About.tsx`
- `src/components/layout/Services.tsx`
- `src/components/layout/Testimonials.tsx`
- `src/components/layout/Contact.tsx`
- `src/components/layout/Footer.tsx`
- `src/components/layout/Booking.tsx` - Booking flow (Steps 1-3)

### Fixed

- Fixed image paths in components
- Fixed TypeScript errors in patient registration
- Fixed Hero button "Ver Servicios" color behavior

---

## [0.1.0] - 2026-02-01 - Sprint 1: Cimientos e Infraestructura

### Added

#### Project Setup (100% Completado)

- Next.js 14 with App Router and TypeScript 5.x
- Tailwind CSS with Nano Banana palette
- Prisma ORM with SQLite
- Shadcn/ui components (Radix UI based)
- Framer Motion for animations

#### Infrastructure (100% Completado)

- Docker multi-stage setup (dev/prod)
- docker-compose configuration
- Non-root user configuration (UID 1001 - appuser)
- Security middleware (Helmet.js, CORS, CSP)

#### Database (100% Completado)

- Initial Prisma schema (Patient, Appointment, ClinicalNote, VoiceNote)
- Initial migration applied

#### Documentation (100% Completado)

- PRD.md - Product Requirements Document
- README.md - Project overview
- PROGRESS.md - Sprint tracking
- TASKS.md - Task list
- CHANGELOG.md - Changelog
- site_requirements.md - Style guide and specs
- AGENTS.md - Team roles and personas

#### Frontend Setup (100% Completado)

- Root layout with global styles
- Home page with all sections
- Component library (Button, Input, Card)

---

## [0.5.0] - Próximamente - Sprint 3/4 Completación (Planificado)

### Sprint 3 - Pendiente Implementación (10%)

#### Servicios de Email SMTP

**To Add:**

- `nodemailer` integration for SMTP email sending
- TLS transport configuration
- Connection pooling for efficiency
- HTML email templates
- Retry mechanism for failed emails

**New Environment Variables:**

```env
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
SMTP_FROM_NAME=Gloria Niño - Terapia
SMTP_FROM_EMAIL=no-reply@glorianino.com
ADMIN_EMAIL=admin@glorianino.com
```

**New Files:**

- `src/infrastructure/email/smtp.ts` - SMTP client
- `src/lib/email/templates/` - Email templates directory

#### Funcionalidad de Reacomodar Citas

**To Add:**

- "Reacomodar" button in assistant and therapist dashboards
- Modal for selecting new date/time
- Availability check with Google Calendar API
- Update event in Google Calendar and SQLite
- Invalidate availability cache in Redis
- Send confirmation email to patient

**New Files:**

- `src/app/api/calendar/reschedule/route.ts` - API endpoint
- `src/components/dashboard/RescheduleModal.tsx` - Modal component
- `src/lib/email/templates/reschedule-confirmation.ts` - Email template

**Modified Files:**

- `src/app/dashboard/asistente/page.tsx` - Add "Reacomodar" button
- `src/app/dashboard/terapeuta/page.tsx` - Add "Reacomodar" button
- `src/infrastructure/external/calendar.ts` - Add `updateEvent()` function
- `src/infrastructure/email/smtp.ts` - Add `sendRescheduleConfirmation()` function

#### Job Programado - Email Diario 10 PM

**To Add:**

- Scheduled job with `node-cron` (0 22 \* \* \*)
- Query next day's appointments from SQLite
- Send daily agenda email to admin (Gloria) only
- HTML table format with: Time, Patient name, Phone, Type, Payment status
- Logging of each execution

**New Files:**

- `src/jobs/send-daily-agenda.ts` - Scheduled job
- `src/lib/email/templates/daily-agenda.ts` - HTML template
- `src/app/api/jobs/trigger-agenda/route.ts` - Manual trigger for testing

**Modified Files:**

- `src/app/layout.tsx` - Initialize job on server start
- `src/infrastructure/email/smtp.ts` - Add `sendDailyAgenda()` function

---

### Sprint 4 - Pendiente Implementación (15%)

#### Upload de Comprobantes con OCR (Híbrido)

**To Add:**

- Upload endpoint for payment proofs (PDF, JPG, PNG, max 5MB)
- Client-side preprocessing (grayscale, contrast, resize)
- Server-side OCR processing with `tesseract.js`
- PDF text extraction with `pdf-parse`
- Regex patterns to extract data from any bank:
  - Amount
  - Transfer date
  - Reference/Key
  - Sender name
  - Sender bank
- Unique filename generation: `payment_{appointmentId}_{timestamp}.{ext}`
- Store in `/public/uploads/payments/`
- Save extracted data in Payment model
- Return file URL and extracted data with confidence percentage

**New Dependencies:**

```bash
pnpm add tesseract.js sharp pdf-parse @types/nodemailer
```

**New Files:**

- `src/app/api/payments/upload-proof/route.ts` - Upload API endpoint
- `src/lib/ocr/processor.ts` - OCR processor (server)
- `src/lib/ocr/templates.ts` - Extraction templates
- `src/components/dashboard/PaymentUpload.tsx` - Upload component with drag & drop
- `src/lib/utils/ocr-client.ts` - Client-side preprocessing (optional)

**Modified Files:**

- `prisma/schema.prisma` - Add OCR-extracted fields to Payment model:

  ```prisma
  model Payment {
    // ... existing fields

    // Datos extraídos por OCR
    extractedDate        DateTime?
    extractedAmount      Float?
    extractedReference   String? // Clave de transferencia
    extractedSenderName  String?
    extractedSenderBank  String?
  }
  ```

- `src/app/dashboard/asistente/page.tsx` - Integrate PaymentUpload component

#### Botón "Ver Más Servicios" en Landing

**To Change:**

- Update "Agenda tu Primera Sesión" button in Services component
- Change to "Ver Más Servicios" button
- Link to `/servicios` page
- Maintain Nano Banana design and animations

**Modified Files:**

- `src/components/layout/Services.tsx` - Line 136-144

#### Contacto Específico para Cursos

**To Add:**

- Contact form in `/cursos` page
- Fields: Name, Email, Course of interest (dropdown), Message
- Save record in SQLite
- Send notification email to admin
- Consistent Nano Banana design
- Smooth animations with Framer Motion
- Update "Más Información" buttons to open modal or scroll to contact section

**New Files:**

- `src/app/api/contact/courses/route.ts` - API endpoint for course inquiries
- `src/lib/email/templates/course-inquiry.ts` - HTML notification template

**Modified Files:**

- `src/app/cursos/page.tsx` - Add contact section at the end

---

### Dependencies to Add

```bash
pnpm add nodemailer node-cron tesseract.js sharp pdf-parse @types/nodemailer
```

| Package             | Use                                   | Sprint |
| ------------------- | ------------------------------------- | ------ |
| `nodemailer`        | Send emails via SMTP                  | 3      |
| `node-cron`         | Scheduled job for daily emails        | 3      |
| `tesseract.js`      | OCR for extracting text from images   | 4      |
| `sharp`             | Pre-process images (optimize for OCR) | 4      |
| `pdf-parse`         | Extract text from PDFs                | 4      |
| `@types/nodemailer` | TypeScript definitions                | 3      |

---

### Estimated Timeline

| Phase | Task                    | Priority | Estimated |
| ----- | ----------------------- | -------- | --------- |
| 1.1   | Configure SMTP          | High     | 1-2 hours |
| 1.2   | Reschedule appointments | High     | 3-4 hours |
| 1.3   | Daily email 10 PM       | High     | 2-3 hours |
| 2.1   | Services button         | Low      | 30 min    |
| 2.2   | Courses contact         | Medium   | 2-3 hours |
| 2.3   | Upload with OCR         | High     | 4-5 hours |

**Total Estimated:** 13-18 hours

---

### Testing Checklist

#### Sprint 3

- [ ] SMTP test: send test email
- [ ] Reschedule test: change appointment and verify email sent
- [ ] Manual job test: trigger endpoint and verify daily email
- [ ] Scheduled job test: wait for 10 PM and verify automatic email

#### Sprint 4

- [ ] Services button test: navigate to /servicios
- [ ] Courses contact test: send inquiry and verify email
- [ ] Upload PDF test: upload, OCR, data extraction
- [ ] Upload JPG test: upload, OCR, data extraction
- [ ] Validation test: attempt to upload invalid file (type/size)
- [ ] Drag & drop test: drag file to upload component

---

### Important Notes

1. **WhatsApp Reminders:** NOT implementing to avoid Meta bans. Reminders are handled through:
   - Google Calendar (email 24h before - already implemented in Sprint 3)
   - Daily email at 10 PM to admin with next day's agenda (pending)

2. **Reschedule Appointments:** Flow with confirmation sent (email to patient). The change is automatic upon receiving the email.

3. **Payment Proof Upload:** Hybrid approach (client-side preprocessing, server-side OCR) to extract data from any bank without specific templates.

4. **Daily Email:** Sent only to admin (Gloria), NOT to assistant. Time: 10 PM (configurable for timezone).

5. **Data to Extract from Proof:** Amount, Transfer date, Reference/Key, Sender name, Sender bank.

---

## [0.5.0] - 2026-02-02 - Sprint 3/4 Completado

### Added

#### Email SMTP Service (Sprint 3)

- SMTP configuration with nodemailer (TLS transport, connection pooling)
- Email templates HTML:
  - Reschedule confirmation (`src/lib/email/templates/reschedule-confirmation.ts`)
  - Daily agenda report (`src/lib/email/templates/daily-agenda.ts`)
  - Course inquiry notification (`src/lib/email/templates/course-inquiry.ts`)
- Email client with retry logic and exponential backoff (`src/infrastructure/email/smtp.ts`)

#### Reschedule Appointments (Sprint 3)

- API endpoint POST /api/calendar/reschedule
- Reschedule modal component (`src/components/dashboard/RescheduleModal.tsx`)
- Google Calendar `updateEvent()` function
- Email confirmation to patient on reschedule
- Availability validation before rescheduling

#### Daily Agenda Job (Sprint 3)

- Scheduled job with node-cron (`src/jobs/send-daily-agenda.ts`)
- Manual trigger endpoint POST /api/jobs/trigger-agenda
- Daily email at 10 PM to admin with next day's agenda
- HTML table with: time, patient name, phone, type, payment status

#### Payment Proof Upload with OCR (Sprint 4)

- API endpoint POST /api/payments/upload-proof
- OCR processor with tesseract.js (`src/lib/ocr/processor.ts`)
- Regex patterns for data extraction:
  - Amount
  - Transfer date
  - Reference/Key
  - Sender name
  - Sender bank
- PDF text extraction with pdf-parse
- Drag & drop upload component (`src/components/dashboard/PaymentUpload.tsx`)
- Extracted data displayed with edit option

#### Database Schema Updates (Sprint 4)

- Added `eventId` field to Appointment model
- Added OCR-extracted fields to Payment model:
  - `extractedDate` - DateTime
  - `extractedAmount` - Float
  - `extractedReference` - String
  - `extractedSenderName` - String
  - `extractedSenderBank` - String
  - `confidence` - Float

#### Course Contact Form (Sprint 4)

- API endpoint POST /api/contact/courses
- Contact form component (`src/components/forms/CourseContactForm.tsx`)
- Course inquiry form on /cursos page
- Email notification to admin on course inquiry

#### Dashboard Updates (Sprint 3/4)

- Added "Reacomodar" button to Assistant dashboard
- Added "Reacomodar" button to Therapist dashboard
- Integrated PaymentUpload component in Assistant dashboard for pending payments
- Updated /cursos page with contact form section

#### Other Changes

- Updated Services component "Ver Más Servicios" button to navigate to /servicios
- Added new environment variables for SMTP configuration
- Imported daily agenda job in layout.tsx for automatic initialization

### Changed

- Updated Prisma schema with new fields
- Updated env validation schema with SMTP variables
- Updated dashboard UI for better UX with reschedule and upload features

### Fixed

- Fixed pdf-parse import issue (using require for CommonJS module)
- Fixed TypeScript errors in new components

### Tests

- ✅ TypeScript typecheck - No errors
- ✅ ESLint - Only warnings (img tags, react-hooks)
- ✅ Production build successful

---

## [0.0.1] - 2026-01-15 - Initial Release

### Initial Release

- Project scaffolding with Next.js 14
- Database schema definition
- Basic authentication structure
- Landing page implementation
- Docker configuration

---

**Full Changelog:** See [CHANGELOG.md](./CHANGELOG.md)
