commit a0ccb8ca641d9d6238b565b38e6ef893feacdb78 Author: Kilian Date: Thu Apr 30 10:09:44 2026 +0100 Initial commit: monorepo Naturcalabacera reservas (apps/api + apps/web + packages/shared) diff --git a/.agents/skills/supabase-postgres-best-practices/SKILL.md b/.agents/skills/supabase-postgres-best-practices/SKILL.md new file mode 100644 index 0000000..d9ef194 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/SKILL.md @@ -0,0 +1,64 @@ +--- +name: supabase-postgres-best-practices +description: Postgres performance optimization and best practices from Supabase. Use this skill when writing, reviewing, or optimizing Postgres queries, schema designs, or database configurations. +license: MIT +metadata: + author: supabase + version: "1.1.1" + organization: Supabase + date: January 2026 + abstract: Comprehensive Postgres performance optimization guide for developers using Supabase and Postgres. Contains performance rules across 8 categories, prioritized by impact from critical (query performance, connection management) to incremental (advanced features). Each rule includes detailed explanations, incorrect vs. correct SQL examples, query plan analysis, and specific performance metrics to guide automated optimization and code generation. +--- + +# Supabase Postgres Best Practices + +Comprehensive performance optimization guide for Postgres, maintained by Supabase. Contains rules across 8 categories, prioritized by impact to guide automated query optimization and schema design. + +## When to Apply + +Reference these guidelines when: +- Writing SQL queries or designing schemas +- Implementing indexes or query optimization +- Reviewing database performance issues +- Configuring connection pooling or scaling +- Optimizing for Postgres-specific features +- Working with Row-Level Security (RLS) + +## Rule Categories by Priority + +| Priority | Category | Impact | Prefix | +|----------|----------|--------|--------| +| 1 | Query Performance | CRITICAL | `query-` | +| 2 | Connection Management | CRITICAL | `conn-` | +| 3 | Security & RLS | CRITICAL | `security-` | +| 4 | Schema Design | HIGH | `schema-` | +| 5 | Concurrency & Locking | MEDIUM-HIGH | `lock-` | +| 6 | Data Access Patterns | MEDIUM | `data-` | +| 7 | Monitoring & Diagnostics | LOW-MEDIUM | `monitor-` | +| 8 | Advanced Features | LOW | `advanced-` | + +## How to Use + +Read individual rule files for detailed explanations and SQL examples: + +``` +references/query-missing-indexes.md +references/query-partial-indexes.md +references/_sections.md +``` + +Each rule file contains: +- Brief explanation of why it matters +- Incorrect SQL example with explanation +- Correct SQL example with explanation +- Optional EXPLAIN output or metrics +- Additional context and references +- Supabase-specific notes (when applicable) + +## References + +- https://www.postgresql.org/docs/current/ +- https://supabase.com/docs +- https://wiki.postgresql.org/wiki/Performance_Optimization +- https://supabase.com/docs/guides/database/overview +- https://supabase.com/docs/guides/auth/row-level-security diff --git a/.agents/skills/supabase-postgres-best-practices/references/_contributing.md b/.agents/skills/supabase-postgres-best-practices/references/_contributing.md new file mode 100644 index 0000000..ac7da39 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/_contributing.md @@ -0,0 +1,170 @@ +# Writing Guidelines for Postgres References + +This document provides guidelines for creating effective Postgres best +practice references that work well with AI agents and LLMs. + +## Key Principles + +### 1. Concrete Transformation Patterns + +Show exact SQL rewrites. Avoid philosophical advice. + +**Good:** "Use `WHERE id = ANY(ARRAY[...])` instead of +`WHERE id IN (SELECT ...)`" **Bad:** "Design good schemas" + +### 2. Error-First Structure + +Always show the problematic pattern first, then the solution. This trains agents +to recognize anti-patterns. + +```markdown +**Incorrect (sequential queries):** [bad example] + +**Correct (batched query):** [good example] +``` + +### 3. Quantified Impact + +Include specific metrics. Helps agents prioritize fixes. + +**Good:** "10x faster queries", "50% smaller index", "Eliminates N+1" +**Bad:** "Faster", "Better", "More efficient" + +### 4. Self-Contained Examples + +Examples should be complete and runnable (or close to it). Include `CREATE TABLE` +if context is needed. + +```sql +-- Include table definition when needed for clarity +CREATE TABLE users ( + id bigint PRIMARY KEY, + email text NOT NULL, + deleted_at timestamptz +); + +-- Now show the index +CREATE INDEX users_active_email_idx ON users(email) WHERE deleted_at IS NULL; +``` + +### 5. Semantic Naming + +Use meaningful table/column names. Names carry intent for LLMs. + +**Good:** `users`, `email`, `created_at`, `is_active` +**Bad:** `table1`, `col1`, `field`, `flag` + +--- + +## Code Example Standards + +### SQL Formatting + +```sql +-- Use lowercase keywords, clear formatting +CREATE INDEX CONCURRENTLY users_email_idx + ON users(email) + WHERE deleted_at IS NULL; + +-- Not cramped or ALL CAPS +CREATE INDEX CONCURRENTLY USERS_EMAIL_IDX ON USERS(EMAIL) WHERE DELETED_AT IS NULL; +``` + +### Comments + +- Explain _why_, not _what_ +- Highlight performance implications +- Point out common pitfalls + +### Language Tags + +- `sql` - Standard SQL queries +- `plpgsql` - Stored procedures/functions +- `typescript` - Application code (when needed) +- `python` - Application code (when needed) + +--- + +## When to Include Application Code + +**Default: SQL Only** + +Most references should focus on pure SQL patterns. This keeps examples portable. + +**Include Application Code When:** + +- Connection pooling configuration +- Transaction management in application context +- ORM anti-patterns (N+1 in Prisma/TypeORM) +- Prepared statement usage + +**Format for Mixed Examples:** + +````markdown +**Incorrect (N+1 in application):** + +```typescript +for (const user of users) { + const posts = await db.query("SELECT * FROM posts WHERE user_id = $1", [ + user.id, + ]); +} +``` +```` + +**Correct (batch query):** + +```typescript +const posts = await db.query("SELECT * FROM posts WHERE user_id = ANY($1)", [ + userIds, +]); +``` + +--- + +## Impact Level Guidelines + +| Level | Improvement | Use When | +|-------|-------------|----------| +| **CRITICAL** | 10-100x | Missing indexes, connection exhaustion, sequential scans on large tables | +| **HIGH** | 5-20x | Wrong index types, poor partitioning, missing covering indexes | +| **MEDIUM-HIGH** | 2-5x | N+1 queries, inefficient pagination, RLS optimization | +| **MEDIUM** | 1.5-3x | Redundant indexes, query plan instability | +| **LOW-MEDIUM** | 1.2-2x | VACUUM tuning, configuration tweaks | +| **LOW** | Incremental | Advanced patterns, edge cases | + +--- + +## Reference Standards + +**Primary Sources:** + +- Official Postgres documentation +- Supabase documentation +- Postgres wiki +- Established blogs (2ndQuadrant, Crunchy Data) + +**Format:** + +```markdown +Reference: +[Postgres Indexes](https://www.postgresql.org/docs/current/indexes.html) +``` + +--- + +## Review Checklist + +Before submitting a reference: + +- [ ] Title is clear and action-oriented +- [ ] Impact level matches the performance gain +- [ ] impactDescription includes quantification +- [ ] Explanation is concise (1-2 sentences) +- [ ] Has at least 1 **Incorrect** SQL example +- [ ] Has at least 1 **Correct** SQL example +- [ ] SQL uses semantic naming +- [ ] Comments explain _why_, not _what_ +- [ ] Trade-offs mentioned if applicable +- [ ] Reference links included +- [ ] `mise run test` passes diff --git a/.agents/skills/supabase-postgres-best-practices/references/_sections.md b/.agents/skills/supabase-postgres-best-practices/references/_sections.md new file mode 100644 index 0000000..8ba57c2 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/_sections.md @@ -0,0 +1,39 @@ +# Section Definitions + +This file defines the rule categories for Postgres best practices. Rules are automatically assigned to sections based on their filename prefix. + +Take the examples below as pure demonstrative. Replace each section with the actual rule categories for Postgres best practices. + +--- + +## 1. Query Performance (query) +**Impact:** CRITICAL +**Description:** Slow queries, missing indexes, inefficient query plans. The most common source of Postgres performance issues. + +## 2. Connection Management (conn) +**Impact:** CRITICAL +**Description:** Connection pooling, limits, and serverless strategies. Critical for applications with high concurrency or serverless deployments. + +## 3. Security & RLS (security) +**Impact:** CRITICAL +**Description:** Row-Level Security policies, privilege management, and authentication patterns. + +## 4. Schema Design (schema) +**Impact:** HIGH +**Description:** Table design, index strategies, partitioning, and data type selection. Foundation for long-term performance. + +## 5. Concurrency & Locking (lock) +**Impact:** MEDIUM-HIGH +**Description:** Transaction management, isolation levels, deadlock prevention, and lock contention patterns. + +## 6. Data Access Patterns (data) +**Impact:** MEDIUM +**Description:** N+1 query elimination, batch operations, cursor-based pagination, and efficient data fetching. + +## 7. Monitoring & Diagnostics (monitor) +**Impact:** LOW-MEDIUM +**Description:** Using pg_stat_statements, EXPLAIN ANALYZE, metrics collection, and performance diagnostics. + +## 8. Advanced Features (advanced) +**Impact:** LOW +**Description:** Full-text search, JSONB optimization, PostGIS, extensions, and advanced Postgres features. diff --git a/.agents/skills/supabase-postgres-best-practices/references/_template.md b/.agents/skills/supabase-postgres-best-practices/references/_template.md new file mode 100644 index 0000000..91ace90 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/_template.md @@ -0,0 +1,34 @@ +--- +title: Clear, Action-Oriented Title (e.g., "Use Partial Indexes for Filtered Queries") +impact: MEDIUM +impactDescription: 5-20x query speedup for filtered queries +tags: indexes, query-optimization, performance +--- + +## [Rule Title] + +[1-2 sentence explanation of the problem and why it matters. Focus on performance impact.] + +**Incorrect (describe the problem):** + +```sql +-- Comment explaining what makes this slow/problematic +CREATE INDEX users_email_idx ON users(email); + +SELECT * FROM users WHERE email = 'user@example.com' AND deleted_at IS NULL; +-- This scans deleted records unnecessarily +``` + +**Correct (describe the solution):** + +```sql +-- Comment explaining why this is better +CREATE INDEX users_active_email_idx ON users(email) WHERE deleted_at IS NULL; + +SELECT * FROM users WHERE email = 'user@example.com' AND deleted_at IS NULL; +-- Only indexes active users, 10x smaller index, faster queries +``` + +[Optional: Additional context, edge cases, or trade-offs] + +Reference: [Postgres Docs](https://www.postgresql.org/docs/current/) diff --git a/.agents/skills/supabase-postgres-best-practices/references/advanced-full-text-search.md b/.agents/skills/supabase-postgres-best-practices/references/advanced-full-text-search.md new file mode 100644 index 0000000..582cbea --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/advanced-full-text-search.md @@ -0,0 +1,55 @@ +--- +title: Use tsvector for Full-Text Search +impact: MEDIUM +impactDescription: 100x faster than LIKE, with ranking support +tags: full-text-search, tsvector, gin, search +--- + +## Use tsvector for Full-Text Search + +LIKE with wildcards can't use indexes. Full-text search with tsvector is orders of magnitude faster. + +**Incorrect (LIKE pattern matching):** + +```sql +-- Cannot use index, scans all rows +select * from articles where content like '%postgresql%'; + +-- Case-insensitive makes it worse +select * from articles where lower(content) like '%postgresql%'; +``` + +**Correct (full-text search with tsvector):** + +```sql +-- Add tsvector column and index +alter table articles add column search_vector tsvector + generated always as (to_tsvector('english', coalesce(title,'') || ' ' || coalesce(content,''))) stored; + +create index articles_search_idx on articles using gin (search_vector); + +-- Fast full-text search +select * from articles +where search_vector @@ to_tsquery('english', 'postgresql & performance'); + +-- With ranking +select *, ts_rank(search_vector, query) as rank +from articles, to_tsquery('english', 'postgresql') query +where search_vector @@ query +order by rank desc; +``` + +Search multiple terms: + +```sql +-- AND: both terms required +to_tsquery('postgresql & performance') + +-- OR: either term +to_tsquery('postgresql | mysql') + +-- Prefix matching +to_tsquery('post:*') +``` + +Reference: [Full Text Search](https://supabase.com/docs/guides/database/full-text-search) diff --git a/.agents/skills/supabase-postgres-best-practices/references/advanced-jsonb-indexing.md b/.agents/skills/supabase-postgres-best-practices/references/advanced-jsonb-indexing.md new file mode 100644 index 0000000..e3d261e --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/advanced-jsonb-indexing.md @@ -0,0 +1,49 @@ +--- +title: Index JSONB Columns for Efficient Querying +impact: MEDIUM +impactDescription: 10-100x faster JSONB queries with proper indexing +tags: jsonb, gin, indexes, json +--- + +## Index JSONB Columns for Efficient Querying + +JSONB queries without indexes scan the entire table. Use GIN indexes for containment queries. + +**Incorrect (no index on JSONB):** + +```sql +create table products ( + id bigint primary key, + attributes jsonb +); + +-- Full table scan for every query +select * from products where attributes @> '{"color": "red"}'; +select * from products where attributes->>'brand' = 'Nike'; +``` + +**Correct (GIN index for JSONB):** + +```sql +-- GIN index for containment operators (@>, ?, ?&, ?|) +create index products_attrs_gin on products using gin (attributes); + +-- Now containment queries use the index +select * from products where attributes @> '{"color": "red"}'; + +-- For specific key lookups, use expression index +create index products_brand_idx on products ((attributes->>'brand')); +select * from products where attributes->>'brand' = 'Nike'; +``` + +Choose the right operator class: + +```sql +-- jsonb_ops (default): supports all operators, larger index +create index idx1 on products using gin (attributes); + +-- jsonb_path_ops: only @> operator, but 2-3x smaller index +create index idx2 on products using gin (attributes jsonb_path_ops); +``` + +Reference: [JSONB Indexes](https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING) diff --git a/.agents/skills/supabase-postgres-best-practices/references/conn-idle-timeout.md b/.agents/skills/supabase-postgres-best-practices/references/conn-idle-timeout.md new file mode 100644 index 0000000..40b9cc5 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/conn-idle-timeout.md @@ -0,0 +1,46 @@ +--- +title: Configure Idle Connection Timeouts +impact: HIGH +impactDescription: Reclaim 30-50% of connection slots from idle clients +tags: connections, timeout, idle, resource-management +--- + +## Configure Idle Connection Timeouts + +Idle connections waste resources. Configure timeouts to automatically reclaim them. + +**Incorrect (connections held indefinitely):** + +```sql +-- No timeout configured +show idle_in_transaction_session_timeout; -- 0 (disabled) + +-- Connections stay open forever, even when idle +select pid, state, state_change, query +from pg_stat_activity +where state = 'idle in transaction'; +-- Shows transactions idle for hours, holding locks +``` + +**Correct (automatic cleanup of idle connections):** + +```sql +-- Terminate connections idle in transaction after 30 seconds +alter system set idle_in_transaction_session_timeout = '30s'; + +-- Terminate completely idle connections after 10 minutes +alter system set idle_session_timeout = '10min'; + +-- Reload configuration +select pg_reload_conf(); +``` + +For pooled connections, configure at the pooler level: + +```ini +# pgbouncer.ini +server_idle_timeout = 60 +client_idle_timeout = 300 +``` + +Reference: [Connection Timeouts](https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-IDLE-IN-TRANSACTION-SESSION-TIMEOUT) diff --git a/.agents/skills/supabase-postgres-best-practices/references/conn-limits.md b/.agents/skills/supabase-postgres-best-practices/references/conn-limits.md new file mode 100644 index 0000000..cb3e400 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/conn-limits.md @@ -0,0 +1,44 @@ +--- +title: Set Appropriate Connection Limits +impact: CRITICAL +impactDescription: Prevent database crashes and memory exhaustion +tags: connections, max-connections, limits, stability +--- + +## Set Appropriate Connection Limits + +Too many connections exhaust memory and degrade performance. Set limits based on available resources. + +**Incorrect (unlimited or excessive connections):** + +```sql +-- Default max_connections = 100, but often increased blindly +show max_connections; -- 500 (way too high for 4GB RAM) + +-- Each connection uses 1-3MB RAM +-- 500 connections * 2MB = 1GB just for connections! +-- Out of memory errors under load +``` + +**Correct (calculate based on resources):** + +```sql +-- Formula: max_connections = (RAM in MB / 5MB per connection) - reserved +-- For 4GB RAM: (4096 / 5) - 10 = ~800 theoretical max +-- But practically, 100-200 is better for query performance + +-- Recommended settings for 4GB RAM +alter system set max_connections = 100; + +-- Also set work_mem appropriately +-- work_mem * max_connections should not exceed 25% of RAM +alter system set work_mem = '8MB'; -- 8MB * 100 = 800MB max +``` + +Monitor connection usage: + +```sql +select count(*), state from pg_stat_activity group by state; +``` + +Reference: [Database Connections](https://supabase.com/docs/guides/platform/performance#connection-management) diff --git a/.agents/skills/supabase-postgres-best-practices/references/conn-pooling.md b/.agents/skills/supabase-postgres-best-practices/references/conn-pooling.md new file mode 100644 index 0000000..e2ebd58 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/conn-pooling.md @@ -0,0 +1,41 @@ +--- +title: Use Connection Pooling for All Applications +impact: CRITICAL +impactDescription: Handle 10-100x more concurrent users +tags: connection-pooling, pgbouncer, performance, scalability +--- + +## Use Connection Pooling for All Applications + +Postgres connections are expensive (1-3MB RAM each). Without pooling, applications exhaust connections under load. + +**Incorrect (new connection per request):** + +```sql +-- Each request creates a new connection +-- Application code: db.connect() per request +-- Result: 500 concurrent users = 500 connections = crashed database + +-- Check current connections +select count(*) from pg_stat_activity; -- 487 connections! +``` + +**Correct (connection pooling):** + +```sql +-- Use a pooler like PgBouncer between app and database +-- Application connects to pooler, pooler reuses a small pool to Postgres + +-- Configure pool_size based on: (CPU cores * 2) + spindle_count +-- Example for 4 cores: pool_size = 10 + +-- Result: 500 concurrent users share 10 actual connections +select count(*) from pg_stat_activity; -- 10 connections +``` + +Pool modes: + +- **Transaction mode**: connection returned after each transaction (best for most apps) +- **Session mode**: connection held for entire session (needed for prepared statements, temp tables) + +Reference: [Connection Pooling](https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pooler) diff --git a/.agents/skills/supabase-postgres-best-practices/references/conn-prepared-statements.md b/.agents/skills/supabase-postgres-best-practices/references/conn-prepared-statements.md new file mode 100644 index 0000000..555547d --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/conn-prepared-statements.md @@ -0,0 +1,46 @@ +--- +title: Use Prepared Statements Correctly with Pooling +impact: HIGH +impactDescription: Avoid prepared statement conflicts in pooled environments +tags: prepared-statements, connection-pooling, transaction-mode +--- + +## Use Prepared Statements Correctly with Pooling + +Prepared statements are tied to individual database connections. In transaction-mode pooling, connections are shared, causing conflicts. + +**Incorrect (named prepared statements with transaction pooling):** + +```sql +-- Named prepared statement +prepare get_user as select * from users where id = $1; + +-- In transaction mode pooling, next request may get different connection +execute get_user(123); +-- ERROR: prepared statement "get_user" does not exist +``` + +**Correct (use unnamed statements or session mode):** + +```sql +-- Option 1: Use unnamed prepared statements (most ORMs do this automatically) +-- The query is prepared and executed in a single protocol message + +-- Option 2: Deallocate after use in transaction mode +prepare get_user as select * from users where id = $1; +execute get_user(123); +deallocate get_user; + +-- Option 3: Use session mode pooling (port 5432 vs 6543) +-- Connection is held for entire session, prepared statements persist +``` + +Check your driver settings: + +```sql +-- Many drivers use prepared statements by default +-- Node.js pg: { prepare: false } to disable +-- JDBC: prepareThreshold=0 to disable +``` + +Reference: [Prepared Statements with Pooling](https://supabase.com/docs/guides/database/connecting-to-postgres#connection-pool-modes) diff --git a/.agents/skills/supabase-postgres-best-practices/references/data-batch-inserts.md b/.agents/skills/supabase-postgres-best-practices/references/data-batch-inserts.md new file mode 100644 index 0000000..997947c --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/data-batch-inserts.md @@ -0,0 +1,54 @@ +--- +title: Batch INSERT Statements for Bulk Data +impact: MEDIUM +impactDescription: 10-50x faster bulk inserts +tags: batch, insert, bulk, performance, copy +--- + +## Batch INSERT Statements for Bulk Data + +Individual INSERT statements have high overhead. Batch multiple rows in single statements or use COPY. + +**Incorrect (individual inserts):** + +```sql +-- Each insert is a separate transaction and round trip +insert into events (user_id, action) values (1, 'click'); +insert into events (user_id, action) values (1, 'view'); +insert into events (user_id, action) values (2, 'click'); +-- ... 1000 more individual inserts + +-- 1000 inserts = 1000 round trips = slow +``` + +**Correct (batch insert):** + +```sql +-- Multiple rows in single statement +insert into events (user_id, action) values + (1, 'click'), + (1, 'view'), + (2, 'click'), + -- ... up to ~1000 rows per batch + (999, 'view'); + +-- One round trip for 1000 rows +``` + +For large imports, use COPY: + +```sql +-- COPY is fastest for bulk loading +copy events (user_id, action, created_at) +from '/path/to/data.csv' +with (format csv, header true); + +-- Or from stdin in application +copy events (user_id, action) from stdin with (format csv); +1,click +1,view +2,click +\. +``` + +Reference: [COPY](https://www.postgresql.org/docs/current/sql-copy.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/data-n-plus-one.md b/.agents/skills/supabase-postgres-best-practices/references/data-n-plus-one.md new file mode 100644 index 0000000..2109186 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/data-n-plus-one.md @@ -0,0 +1,53 @@ +--- +title: Eliminate N+1 Queries with Batch Loading +impact: MEDIUM-HIGH +impactDescription: 10-100x fewer database round trips +tags: n-plus-one, batch, performance, queries +--- + +## Eliminate N+1 Queries with Batch Loading + +N+1 queries execute one query per item in a loop. Batch them into a single query using arrays or JOINs. + +**Incorrect (N+1 queries):** + +```sql +-- First query: get all users +select id from users where active = true; -- Returns 100 IDs + +-- Then N queries, one per user +select * from orders where user_id = 1; +select * from orders where user_id = 2; +select * from orders where user_id = 3; +-- ... 97 more queries! + +-- Total: 101 round trips to database +``` + +**Correct (single batch query):** + +```sql +-- Collect IDs and query once with ANY +select * from orders where user_id = any(array[1, 2, 3, ...]); + +-- Or use JOIN instead of loop +select u.id, u.name, o.* +from users u +left join orders o on o.user_id = u.id +where u.active = true; + +-- Total: 1 round trip +``` + +Application pattern: + +```sql +-- Instead of looping in application code: +-- for user in users: db.query("SELECT * FROM orders WHERE user_id = $1", user.id) + +-- Pass array parameter: +select * from orders where user_id = any($1::bigint[]); +-- Application passes: [1, 2, 3, 4, 5, ...] +``` + +Reference: [N+1 Query Problem](https://supabase.com/docs/guides/database/query-optimization) diff --git a/.agents/skills/supabase-postgres-best-practices/references/data-pagination.md b/.agents/skills/supabase-postgres-best-practices/references/data-pagination.md new file mode 100644 index 0000000..633d839 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/data-pagination.md @@ -0,0 +1,50 @@ +--- +title: Use Cursor-Based Pagination Instead of OFFSET +impact: MEDIUM-HIGH +impactDescription: Consistent O(1) performance regardless of page depth +tags: pagination, cursor, keyset, offset, performance +--- + +## Use Cursor-Based Pagination Instead of OFFSET + +OFFSET-based pagination scans all skipped rows, getting slower on deeper pages. Cursor pagination is O(1). + +**Incorrect (OFFSET pagination):** + +```sql +-- Page 1: scans 20 rows +select * from products order by id limit 20 offset 0; + +-- Page 100: scans 2000 rows to skip 1980 +select * from products order by id limit 20 offset 1980; + +-- Page 10000: scans 200,000 rows! +select * from products order by id limit 20 offset 199980; +``` + +**Correct (cursor/keyset pagination):** + +```sql +-- Page 1: get first 20 +select * from products order by id limit 20; +-- Application stores last_id = 20 + +-- Page 2: start after last ID +select * from products where id > 20 order by id limit 20; +-- Uses index, always fast regardless of page depth + +-- Page 10000: same speed as page 1 +select * from products where id > 199980 order by id limit 20; +``` + +For multi-column sorting: + +```sql +-- Cursor must include all sort columns +select * from products +where (created_at, id) > ('2024-01-15 10:00:00', 12345) +order by created_at, id +limit 20; +``` + +Reference: [Pagination](https://supabase.com/docs/guides/database/pagination) diff --git a/.agents/skills/supabase-postgres-best-practices/references/data-upsert.md b/.agents/skills/supabase-postgres-best-practices/references/data-upsert.md new file mode 100644 index 0000000..bc95e23 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/data-upsert.md @@ -0,0 +1,50 @@ +--- +title: Use UPSERT for Insert-or-Update Operations +impact: MEDIUM +impactDescription: Atomic operation, eliminates race conditions +tags: upsert, on-conflict, insert, update +--- + +## Use UPSERT for Insert-or-Update Operations + +Using separate SELECT-then-INSERT/UPDATE creates race conditions. Use INSERT ... ON CONFLICT for atomic upserts. + +**Incorrect (check-then-insert race condition):** + +```sql +-- Race condition: two requests check simultaneously +select * from settings where user_id = 123 and key = 'theme'; +-- Both find nothing + +-- Both try to insert +insert into settings (user_id, key, value) values (123, 'theme', 'dark'); +-- One succeeds, one fails with duplicate key error! +``` + +**Correct (atomic UPSERT):** + +```sql +-- Single atomic operation +insert into settings (user_id, key, value) +values (123, 'theme', 'dark') +on conflict (user_id, key) +do update set value = excluded.value, updated_at = now(); + +-- Returns the inserted/updated row +insert into settings (user_id, key, value) +values (123, 'theme', 'dark') +on conflict (user_id, key) +do update set value = excluded.value +returning *; +``` + +Insert-or-ignore pattern: + +```sql +-- Insert only if not exists (no update) +insert into page_views (page_id, user_id) +values (1, 123) +on conflict (page_id, user_id) do nothing; +``` + +Reference: [INSERT ON CONFLICT](https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT) diff --git a/.agents/skills/supabase-postgres-best-practices/references/lock-advisory.md b/.agents/skills/supabase-postgres-best-practices/references/lock-advisory.md new file mode 100644 index 0000000..572eaf0 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/lock-advisory.md @@ -0,0 +1,56 @@ +--- +title: Use Advisory Locks for Application-Level Locking +impact: MEDIUM +impactDescription: Efficient coordination without row-level lock overhead +tags: advisory-locks, coordination, application-locks +--- + +## Use Advisory Locks for Application-Level Locking + +Advisory locks provide application-level coordination without requiring database rows to lock. + +**Incorrect (creating rows just for locking):** + +```sql +-- Creating dummy rows to lock on +create table resource_locks ( + resource_name text primary key +); + +insert into resource_locks values ('report_generator'); + +-- Lock by selecting the row +select * from resource_locks where resource_name = 'report_generator' for update; +``` + +**Correct (advisory locks):** + +```sql +-- Session-level advisory lock (released on disconnect or unlock) +select pg_advisory_lock(hashtext('report_generator')); +-- ... do exclusive work ... +select pg_advisory_unlock(hashtext('report_generator')); + +-- Transaction-level lock (released on commit/rollback) +begin; +select pg_advisory_xact_lock(hashtext('daily_report')); +-- ... do work ... +commit; -- Lock automatically released +``` + +Try-lock for non-blocking operations: + +```sql +-- Returns immediately with true/false instead of waiting +select pg_try_advisory_lock(hashtext('resource_name')); + +-- Use in application +if (acquired) { + -- Do work + select pg_advisory_unlock(hashtext('resource_name')); +} else { + -- Skip or retry later +} +``` + +Reference: [Advisory Locks](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS) diff --git a/.agents/skills/supabase-postgres-best-practices/references/lock-deadlock-prevention.md b/.agents/skills/supabase-postgres-best-practices/references/lock-deadlock-prevention.md new file mode 100644 index 0000000..974da5e --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/lock-deadlock-prevention.md @@ -0,0 +1,68 @@ +--- +title: Prevent Deadlocks with Consistent Lock Ordering +impact: MEDIUM-HIGH +impactDescription: Eliminate deadlock errors, improve reliability +tags: deadlocks, locking, transactions, ordering +--- + +## Prevent Deadlocks with Consistent Lock Ordering + +Deadlocks occur when transactions lock resources in different orders. Always +acquire locks in a consistent order. + +**Incorrect (inconsistent lock ordering):** + +```sql +-- Transaction A -- Transaction B +begin; begin; +update accounts update accounts +set balance = balance - 100 set balance = balance - 50 +where id = 1; where id = 2; -- B locks row 2 + +update accounts update accounts +set balance = balance + 100 set balance = balance + 50 +where id = 2; -- A waits for B where id = 1; -- B waits for A + +-- DEADLOCK! Both waiting for each other +``` + +**Correct (lock rows in consistent order first):** + +```sql +-- Explicitly acquire locks in ID order before updating +begin; +select * from accounts where id in (1, 2) order by id for update; + +-- Now perform updates in any order - locks already held +update accounts set balance = balance - 100 where id = 1; +update accounts set balance = balance + 100 where id = 2; +commit; +``` + +Alternative: use a single statement to update atomically: + +```sql +-- Single statement acquires all locks atomically +begin; +update accounts +set balance = balance + case id + when 1 then -100 + when 2 then 100 +end +where id in (1, 2); +commit; +``` + +Detect deadlocks in logs: + +```sql +-- Check for recent deadlocks +select * from pg_stat_database where deadlocks > 0; + +-- Enable deadlock logging +set log_lock_waits = on; +set deadlock_timeout = '1s'; +``` + +Reference: +[Deadlocks](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-DEADLOCKS) diff --git a/.agents/skills/supabase-postgres-best-practices/references/lock-short-transactions.md b/.agents/skills/supabase-postgres-best-practices/references/lock-short-transactions.md new file mode 100644 index 0000000..e6b8ef2 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/lock-short-transactions.md @@ -0,0 +1,50 @@ +--- +title: Keep Transactions Short to Reduce Lock Contention +impact: MEDIUM-HIGH +impactDescription: 3-5x throughput improvement, fewer deadlocks +tags: transactions, locking, contention, performance +--- + +## Keep Transactions Short to Reduce Lock Contention + +Long-running transactions hold locks that block other queries. Keep transactions as short as possible. + +**Incorrect (long transaction with external calls):** + +```sql +begin; +select * from orders where id = 1 for update; -- Lock acquired + +-- Application makes HTTP call to payment API (2-5 seconds) +-- Other queries on this row are blocked! + +update orders set status = 'paid' where id = 1; +commit; -- Lock held for entire duration +``` + +**Correct (minimal transaction scope):** + +```sql +-- Validate data and call APIs outside transaction +-- Application: response = await paymentAPI.charge(...) + +-- Only hold lock for the actual update +begin; +update orders +set status = 'paid', payment_id = $1 +where id = $2 and status = 'pending' +returning *; +commit; -- Lock held for milliseconds +``` + +Use `statement_timeout` to prevent runaway transactions: + +```sql +-- Abort queries running longer than 30 seconds +set statement_timeout = '30s'; + +-- Or per-session +set local statement_timeout = '5s'; +``` + +Reference: [Transaction Management](https://www.postgresql.org/docs/current/tutorial-transactions.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/lock-skip-locked.md b/.agents/skills/supabase-postgres-best-practices/references/lock-skip-locked.md new file mode 100644 index 0000000..77bdbb9 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/lock-skip-locked.md @@ -0,0 +1,54 @@ +--- +title: Use SKIP LOCKED for Non-Blocking Queue Processing +impact: MEDIUM-HIGH +impactDescription: 10x throughput for worker queues +tags: skip-locked, queue, workers, concurrency +--- + +## Use SKIP LOCKED for Non-Blocking Queue Processing + +When multiple workers process a queue, SKIP LOCKED allows workers to process different rows without waiting. + +**Incorrect (workers block each other):** + +```sql +-- Worker 1 and Worker 2 both try to get next job +begin; +select * from jobs where status = 'pending' order by created_at limit 1 for update; +-- Worker 2 waits for Worker 1's lock to release! +``` + +**Correct (SKIP LOCKED for parallel processing):** + +```sql +-- Each worker skips locked rows and gets the next available +begin; +select * from jobs +where status = 'pending' +order by created_at +limit 1 +for update skip locked; + +-- Worker 1 gets job 1, Worker 2 gets job 2 (no waiting) + +update jobs set status = 'processing' where id = $1; +commit; +``` + +Complete queue pattern: + +```sql +-- Atomic claim-and-update in one statement +update jobs +set status = 'processing', worker_id = $1, started_at = now() +where id = ( + select id from jobs + where status = 'pending' + order by created_at + limit 1 + for update skip locked +) +returning *; +``` + +Reference: [SELECT FOR UPDATE SKIP LOCKED](https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE) diff --git a/.agents/skills/supabase-postgres-best-practices/references/monitor-explain-analyze.md b/.agents/skills/supabase-postgres-best-practices/references/monitor-explain-analyze.md new file mode 100644 index 0000000..542978c --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/monitor-explain-analyze.md @@ -0,0 +1,45 @@ +--- +title: Use EXPLAIN ANALYZE to Diagnose Slow Queries +impact: LOW-MEDIUM +impactDescription: Identify exact bottlenecks in query execution +tags: explain, analyze, diagnostics, query-plan +--- + +## Use EXPLAIN ANALYZE to Diagnose Slow Queries + +EXPLAIN ANALYZE executes the query and shows actual timings, revealing the true performance bottlenecks. + +**Incorrect (guessing at performance issues):** + +```sql +-- Query is slow, but why? +select * from orders where customer_id = 123 and status = 'pending'; +-- "It must be missing an index" - but which one? +``` + +**Correct (use EXPLAIN ANALYZE):** + +```sql +explain (analyze, buffers, format text) +select * from orders where customer_id = 123 and status = 'pending'; + +-- Output reveals the issue: +-- Seq Scan on orders (cost=0.00..25000.00 rows=50 width=100) (actual time=0.015..450.123 rows=50 loops=1) +-- Filter: ((customer_id = 123) AND (status = 'pending'::text)) +-- Rows Removed by Filter: 999950 +-- Buffers: shared hit=5000 read=15000 +-- Planning Time: 0.150 ms +-- Execution Time: 450.500 ms +``` + +Key things to look for: + +```sql +-- Seq Scan on large tables = missing index +-- Rows Removed by Filter = poor selectivity or missing index +-- Buffers: read >> hit = data not cached, needs more memory +-- Nested Loop with high loops = consider different join strategy +-- Sort Method: external merge = work_mem too low +``` + +Reference: [EXPLAIN](https://supabase.com/docs/guides/database/inspect) diff --git a/.agents/skills/supabase-postgres-best-practices/references/monitor-pg-stat-statements.md b/.agents/skills/supabase-postgres-best-practices/references/monitor-pg-stat-statements.md new file mode 100644 index 0000000..d7e82f1 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/monitor-pg-stat-statements.md @@ -0,0 +1,55 @@ +--- +title: Enable pg_stat_statements for Query Analysis +impact: LOW-MEDIUM +impactDescription: Identify top resource-consuming queries +tags: pg-stat-statements, monitoring, statistics, performance +--- + +## Enable pg_stat_statements for Query Analysis + +pg_stat_statements tracks execution statistics for all queries, helping identify slow and frequent queries. + +**Incorrect (no visibility into query patterns):** + +```sql +-- Database is slow, but which queries are the problem? +-- No way to know without pg_stat_statements +``` + +**Correct (enable and query pg_stat_statements):** + +```sql +-- Enable the extension +create extension if not exists pg_stat_statements; + +-- Find slowest queries by total time +select + calls, + round(total_exec_time::numeric, 2) as total_time_ms, + round(mean_exec_time::numeric, 2) as mean_time_ms, + query +from pg_stat_statements +order by total_exec_time desc +limit 10; + +-- Find most frequent queries +select calls, query +from pg_stat_statements +order by calls desc +limit 10; + +-- Reset statistics after optimization +select pg_stat_statements_reset(); +``` + +Key metrics to monitor: + +```sql +-- Queries with high mean time (candidates for optimization) +select query, mean_exec_time, calls +from pg_stat_statements +where mean_exec_time > 100 -- > 100ms average +order by mean_exec_time desc; +``` + +Reference: [pg_stat_statements](https://supabase.com/docs/guides/database/extensions/pg_stat_statements) diff --git a/.agents/skills/supabase-postgres-best-practices/references/monitor-vacuum-analyze.md b/.agents/skills/supabase-postgres-best-practices/references/monitor-vacuum-analyze.md new file mode 100644 index 0000000..e0e8ea0 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/monitor-vacuum-analyze.md @@ -0,0 +1,55 @@ +--- +title: Maintain Table Statistics with VACUUM and ANALYZE +impact: MEDIUM +impactDescription: 2-10x better query plans with accurate statistics +tags: vacuum, analyze, statistics, maintenance, autovacuum +--- + +## Maintain Table Statistics with VACUUM and ANALYZE + +Outdated statistics cause the query planner to make poor decisions. VACUUM reclaims space, ANALYZE updates statistics. + +**Incorrect (stale statistics):** + +```sql +-- Table has 1M rows but stats say 1000 +-- Query planner chooses wrong strategy +explain select * from orders where status = 'pending'; +-- Shows: Seq Scan (because stats show small table) +-- Actually: Index Scan would be much faster +``` + +**Correct (maintain fresh statistics):** + +```sql +-- Manually analyze after large data changes +analyze orders; + +-- Analyze specific columns used in WHERE clauses +analyze orders (status, created_at); + +-- Check when tables were last analyzed +select + relname, + last_vacuum, + last_autovacuum, + last_analyze, + last_autoanalyze +from pg_stat_user_tables +order by last_analyze nulls first; +``` + +Autovacuum tuning for busy tables: + +```sql +-- Increase frequency for high-churn tables +alter table orders set ( + autovacuum_vacuum_scale_factor = 0.05, -- Vacuum at 5% dead tuples (default 20%) + autovacuum_analyze_scale_factor = 0.02 -- Analyze at 2% changes (default 10%) +); + +-- Check autovacuum status +select * from pg_stat_progress_vacuum; +``` + +Reference: [VACUUM](https://supabase.com/docs/guides/database/database-size#vacuum-operations) diff --git a/.agents/skills/supabase-postgres-best-practices/references/query-composite-indexes.md b/.agents/skills/supabase-postgres-best-practices/references/query-composite-indexes.md new file mode 100644 index 0000000..fea6452 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/query-composite-indexes.md @@ -0,0 +1,44 @@ +--- +title: Create Composite Indexes for Multi-Column Queries +impact: HIGH +impactDescription: 5-10x faster multi-column queries +tags: indexes, composite-index, multi-column, query-optimization +--- + +## Create Composite Indexes for Multi-Column Queries + +When queries filter on multiple columns, a composite index is more efficient than separate single-column indexes. + +**Incorrect (separate indexes require bitmap scan):** + +```sql +-- Two separate indexes +create index orders_status_idx on orders (status); +create index orders_created_idx on orders (created_at); + +-- Query must combine both indexes (slower) +select * from orders where status = 'pending' and created_at > '2024-01-01'; +``` + +**Correct (composite index):** + +```sql +-- Single composite index (leftmost column first for equality checks) +create index orders_status_created_idx on orders (status, created_at); + +-- Query uses one efficient index scan +select * from orders where status = 'pending' and created_at > '2024-01-01'; +``` + +**Column order matters** - place equality columns first, range columns last: + +```sql +-- Good: status (=) before created_at (>) +create index idx on orders (status, created_at); + +-- Works for: WHERE status = 'pending' +-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01' +-- Does NOT work for: WHERE created_at > '2024-01-01' (leftmost prefix rule) +``` + +Reference: [Multicolumn Indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/query-covering-indexes.md b/.agents/skills/supabase-postgres-best-practices/references/query-covering-indexes.md new file mode 100644 index 0000000..9d2a494 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/query-covering-indexes.md @@ -0,0 +1,40 @@ +--- +title: Use Covering Indexes to Avoid Table Lookups +impact: MEDIUM-HIGH +impactDescription: 2-5x faster queries by eliminating heap fetches +tags: indexes, covering-index, include, index-only-scan +--- + +## Use Covering Indexes to Avoid Table Lookups + +Covering indexes include all columns needed by a query, enabling index-only scans that skip the table entirely. + +**Incorrect (index scan + heap fetch):** + +```sql +create index users_email_idx on users (email); + +-- Must fetch name and created_at from table heap +select email, name, created_at from users where email = 'user@example.com'; +``` + +**Correct (index-only scan with INCLUDE):** + +```sql +-- Include non-searchable columns in the index +create index users_email_idx on users (email) include (name, created_at); + +-- All columns served from index, no table access needed +select email, name, created_at from users where email = 'user@example.com'; +``` + +Use INCLUDE for columns you SELECT but don't filter on: + +```sql +-- Searching by status, but also need customer_id and total +create index orders_status_idx on orders (status) include (customer_id, total); + +select status, customer_id, total from orders where status = 'shipped'; +``` + +Reference: [Index-Only Scans](https://www.postgresql.org/docs/current/indexes-index-only-scans.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/query-index-types.md b/.agents/skills/supabase-postgres-best-practices/references/query-index-types.md new file mode 100644 index 0000000..93b3259 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/query-index-types.md @@ -0,0 +1,48 @@ +--- +title: Choose the Right Index Type for Your Data +impact: HIGH +impactDescription: 10-100x improvement with correct index type +tags: indexes, btree, gin, gist, brin, hash, index-types +--- + +## Choose the Right Index Type for Your Data + +Different index types excel at different query patterns. The default B-tree isn't always optimal. + +**Incorrect (B-tree for JSONB containment):** + +```sql +-- B-tree cannot optimize containment operators +create index products_attrs_idx on products (attributes); +select * from products where attributes @> '{"color": "red"}'; +-- Full table scan - B-tree doesn't support @> operator +``` + +**Correct (GIN for JSONB):** + +```sql +-- GIN supports @>, ?, ?&, ?| operators +create index products_attrs_idx on products using gin (attributes); +select * from products where attributes @> '{"color": "red"}'; +``` + +Index type guide: + +```sql +-- B-tree (default): =, <, >, BETWEEN, IN, IS NULL +create index users_created_idx on users (created_at); + +-- GIN: arrays, JSONB, full-text search +create index posts_tags_idx on posts using gin (tags); + +-- GiST: geometric data, range types, nearest-neighbor (KNN) queries +create index locations_idx on places using gist (location); + +-- BRIN: large time-series tables (10-100x smaller) +create index events_time_idx on events using brin (created_at); + +-- Hash: equality-only (slightly faster than B-tree for =) +create index sessions_token_idx on sessions using hash (token); +``` + +Reference: [Index Types](https://www.postgresql.org/docs/current/indexes-types.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/query-missing-indexes.md b/.agents/skills/supabase-postgres-best-practices/references/query-missing-indexes.md new file mode 100644 index 0000000..e6daace --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/query-missing-indexes.md @@ -0,0 +1,43 @@ +--- +title: Add Indexes on WHERE and JOIN Columns +impact: CRITICAL +impactDescription: 100-1000x faster queries on large tables +tags: indexes, performance, sequential-scan, query-optimization +--- + +## Add Indexes on WHERE and JOIN Columns + +Queries filtering or joining on unindexed columns cause full table scans, which become exponentially slower as tables grow. + +**Incorrect (sequential scan on large table):** + +```sql +-- No index on customer_id causes full table scan +select * from orders where customer_id = 123; + +-- EXPLAIN shows: Seq Scan on orders (cost=0.00..25000.00 rows=100 width=85) +``` + +**Correct (index scan):** + +```sql +-- Create index on frequently filtered column +create index orders_customer_id_idx on orders (customer_id); + +select * from orders where customer_id = 123; + +-- EXPLAIN shows: Index Scan using orders_customer_id_idx (cost=0.42..8.44 rows=100 width=85) +``` + +For JOIN columns, always index the foreign key side: + +```sql +-- Index the referencing column +create index orders_customer_id_idx on orders (customer_id); + +select c.name, o.total +from customers c +join orders o on o.customer_id = c.id; +``` + +Reference: [Query Optimization](https://supabase.com/docs/guides/database/query-optimization) diff --git a/.agents/skills/supabase-postgres-best-practices/references/query-partial-indexes.md b/.agents/skills/supabase-postgres-best-practices/references/query-partial-indexes.md new file mode 100644 index 0000000..3e61a34 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/query-partial-indexes.md @@ -0,0 +1,45 @@ +--- +title: Use Partial Indexes for Filtered Queries +impact: HIGH +impactDescription: 5-20x smaller indexes, faster writes and queries +tags: indexes, partial-index, query-optimization, storage +--- + +## Use Partial Indexes for Filtered Queries + +Partial indexes only include rows matching a WHERE condition, making them smaller and faster when queries consistently filter on the same condition. + +**Incorrect (full index includes irrelevant rows):** + +```sql +-- Index includes all rows, even soft-deleted ones +create index users_email_idx on users (email); + +-- Query always filters active users +select * from users where email = 'user@example.com' and deleted_at is null; +``` + +**Correct (partial index matches query filter):** + +```sql +-- Index only includes active users +create index users_active_email_idx on users (email) +where deleted_at is null; + +-- Query uses the smaller, faster index +select * from users where email = 'user@example.com' and deleted_at is null; +``` + +Common use cases for partial indexes: + +```sql +-- Only pending orders (status rarely changes once completed) +create index orders_pending_idx on orders (created_at) +where status = 'pending'; + +-- Only non-null values +create index products_sku_idx on products (sku) +where sku is not null; +``` + +Reference: [Partial Indexes](https://www.postgresql.org/docs/current/indexes-partial.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-constraints.md b/.agents/skills/supabase-postgres-best-practices/references/schema-constraints.md new file mode 100644 index 0000000..1d2ef8f --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-constraints.md @@ -0,0 +1,80 @@ +--- +title: Add Constraints Safely in Migrations +impact: HIGH +impactDescription: Prevents migration failures and enables idempotent schema changes +tags: constraints, migrations, schema, alter-table +--- + +## Add Constraints Safely in Migrations + +PostgreSQL does not support `ADD CONSTRAINT IF NOT EXISTS`. Migrations using this syntax will fail. + +**Incorrect (causes syntax error):** + +```sql +-- ERROR: syntax error at or near "not" (SQLSTATE 42601) +alter table public.profiles +add constraint if not exists profiles_birthchart_id_unique unique (birthchart_id); +``` + +**Correct (idempotent constraint creation):** + +```sql +-- Use DO block to check before adding +do $$ +begin + if not exists ( + select 1 from pg_constraint + where conname = 'profiles_birthchart_id_unique' + and conrelid = 'public.profiles'::regclass + ) then + alter table public.profiles + add constraint profiles_birthchart_id_unique unique (birthchart_id); + end if; +end $$; +``` + +For all constraint types: + +```sql +-- Check constraints +do $$ +begin + if not exists ( + select 1 from pg_constraint + where conname = 'check_age_positive' + ) then + alter table users add constraint check_age_positive check (age > 0); + end if; +end $$; + +-- Foreign keys +do $$ +begin + if not exists ( + select 1 from pg_constraint + where conname = 'profiles_birthchart_id_fkey' + ) then + alter table profiles + add constraint profiles_birthchart_id_fkey + foreign key (birthchart_id) references birthcharts(id); + end if; +end $$; +``` + +Check if constraint exists: + +```sql +-- Query to check constraint existence +select conname, contype, pg_get_constraintdef(oid) +from pg_constraint +where conrelid = 'public.profiles'::regclass; + +-- contype values: +-- 'p' = PRIMARY KEY +-- 'f' = FOREIGN KEY +-- 'u' = UNIQUE +-- 'c' = CHECK +``` + +Reference: [Constraints](https://www.postgresql.org/docs/current/ddl-constraints.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-data-types.md b/.agents/skills/supabase-postgres-best-practices/references/schema-data-types.md new file mode 100644 index 0000000..f253a58 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-data-types.md @@ -0,0 +1,46 @@ +--- +title: Choose Appropriate Data Types +impact: HIGH +impactDescription: 50% storage reduction, faster comparisons +tags: data-types, schema, storage, performance +--- + +## Choose Appropriate Data Types + +Using the right data types reduces storage, improves query performance, and prevents bugs. + +**Incorrect (wrong data types):** + +```sql +create table users ( + id int, -- Will overflow at 2.1 billion + email varchar(255), -- Unnecessary length limit + created_at timestamp, -- Missing timezone info + is_active varchar(5), -- String for boolean + price varchar(20) -- String for numeric +); +``` + +**Correct (appropriate data types):** + +```sql +create table users ( + id bigint generated always as identity primary key, -- 9 quintillion max + email text, -- No artificial limit, same performance as varchar + created_at timestamptz, -- Always store timezone-aware timestamps + is_active boolean default true, -- 1 byte vs variable string length + price numeric(10,2) -- Exact decimal arithmetic +); +``` + +Key guidelines: + +```sql +-- IDs: use bigint, not int (future-proofing) +-- Strings: use text, not varchar(n) unless constraint needed +-- Time: use timestamptz, not timestamp +-- Money: use numeric, not float (precision matters) +-- Enums: use text with check constraint or create enum type +``` + +Reference: [Data Types](https://www.postgresql.org/docs/current/datatype.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-foreign-key-indexes.md b/.agents/skills/supabase-postgres-best-practices/references/schema-foreign-key-indexes.md new file mode 100644 index 0000000..6c3d6ff --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-foreign-key-indexes.md @@ -0,0 +1,59 @@ +--- +title: Index Foreign Key Columns +impact: HIGH +impactDescription: 10-100x faster JOINs and CASCADE operations +tags: foreign-key, indexes, joins, schema +--- + +## Index Foreign Key Columns + +Postgres does not automatically index foreign key columns. Missing indexes cause slow JOINs and CASCADE operations. + +**Incorrect (unindexed foreign key):** + +```sql +create table orders ( + id bigint generated always as identity primary key, + customer_id bigint references customers(id) on delete cascade, + total numeric(10,2) +); + +-- No index on customer_id! +-- JOINs and ON DELETE CASCADE both require full table scan +select * from orders where customer_id = 123; -- Seq Scan +delete from customers where id = 123; -- Locks table, scans all orders +``` + +**Correct (indexed foreign key):** + +```sql +create table orders ( + id bigint generated always as identity primary key, + customer_id bigint references customers(id) on delete cascade, + total numeric(10,2) +); + +-- Always index the FK column +create index orders_customer_id_idx on orders (customer_id); + +-- Now JOINs and cascades are fast +select * from orders where customer_id = 123; -- Index Scan +delete from customers where id = 123; -- Uses index, fast cascade +``` + +Find missing FK indexes: + +```sql +select + conrelid::regclass as table_name, + a.attname as fk_column +from pg_constraint c +join pg_attribute a on a.attrelid = c.conrelid and a.attnum = any(c.conkey) +where c.contype = 'f' + and not exists ( + select 1 from pg_index i + where i.indrelid = c.conrelid and a.attnum = any(i.indkey) + ); +``` + +Reference: [Foreign Keys](https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-lowercase-identifiers.md b/.agents/skills/supabase-postgres-best-practices/references/schema-lowercase-identifiers.md new file mode 100644 index 0000000..f007294 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-lowercase-identifiers.md @@ -0,0 +1,55 @@ +--- +title: Use Lowercase Identifiers for Compatibility +impact: MEDIUM +impactDescription: Avoid case-sensitivity bugs with tools, ORMs, and AI assistants +tags: naming, identifiers, case-sensitivity, schema, conventions +--- + +## Use Lowercase Identifiers for Compatibility + +PostgreSQL folds unquoted identifiers to lowercase. Quoted mixed-case identifiers require quotes forever and cause issues with tools, ORMs, and AI assistants that may not recognize them. + +**Incorrect (mixed-case identifiers):** + +```sql +-- Quoted identifiers preserve case but require quotes everywhere +CREATE TABLE "Users" ( + "userId" bigint PRIMARY KEY, + "firstName" text, + "lastName" text +); + +-- Must always quote or queries fail +SELECT "firstName" FROM "Users" WHERE "userId" = 1; + +-- This fails - Users becomes users without quotes +SELECT firstName FROM Users; +-- ERROR: relation "users" does not exist +``` + +**Correct (lowercase snake_case):** + +```sql +-- Unquoted lowercase identifiers are portable and tool-friendly +CREATE TABLE users ( + user_id bigint PRIMARY KEY, + first_name text, + last_name text +); + +-- Works without quotes, recognized by all tools +SELECT first_name FROM users WHERE user_id = 1; +``` + +Common sources of mixed-case identifiers: + +```sql +-- ORMs often generate quoted camelCase - configure them to use snake_case +-- Migrations from other databases may preserve original casing +-- Some GUI tools quote identifiers by default - disable this + +-- If stuck with mixed-case, create views as a compatibility layer +CREATE VIEW users AS SELECT "userId" AS user_id, "firstName" AS first_name FROM "Users"; +``` + +Reference: [Identifiers and Key Words](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-partitioning.md b/.agents/skills/supabase-postgres-best-practices/references/schema-partitioning.md new file mode 100644 index 0000000..13137a0 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-partitioning.md @@ -0,0 +1,55 @@ +--- +title: Partition Large Tables for Better Performance +impact: MEDIUM-HIGH +impactDescription: 5-20x faster queries and maintenance on large tables +tags: partitioning, large-tables, time-series, performance +--- + +## Partition Large Tables for Better Performance + +Partitioning splits a large table into smaller pieces, improving query performance and maintenance operations. + +**Incorrect (single large table):** + +```sql +create table events ( + id bigint generated always as identity, + created_at timestamptz, + data jsonb +); + +-- 500M rows, queries scan everything +select * from events where created_at > '2024-01-01'; -- Slow +vacuum events; -- Takes hours, locks table +``` + +**Correct (partitioned by time range):** + +```sql +create table events ( + id bigint generated always as identity, + created_at timestamptz not null, + data jsonb +) partition by range (created_at); + +-- Create partitions for each month +create table events_2024_01 partition of events + for values from ('2024-01-01') to ('2024-02-01'); + +create table events_2024_02 partition of events + for values from ('2024-02-01') to ('2024-03-01'); + +-- Queries only scan relevant partitions +select * from events where created_at > '2024-01-15'; -- Only scans events_2024_01+ + +-- Drop old data instantly +drop table events_2023_01; -- Instant vs DELETE taking hours +``` + +When to partition: + +- Tables > 100M rows +- Time-series data with date-based queries +- Need to efficiently drop old data + +Reference: [Table Partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html) diff --git a/.agents/skills/supabase-postgres-best-practices/references/schema-primary-keys.md b/.agents/skills/supabase-postgres-best-practices/references/schema-primary-keys.md new file mode 100644 index 0000000..fb0fbb1 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/schema-primary-keys.md @@ -0,0 +1,61 @@ +--- +title: Select Optimal Primary Key Strategy +impact: HIGH +impactDescription: Better index locality, reduced fragmentation +tags: primary-key, identity, uuid, serial, schema +--- + +## Select Optimal Primary Key Strategy + +Primary key choice affects insert performance, index size, and replication +efficiency. + +**Incorrect (problematic PK choices):** + +```sql +-- identity is the SQL-standard approach +create table users ( + id serial primary key -- Works, but IDENTITY is recommended +); + +-- Random UUIDs (v4) cause index fragmentation +create table orders ( + id uuid default gen_random_uuid() primary key -- UUIDv4 = random = scattered inserts +); +``` + +**Correct (optimal PK strategies):** + +```sql +-- Use IDENTITY for sequential IDs (SQL-standard, best for most cases) +create table users ( + id bigint generated always as identity primary key +); + +-- For distributed systems needing UUIDs, use UUIDv7 (time-ordered) +-- Requires pg_uuidv7 extension: create extension pg_uuidv7; +create table orders ( + id uuid default uuid_generate_v7() primary key -- Time-ordered, no fragmentation +); + +-- Alternative: time-prefixed IDs for sortable, distributed IDs (no extension needed) +create table events ( + id text default concat( + to_char(now() at time zone 'utc', 'YYYYMMDDHH24MISSMS'), + gen_random_uuid()::text + ) primary key +); +``` + +Guidelines: + +- Single database: `bigint identity` (sequential, 8 bytes, SQL-standard) +- Distributed/exposed IDs: UUIDv7 (requires pg_uuidv7) or ULID (time-ordered, no + fragmentation) +- `serial` works but `identity` is SQL-standard and preferred for new + applications +- Avoid random UUIDs (v4) as primary keys on large tables (causes index + fragmentation) + +Reference: +[Identity Columns](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-GENERATED-IDENTITY) diff --git a/.agents/skills/supabase-postgres-best-practices/references/security-privileges.md b/.agents/skills/supabase-postgres-best-practices/references/security-privileges.md new file mode 100644 index 0000000..448ec34 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/security-privileges.md @@ -0,0 +1,54 @@ +--- +title: Apply Principle of Least Privilege +impact: MEDIUM +impactDescription: Reduced attack surface, better audit trail +tags: privileges, security, roles, permissions +--- + +## Apply Principle of Least Privilege + +Grant only the minimum permissions required. Never use superuser for application queries. + +**Incorrect (overly broad permissions):** + +```sql +-- Application uses superuser connection +-- Or grants ALL to application role +grant all privileges on all tables in schema public to app_user; +grant all privileges on all sequences in schema public to app_user; + +-- Any SQL injection becomes catastrophic +-- drop table users; cascades to everything +``` + +**Correct (minimal, specific grants):** + +```sql +-- Create role with no default privileges +create role app_readonly nologin; + +-- Grant only SELECT on specific tables +grant usage on schema public to app_readonly; +grant select on public.products, public.categories to app_readonly; + +-- Create role for writes with limited scope +create role app_writer nologin; +grant usage on schema public to app_writer; +grant select, insert, update on public.orders to app_writer; +grant usage on sequence orders_id_seq to app_writer; +-- No DELETE permission + +-- Login role inherits from these +create role app_user login password 'xxx'; +grant app_writer to app_user; +``` + +Revoke public defaults: + +```sql +-- Revoke default public access +revoke all on schema public from public; +revoke all on all tables in schema public from public; +``` + +Reference: [Roles and Privileges](https://supabase.com/blog/postgres-roles-and-privileges) diff --git a/.agents/skills/supabase-postgres-best-practices/references/security-rls-basics.md b/.agents/skills/supabase-postgres-best-practices/references/security-rls-basics.md new file mode 100644 index 0000000..c61e1a8 --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/security-rls-basics.md @@ -0,0 +1,50 @@ +--- +title: Enable Row Level Security for Multi-Tenant Data +impact: CRITICAL +impactDescription: Database-enforced tenant isolation, prevent data leaks +tags: rls, row-level-security, multi-tenant, security +--- + +## Enable Row Level Security for Multi-Tenant Data + +Row Level Security (RLS) enforces data access at the database level, ensuring users only see their own data. + +**Incorrect (application-level filtering only):** + +```sql +-- Relying only on application to filter +select * from orders where user_id = $current_user_id; + +-- Bug or bypass means all data is exposed! +select * from orders; -- Returns ALL orders +``` + +**Correct (database-enforced RLS):** + +```sql +-- Enable RLS on the table +alter table orders enable row level security; + +-- Create policy for users to see only their orders +create policy orders_user_policy on orders + for all + using (user_id = current_setting('app.current_user_id')::bigint); + +-- Force RLS even for table owners +alter table orders force row level security; + +-- Set user context and query +set app.current_user_id = '123'; +select * from orders; -- Only returns orders for user 123 +``` + +Policy for authenticated role: + +```sql +create policy orders_user_policy on orders + for all + to authenticated + using (user_id = auth.uid()); +``` + +Reference: [Row Level Security](https://supabase.com/docs/guides/database/postgres/row-level-security) diff --git a/.agents/skills/supabase-postgres-best-practices/references/security-rls-performance.md b/.agents/skills/supabase-postgres-best-practices/references/security-rls-performance.md new file mode 100644 index 0000000..b32d92f --- /dev/null +++ b/.agents/skills/supabase-postgres-best-practices/references/security-rls-performance.md @@ -0,0 +1,57 @@ +--- +title: Optimize RLS Policies for Performance +impact: HIGH +impactDescription: 5-10x faster RLS queries with proper patterns +tags: rls, performance, security, optimization +--- + +## Optimize RLS Policies for Performance + +Poorly written RLS policies can cause severe performance issues. Use subqueries and indexes strategically. + +**Incorrect (function called for every row):** + +```sql +create policy orders_policy on orders + using (auth.uid() = user_id); -- auth.uid() called per row! + +-- With 1M rows, auth.uid() is called 1M times +``` + +**Correct (wrap functions in SELECT):** + +```sql +create policy orders_policy on orders + using ((select auth.uid()) = user_id); -- Called once, cached + +-- 100x+ faster on large tables +``` + +Use security definer functions for complex checks: + +```sql +-- Create helper function (runs as definer, bypasses RLS) +create or replace function is_team_member(team_id bigint) +returns boolean +language sql +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.team_members + where team_id = $1 and user_id = (select auth.uid()) + ); +$$; + +-- Use in policy (indexed lookup, not per-row check) +create policy team_orders_policy on orders + using ((select is_team_member(team_id))); +``` + +Always add indexes on columns used in RLS policies: + +```sql +create index orders_user_id_idx on orders (user_id); +``` + +Reference: [RLS Performance](https://supabase.com/docs/guides/database/postgres/row-level-security#rls-performance-recommendations) diff --git a/.claude/skills/supabase-postgres-best-practices b/.claude/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.claude/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.codebuddy/skills/supabase-postgres-best-practices b/.codebuddy/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.codebuddy/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.commandcode/skills/supabase-postgres-best-practices b/.commandcode/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.commandcode/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.continue/skills/supabase-postgres-best-practices b/.continue/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.continue/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.crush/skills/supabase-postgres-best-practices b/.crush/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.crush/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b8cee73 --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +VITE_SUPABASE_URL= +VITE_SUPABASE_ANON_KEY= +VITE_SUPABASE_SCHEMA= diff --git a/.factory/skills/supabase-postgres-best-practices b/.factory/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.factory/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..868bfeb --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Env files +.env +.env.* +!.env.example + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/.goose/skills/supabase-postgres-best-practices b/.goose/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.goose/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.kilocode/skills/supabase-postgres-best-practices b/.kilocode/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.kilocode/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.kiro/skills/supabase-postgres-best-practices b/.kiro/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.kiro/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.mcpjam/skills/supabase-postgres-best-practices b/.mcpjam/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.mcpjam/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.mux/skills/supabase-postgres-best-practices b/.mux/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.mux/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.neovate/skills/supabase-postgres-best-practices b/.neovate/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.neovate/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.openhands/skills/supabase-postgres-best-practices b/.openhands/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.openhands/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.pi/skills/supabase-postgres-best-practices b/.pi/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.pi/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.qoder/skills/supabase-postgres-best-practices b/.qoder/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.qoder/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.qwen/skills/supabase-postgres-best-practices b/.qwen/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.qwen/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.roo/skills/supabase-postgres-best-practices b/.roo/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.roo/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.trae/skills/supabase-postgres-best-practices b/.trae/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.trae/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.windsurf/skills/supabase-postgres-best-practices b/.windsurf/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.windsurf/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/.zencoder/skills/supabase-postgres-best-practices b/.zencoder/skills/supabase-postgres-best-practices new file mode 120000 index 0000000..4990773 --- /dev/null +++ b/.zencoder/skills/supabase-postgres-best-practices @@ -0,0 +1 @@ +../../.agents/skills/supabase-postgres-best-practices \ No newline at end of file diff --git a/Diseño de calendario.png b/Diseño de calendario.png new file mode 100644 index 0000000..57f6341 Binary files /dev/null and b/Diseño de calendario.png differ diff --git a/Ejemplo calendario y vista.png b/Ejemplo calendario y vista.png new file mode 100644 index 0000000..8c8ab35 Binary files /dev/null and b/Ejemplo calendario y vista.png differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e9227fb --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +# Naturcalabacera — Monorepo + +Monorepo with pnpm workspaces. Workspaces: `apps/web`, `apps/api`, `packages/shared`. + +## Getting started + +```bash +pnpm install +pnpm dev:web # start frontend +pnpm dev:api # start API server +pnpm build # build all +pnpm test # run shared package tests +``` + +--- + +## apps/web — React + TypeScript + Vite + +Minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/apps/api/.env.example b/apps/api/.env.example new file mode 100644 index 0000000..ee79242 --- /dev/null +++ b/apps/api/.env.example @@ -0,0 +1,30 @@ +# ───────────────────────────────────────────── +# apps/api — Variables de entorno +# Copia este archivo como .env y rellena los valores. +# NUNCA expongas estas variables al frontend. +# ───────────────────────────────────────────── + +# Servidor +API_PORT=3001 +NODE_ENV=development + +# Supabase (self-hosted) — usar service_role key (bypasea RLS) +SUPABASE_URL=https://tu-supabase.tudominio.com +SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... + +# Resend — servicio de email +# Crear cuenta en https://resend.com y configurar dominio +RESEND_API_KEY=re_... +EMAIL_FROM=Naturcalabacera + +# Destinatarios de notificaciones (parametrizables, sin hardcodear) +NOTIFICATION_EMAIL_TENERIFFA=contacto-teneriffa@ejemplo.com +NOTIFICATION_EMAIL_NATUR=admin@naturcalabacera.com +NOTIFICATION_EMAIL_POOL_HEATING=jonathan@ejemplo.com # "Jonathan o las chicas" + +# URL del frontend para CORS +WEB_ORIGIN=http://localhost:5173 + +# Jobs — runner de notificaciones +JOB_RUNNER_INTERVAL_MS=300000 # 5 minutos (300000ms) +JOB_MAX_RETRIES=3 diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 0000000..cbf45b0 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,25 @@ +{ + "name": "@naturcalabacera/api", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "tsx watch --env-file=.env src/index.ts", + "build": "tsc", + "start": "node dist/index.js", + "lint": "eslint ." + }, + "dependencies": { + "@naturcalabacera/shared": "workspace:*", + "@supabase/supabase-js": "^2.95.3", + "cors": "^2.8.5", + "express": "^4.21.2" + }, + "devDependencies": { + "@types/cors": "^2.8.18", + "@types/express": "^5.0.0", + "@types/node": "^24.10.1", + "tsx": "^4.19.2", + "typescript": "~5.9.3" + } +} diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.ts new file mode 100644 index 0000000..b25325c --- /dev/null +++ b/apps/api/src/config/env.ts @@ -0,0 +1,40 @@ +/** + * Configuración centralizada de variables de entorno. + * Falla al arrancar si faltan variables críticas. + */ + +function required(name: string): string { + const value = process.env[name]; + if (!value) throw new Error(`Variable de entorno requerida: ${name}`); + return value; +} + +function optional(name: string, defaultValue: string): string { + return process.env[name] ?? defaultValue; +} + +export const env = { + // Servidor + PORT: parseInt(optional('API_PORT', '3001'), 10), + NODE_ENV: optional('NODE_ENV', 'development'), + + // Supabase (self-hosted) + SUPABASE_URL: required('SUPABASE_URL'), + SUPABASE_SERVICE_ROLE_KEY: required('SUPABASE_SERVICE_ROLE_KEY'), + + // Email — Resend + RESEND_API_KEY: required('RESEND_API_KEY'), + EMAIL_FROM: optional('EMAIL_FROM', 'Naturcalabacera '), + + // Destinatarios de notificaciones (configurables, sin hardcodear) + NOTIFICATION_EMAIL_TENERIFFA: required('NOTIFICATION_EMAIL_TENERIFFA'), + NOTIFICATION_EMAIL_NATUR: required('NOTIFICATION_EMAIL_NATUR'), + NOTIFICATION_EMAIL_POOL_HEATING: required('NOTIFICATION_EMAIL_POOL_HEATING'), + + // Jobs + JOB_RUNNER_INTERVAL_MS: parseInt(optional('JOB_RUNNER_INTERVAL_MS', '300000'), 10), // 5 min + JOB_MAX_RETRIES: parseInt(optional('JOB_MAX_RETRIES', '3'), 10), + + // Origen del frontend para CORS + WEB_ORIGIN: optional('WEB_ORIGIN', 'http://localhost:5173'), +}; diff --git a/apps/api/src/events/handler.ts b/apps/api/src/events/handler.ts new file mode 100644 index 0000000..5ea693b --- /dev/null +++ b/apps/api/src/events/handler.ts @@ -0,0 +1,252 @@ +import { readFileSync } from 'fs'; +import { join, dirname } from 'path'; +import { fileURLToPath } from 'url'; +import { sendEmail } from '../services/email.js'; +import { env } from '../config/env.js'; +import type { Reservation, NotificationEventType } from '@naturcalabacera/shared'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const TEMPLATES_DIR = join(__dirname, '../templates'); + +/** + * Carga un template HTML y reemplaza las variables {{VARIABLE}}. + */ +function renderTemplate(templateName: string, vars: Record): string { + const filePath = join(TEMPLATES_DIR, `${templateName}.html`); + let html = readFileSync(filePath, 'utf-8'); + for (const [key, value] of Object.entries(vars)) { + html = html.replaceAll(`{{${key}}}`, value); + } + return html; +} + +function formatDate(dateStr: string): string { + const date = new Date(dateStr + 'T12:00:00Z'); + return date.toLocaleDateString('es-ES', { day: '2-digit', month: 'long', year: 'numeric' }); +} + +function formatDateShort(dateStr: string): string { + const date = new Date(dateStr + 'T12:00:00Z'); + return date.toLocaleDateString('es-ES', { day: '2-digit', month: 'short', year: 'numeric' }); +} + +function propertyLabel(property: string): string { + return property === 'los_dragos' ? 'Los Dragos' : 'La Esquinita'; +} + +function nightsCount(start: string, end: string): string { + const d1 = new Date(start + 'T12:00:00Z'); + const d2 = new Date(end + 'T12:00:00Z'); + const nights = Math.round((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24)); + return `${nights} noche${nights === 1 ? '' : 's'}`; +} + +function formatFieldValue(field: string, value: unknown): string { + if (value === null || value === undefined || value === '') return '—'; + if (field === 'start_date' || field === 'end_date') return formatDate(String(value)); + if (field === 'property') return propertyLabel(String(value)); + if (field === 'origin') return value === 'Teneriffa2000' ? 'Teneriffa' : 'Natur'; + if (typeof value === 'boolean') return value ? 'Sí' : 'No'; + return String(value); +} + +/** + * Genera el bloque HTML con la tabla de cambios entre dos versiones de reserva. + * Se incluye solo en emails de tipo "modificada". + */ +function buildChangesBlock(prev: Reservation, curr: Reservation): string { + const FIELD_LABELS: Record = { + client_name: 'Cliente', + start_date: 'Fecha de entrada', + end_date: 'Fecha de salida', + property: 'Propiedad', + adults_count: 'Adultos', + children_count: 'Niños', + has_cleaning: 'Limpieza incluida', + has_pool_heating: 'Calefacción de piscina', + has_flies_products: 'Productos antiparasitarios', + government_registration: 'Registro gubernamental', + observations: 'Observaciones', + is_event: 'Es evento', + event_type: 'Tipo de evento', + attendees_count: 'Nº asistentes', + }; + + const changes: Array<{ label: string; from: string; to: string }> = []; + + for (const [field, label] of Object.entries(FIELD_LABELS)) { + const prevVal = (prev as Record)[field]; + const currVal = (curr as Record)[field]; + const prevStr = formatFieldValue(field, prevVal); + const currStr = formatFieldValue(field, currVal); + if (prevStr !== currStr) { + changes.push({ label, from: prevStr, to: currStr }); + } + } + + if (changes.length === 0) { + return `

Sin cambios detectados en los datos principales.

`; + } + + let rows = ''; + for (const { label, from, to } of changes) { + rows += ` + + ${label} + ${from} + ${to} + `; + } + + return ` +
+

Cambios realizados

+ + + + + + + + + ${rows} +
CampoAntesAhora
+
`; +} + +/** + * Genera el bloque HTML de observaciones si existen. + */ +function buildObservationsBlock(observations?: string): string { + if (!observations || observations.trim() === '') return ''; + return ` +
+

Observaciones

+

${observations}

+
`; +} + +/** + * Genera la lista de servicios adicionales de la reserva. + */ +function buildServicesText(r: Reservation): string { + const services: string[] = []; + if (r.has_cleaning) services.push('Limpieza'); + if (r.has_pool_heating) services.push('Calefacción piscina'); + if (r.has_flies_products) services.push('Antiparasitarios'); + if (r.is_event && r.event_type) { + const label = r.event_type === 'Otro' ? `Evento: ${r.event_type_other ?? 'otro'}` : `Evento: ${r.event_type}`; + services.push(label); + } + return services.length > 0 ? services.join(' · ') : '—'; +} + +interface SendResult { + success: boolean; + error?: string; +} + +/** + * Envía el email correspondiente a un evento de notificación. + * Para reservation.updated acepta previousReservation para mostrar el diff. + */ +export async function handleNotificationEvent( + eventType: NotificationEventType, + reservation: Reservation, + previousReservation?: Reservation +): Promise { + const nights = nightsCount(reservation.start_date, reservation.end_date); + const dateRange = `${formatDateShort(reservation.start_date)} – ${formatDateShort(reservation.end_date)}`; + + const baseVars: Record = { + CLIENT_NAME: reservation.client_name, + START_DATE: formatDate(reservation.start_date), + END_DATE: formatDate(reservation.end_date), + PROPERTY: propertyLabel(reservation.property), + ORIGIN: reservation.origin === 'Teneriffa2000' ? 'Teneriffa' : 'Natur', + ADULTS: String(reservation.adults_count), + CHILDREN: String(reservation.children_count), + TOTAL_PERSONS: String(reservation.adults_count + reservation.children_count), + RESERVATION_ID: reservation.id, + INVOICE_NUMBER: reservation.invoice_number ?? '—', + NIGHTS: nights, + DATE_RANGE: dateRange, + SERVICES: buildServicesText(reservation), + GOVERNMENT_REG: reservation.government_registration ?? '—', + OBSERVATIONS_BLOCK: buildObservationsBlock(reservation.observations), + CHANGES_BLOCK: '', + CANCEL_ALERT: '', + }; + + switch (eventType) { + case 'reservation.created': { + const isTeenriffa = reservation.origin === 'Teneriffa2000'; + const template = isTeenriffa ? 'teneriffa-crud' : 'natur-crud'; + const originLabel = isTeenriffa ? 'Teneriffa' : 'Natur'; + const vars = { + ...baseVars, + ACTION: 'creada', + ACTION_LABEL: 'Nueva Reserva', + CHANGES_BLOCK: '', + }; + const html = renderTemplate(template, vars); + const subject = `[NUEVA RESERVA] ${originLabel} — ${reservation.client_name} | ${propertyLabel(reservation.property)} | ${dateRange}`; + return sendEmail({ to: [env.NOTIFICATION_EMAIL_TENERIFFA, env.NOTIFICATION_EMAIL_NATUR], subject, html }); + } + + case 'reservation.updated': { + const isTeenriffa = reservation.origin === 'Teneriffa2000'; + const template = isTeenriffa ? 'teneriffa-crud' : 'natur-crud'; + const originLabel = isTeenriffa ? 'Teneriffa' : 'Natur'; + const changesBlock = previousReservation + ? buildChangesBlock(previousReservation, reservation) + : `

No se recibieron datos anteriores para comparar.

`; + const vars = { + ...baseVars, + ACTION: 'modificada', + ACTION_LABEL: 'Reserva Modificada', + CHANGES_BLOCK: changesBlock, + }; + const html = renderTemplate(template, vars); + const subject = `[MODIFICADA] ${originLabel} — ${reservation.client_name} | ${propertyLabel(reservation.property)} | ${dateRange}`; + return sendEmail({ to: [env.NOTIFICATION_EMAIL_TENERIFFA, env.NOTIFICATION_EMAIL_NATUR], subject, html }); + } + + case 'reservation.cancelled': { + const isTeenriffa = reservation.origin === 'Teneriffa2000'; + const template = isTeenriffa ? 'teneriffa-crud' : 'natur-crud'; + const originLabel = isTeenriffa ? 'Teneriffa' : 'Natur'; + const vars = { + ...baseVars, + ACTION: 'cancelada', + ACTION_LABEL: 'Reserva Cancelada', + CHANGES_BLOCK: '', + CANCEL_ALERT: `

Esta reserva ha sido cancelada y eliminada del sistema.

`, + }; + const html = renderTemplate(template, vars); + const subject = `[CANCELADA] ${originLabel} — ${reservation.client_name} | ${propertyLabel(reservation.property)} | ${dateRange}`; + return sendEmail({ to: [env.NOTIFICATION_EMAIL_TENERIFFA, env.NOTIFICATION_EMAIL_NATUR], subject, html }); + } + + case 'reservation.reminder_24h': { + const html = renderTemplate('reminder-24h', baseVars); + const subject = `Recordatorio: Check-in mañana — ${reservation.client_name} (Los Dragos)`; + return sendEmail({ to: env.NOTIFICATION_EMAIL_TENERIFFA, subject, html }); + } + + case 'reservation.invoice_second_notice': { + const html = renderTemplate('invoice-10d', baseVars); + const subject = `Segunda factura en 10 días — ${reservation.client_name} (${propertyLabel(reservation.property)})`; + return sendEmail({ to: env.NOTIFICATION_EMAIL_NATUR, subject, html }); + } + + case 'reservation.pool_heating_notice': { + const html = renderTemplate('pool-heating-48h', baseVars); + const subject = `Calefacción de piscina en 48h — ${reservation.client_name} (${propertyLabel(reservation.property)})`; + return sendEmail({ to: env.NOTIFICATION_EMAIL_POOL_HEATING, subject, html }); + } + + default: + return { success: false, error: `Tipo de evento desconocido: ${eventType}` }; + } +} diff --git a/apps/api/src/events/types.ts b/apps/api/src/events/types.ts new file mode 100644 index 0000000..ec479eb --- /dev/null +++ b/apps/api/src/events/types.ts @@ -0,0 +1,67 @@ +import type { NotificationEventType } from '@naturcalabacera/shared'; +import type { Reservation, ReservationOrigin, Property } from '@naturcalabacera/shared'; + +export type CrudOperation = 'created' | 'updated' | 'cancelled'; + +/** + * Condiciones que determinan si se envía un evento de notificación. + * Permiten evaluar de forma declarativa sin dispersar la lógica. + */ +export interface NotificationCondition { + origin?: ReservationOrigin; + property?: Property; + hasPoolHeating?: boolean; +} + +/** + * Descriptor de cada tipo de evento: + * - conditions: cuándo se dispara + * - recipientEnvKey: qué env var contiene el destinatario + * - templateName: nombre del template HTML + * - offsetDays: días antes del check-in (para eventos programados; undefined = inmediato) + */ +export interface EventDescriptor { + eventType: NotificationEventType; + conditions: NotificationCondition; + recipientEnvKey: 'NOTIFICATION_EMAIL_TENERIFFA' | 'NOTIFICATION_EMAIL_NATUR' | 'NOTIFICATION_EMAIL_POOL_HEATING'; + templateName: string; + offsetDays?: number; // undefined = disparo inmediato (CRUD) +} + +/** + * Mapa declarativo de todos los eventos del sistema. + * Añadir un nuevo tipo de notificación = añadir una entrada aquí. + */ +export const EVENT_DESCRIPTORS: EventDescriptor[] = [ + { + eventType: 'reservation.reminder_24h', + conditions: { origin: 'Teneriffa2000', property: 'los_dragos' }, + recipientEnvKey: 'NOTIFICATION_EMAIL_TENERIFFA', + templateName: 'reminder-24h', + offsetDays: 1, + }, + { + eventType: 'reservation.invoice_second_notice', + conditions: { origin: 'Naturcalabacera' }, + recipientEnvKey: 'NOTIFICATION_EMAIL_NATUR', + templateName: 'invoice-10d', + offsetDays: 10, + }, + { + eventType: 'reservation.pool_heating_notice', + conditions: { hasPoolHeating: true }, + recipientEnvKey: 'NOTIFICATION_EMAIL_POOL_HEATING', + templateName: 'pool-heating-48h', + offsetDays: 2, + }, +]; + +/** + * Evalúa si una reserva cumple las condiciones de un descriptor de evento. + */ +export function matchesConditions(reservation: Reservation, conditions: NotificationCondition): boolean { + if (conditions.origin && reservation.origin !== conditions.origin) return false; + if (conditions.property && reservation.property !== conditions.property) return false; + if (conditions.hasPoolHeating !== undefined && reservation.has_pool_heating !== conditions.hasPoolHeating) return false; + return true; +} diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts new file mode 100644 index 0000000..1793f25 --- /dev/null +++ b/apps/api/src/index.ts @@ -0,0 +1,38 @@ +import express from 'express'; +import cors from 'cors'; +import { env } from './config/env.js'; +import { healthRouter } from './routes/health.js'; +import { notificationsRouter } from './routes/notifications.js'; +import { usersRouter } from './routes/users.js'; +import { runPendingJobs } from './jobs/runner.js'; + +const app = express(); + +// Middlewares +const allowedOrigin = env.NODE_ENV === 'development' + ? (origin: string | undefined, cb: (e: Error | null, ok?: boolean) => void) => cb(null, true) + : env.WEB_ORIGIN; +app.use(cors({ origin: allowedOrigin, credentials: true })); +app.use(express.json()); + +// Rutas +app.use('/health', healthRouter); +app.use('/api/notifications', notificationsRouter); +app.use('/api/users', usersRouter); + +// Arrancar servidor +app.listen(env.PORT, () => { + console.log(`[api] Servidor iniciado en puerto ${env.PORT} (${env.NODE_ENV})`); +}); + +// Job runner — procesa notificaciones pendientes cada JOB_RUNNER_INTERVAL_MS +// Solo una instancia debería ejecutarlo; el locking en BD evita duplicados si hay varias. +console.log(`[api] Job runner iniciado (intervalo: ${env.JOB_RUNNER_INTERVAL_MS / 1000}s)`); + +// Primera ejecución inmediata +runPendingJobs().catch(err => console.error('[jobs] Error en primera ejecución:', err)); + +// Ejecuciones periódicas +setInterval(() => { + runPendingJobs().catch(err => console.error('[jobs] Error en runner:', err)); +}, env.JOB_RUNNER_INTERVAL_MS); diff --git a/apps/api/src/jobs/runner.ts b/apps/api/src/jobs/runner.ts new file mode 100644 index 0000000..5cd3821 --- /dev/null +++ b/apps/api/src/jobs/runner.ts @@ -0,0 +1,168 @@ +import { supabaseAdmin } from '../lib/supabase.js'; +import { handleNotificationEvent } from '../events/handler.js'; +import { env } from '../config/env.js'; +import type { NotificationEventType, Reservation } from '@naturcalabacera/shared'; + +/** + * Runner de jobs con garantías de idempotencia y robustez: + * + * - Selecciona eventos pendientes con FOR UPDATE SKIP LOCKED (via RPC) + * para que múltiples instancias no procesen el mismo evento. + * - Actualiza status a 'processing' antes de procesar. + * - En éxito: status = 'sent'. En fallo: incrementa attempts, registra error. + * - Reintentos máximos configurables (JOB_MAX_RETRIES). + * - Todas las comparaciones de fechas en UTC. + */ + +interface NotificationRow { + id: string; + reservation_id: string; + event_type: NotificationEventType; + attempts: number; +} + +export async function runPendingJobs(): Promise { + const now = new Date().toISOString(); + + // Selecciona hasta 10 eventos pendientes cuyo scheduled_for ya ha pasado + // y que no hayan superado el máximo de reintentos + const { data: events, error: fetchError } = await supabaseAdmin + .from('notification_events') + .select('id, reservation_id, event_type, attempts') + .eq('status', 'pending') + .lte('scheduled_for', now) + .lt('attempts', env.JOB_MAX_RETRIES) + .order('scheduled_for', { ascending: true }) + .limit(10); + + if (fetchError) { + console.error('[jobs] Error al obtener eventos pendientes:', fetchError.message); + return; + } + + if (!events || events.length === 0) return; + + console.log(`[jobs] Procesando ${events.length} evento(s)...`); + + for (const event of events as NotificationRow[]) { + // Marcar como 'processing' para evitar que otra instancia lo tome + const { error: lockError } = await supabaseAdmin + .from('notification_events') + .update({ status: 'processing', attempts: event.attempts + 1 }) + .eq('id', event.id) + .eq('status', 'pending'); // Solo actualiza si sigue en pending (evita race) + + if (lockError) { + console.warn(`[jobs] Evento ${event.id} ya tomado por otra instancia`); + continue; + } + + // Obtener la reserva completa + const { data: reservation, error: resError } = await supabaseAdmin + .from('reservations') + .select('*') + .eq('id', event.reservation_id) + .single(); + + if (resError || !reservation) { + await markFailed(event.id, `Reserva no encontrada: ${event.reservation_id}`); + continue; + } + + // Procesar el evento + const result = await handleNotificationEvent(event.event_type, reservation as Reservation); + + if (result.success) { + await supabaseAdmin + .from('notification_events') + .update({ status: 'sent', sent_at: new Date().toISOString() }) + .eq('id', event.id); + console.log(`[jobs] ✓ Evento ${event.event_type} para reserva ${event.reservation_id}`); + } else { + const isLastAttempt = event.attempts + 1 >= env.JOB_MAX_RETRIES; + await supabaseAdmin + .from('notification_events') + .update({ + status: isLastAttempt ? 'failed' : 'pending', + last_error: result.error ?? 'Error desconocido', + }) + .eq('id', event.id); + console.error(`[jobs] ✗ Evento ${event.event_type}: ${result.error}`); + } + } +} + +async function markFailed(eventId: string, error: string): Promise { + await supabaseAdmin + .from('notification_events') + .update({ status: 'failed', last_error: error }) + .eq('id', eventId); +} + +/** + * Inserta eventos de notificación para una reserva según las condiciones del evento. + * Usa ON CONFLICT DO NOTHING para idempotencia — si ya existe, no hace nada. + */ +export async function scheduleNotificationsForReservation( + reservation: Reservation, + operation: 'created' | 'updated' | 'cancelled' +): Promise { + const eventsToInsert = []; + const startDate = new Date(reservation.start_date + 'T12:00:00Z'); + const now = new Date().toISOString(); + + // El email CRUD se envía directamente en la ruta, no se encola aquí. + + // 2. Recordatorio 24h antes — solo Teneriffa + Los Dragos + if (reservation.origin === 'Teneriffa2000' && reservation.property === 'los_dragos') { + const scheduled = new Date(startDate); + scheduled.setUTCHours(scheduled.getUTCHours() - 24); + if (scheduled > new Date()) { + eventsToInsert.push({ + reservation_id: reservation.id, + event_type: 'reservation.reminder_24h', + scheduled_for: scheduled.toISOString(), + status: 'pending', + }); + } + } + + // 3. Segunda factura 10 días antes — solo Natur + if (reservation.origin === 'Naturcalabacera') { + const scheduled = new Date(startDate); + scheduled.setUTCDate(scheduled.getUTCDate() - 10); + if (scheduled > new Date()) { + eventsToInsert.push({ + reservation_id: reservation.id, + event_type: 'reservation.invoice_second_notice', + scheduled_for: scheduled.toISOString(), + status: 'pending', + }); + } + } + + // 4. Aviso calefacción piscina 48h antes + if (reservation.has_pool_heating) { + const scheduled = new Date(startDate); + scheduled.setUTCHours(scheduled.getUTCHours() - 48); + if (scheduled > new Date()) { + eventsToInsert.push({ + reservation_id: reservation.id, + event_type: 'reservation.pool_heating_notice', + scheduled_for: scheduled.toISOString(), + status: 'pending', + }); + } + } + + if (eventsToInsert.length === 0) return; + + // onConflict con la constraint UNIQUE(reservation_id, event_type, scheduled_for) + const { error } = await supabaseAdmin + .from('notification_events') + .upsert(eventsToInsert, { onConflict: 'reservation_id,event_type,scheduled_for', ignoreDuplicates: true }); + + if (error) { + console.error('[jobs] Error al insertar notification_events:', error.message); + } +} diff --git a/apps/api/src/lib/supabase.ts b/apps/api/src/lib/supabase.ts new file mode 100644 index 0000000..49a0b7e --- /dev/null +++ b/apps/api/src/lib/supabase.ts @@ -0,0 +1,19 @@ +import { createClient } from '@supabase/supabase-js'; +import { env } from '../config/env.js'; + +/** + * Cliente Supabase con service_role key. + * Solo usar en el backend — nunca exponer al frontend. + * Bypasea RLS: úsalo con precaución. + */ +export const supabaseAdmin = createClient( + env.SUPABASE_URL, + env.SUPABASE_SERVICE_ROLE_KEY, + { + db: { schema: 'natur_reservas' }, + auth: { + autoRefreshToken: false, + persistSession: false, + }, + } +); diff --git a/apps/api/src/routes/health.ts b/apps/api/src/routes/health.ts new file mode 100644 index 0000000..eb7d3c0 --- /dev/null +++ b/apps/api/src/routes/health.ts @@ -0,0 +1,9 @@ +import { Router } from 'express'; + +const router = Router(); + +router.get('/', (_req, res) => { + res.json({ status: 'ok', timestamp: new Date().toISOString() }); +}); + +export { router as healthRouter }; diff --git a/apps/api/src/routes/notifications.ts b/apps/api/src/routes/notifications.ts new file mode 100644 index 0000000..3011996 --- /dev/null +++ b/apps/api/src/routes/notifications.ts @@ -0,0 +1,67 @@ +import { Router } from 'express'; +import { scheduleNotificationsForReservation } from '../jobs/runner.js'; +import { handleNotificationEvent } from '../events/handler.js'; +import { supabaseAdmin } from '../lib/supabase.js'; +import type { Reservation } from '@naturcalabacera/shared'; + +const router = Router(); + +/** + * POST /api/notifications/reservation-event + * + * Llamado por el frontend tras cada operación CRUD exitosa. + * - Envía el email CRUD inmediatamente (sin pasar por la cola) + * - Encola los eventos futuros (recordatorios, facturas, etc.) + * + * Body: { reservation: Reservation, operation: 'created' | 'updated' | 'cancelled' } + */ +router.post('/reservation-event', async (req, res) => { + const { reservation, operation, previousReservation } = req.body as { + reservation: Reservation; + operation: 'created' | 'updated' | 'cancelled'; + previousReservation?: Reservation; + }; + + if (!reservation || !operation) { + return res.status(400).json({ error: 'reservation y operation son requeridos' }); + } + + if (!['created', 'updated', 'cancelled'].includes(operation)) { + return res.status(400).json({ error: 'operation debe ser created, updated o cancelled' }); + } + + try { + // Enviar email CRUD al momento, sin esperar al job runner + const eventType = `reservation.${operation}` as const; + const now = new Date().toISOString(); + const emailResult = await handleNotificationEvent(eventType, reservation, previousReservation); + + // Registrar el evento en notification_events (historial) + await supabaseAdmin.from('notification_events').insert({ + reservation_id: reservation.id, + event_type: eventType, + scheduled_for: now, + status: emailResult.success ? 'sent' : 'failed', + sent_at: emailResult.success ? now : null, + last_error: emailResult.success ? null : (emailResult.error ?? 'Error desconocido'), + attempts: 1, + }); + + if (!emailResult.success) { + console.error(`[notifications] Email CRUD fallido: ${emailResult.error}`); + } else { + console.log(`[notifications] ✓ Email enviado para ${eventType} — ${reservation.client_name}`); + } + + // Encolar eventos futuros (recordatorios, avisos, etc.) + await scheduleNotificationsForReservation(reservation, operation); + + return res.json({ ok: true }); + } catch (err) { + const message = err instanceof Error ? err.message : 'Error interno'; + console.error('[notifications] Error:', message); + return res.status(500).json({ error: message }); + } +}); + +export { router as notificationsRouter }; diff --git a/apps/api/src/routes/users.ts b/apps/api/src/routes/users.ts new file mode 100644 index 0000000..541bc81 --- /dev/null +++ b/apps/api/src/routes/users.ts @@ -0,0 +1,154 @@ +import { Router, type Request, type Response, type NextFunction } from 'express'; +import { supabaseAdmin } from '../lib/supabase.js'; +import type { UserRole } from '@naturcalabacera/shared'; + +const router = Router(); + +const VALID_ROLES: UserRole[] = ['admin', 'internal_staff', 'external_availability_viewer']; + +/** + * Middleware: extrae el JWT del header Authorization, valida la sesión con + * Supabase y comprueba que el usuario es admin. Si pasa, deja el id del + * caller en res.locals.callerId. + */ +async function requireAdmin(req: Request, res: Response, next: NextFunction): Promise { + const auth = req.headers.authorization; + if (!auth || !auth.startsWith('Bearer ')) { + res.status(401).json({ error: 'Falta token de autenticación' }); + return; + } + const token = auth.slice('Bearer '.length); + + const { data: userData, error: userError } = await supabaseAdmin.auth.getUser(token); + if (userError || !userData.user) { + res.status(401).json({ error: 'Token inválido' }); + return; + } + + const { data: profile, error: profileError } = await supabaseAdmin + .from('user_profiles') + .select('role') + .eq('id', userData.user.id) + .single(); + + if (profileError || !profile) { + res.status(403).json({ error: 'Perfil no encontrado' }); + return; + } + + if (profile.role !== 'admin') { + res.status(403).json({ error: 'Solo admins pueden gestionar usuarios' }); + return; + } + + res.locals.callerId = userData.user.id; + next(); +} + +// GET /api/users — listar todos los perfiles +router.get('/', requireAdmin, async (_req, res) => { + const { data, error } = await supabaseAdmin + .from('user_profiles') + .select('id, email, role, display_name, created_at') + .order('created_at', { ascending: false }); + + if (error) { + return res.status(500).json({ error: error.message }); + } + return res.json({ users: data ?? [] }); +}); + +// POST /api/users/invite — invitar un usuario nuevo +router.post('/invite', requireAdmin, async (req, res) => { + const { email, role, display_name } = req.body as { + email?: string; + role?: UserRole; + display_name?: string; + }; + + if (!email || !role) { + return res.status(400).json({ error: 'email y role son requeridos' }); + } + if (!VALID_ROLES.includes(role)) { + return res.status(400).json({ error: 'Rol inválido' }); + } + + // 1. Invitar al usuario por email (envía correo con magic link) + const { data: invited, error: inviteError } = await supabaseAdmin.auth.admin.inviteUserByEmail(email); + if (inviteError || !invited.user) { + return res.status(400).json({ error: inviteError?.message ?? 'Error al invitar usuario' }); + } + + // 2. Crear el perfil con el rol seleccionado + const { data: profile, error: profileError } = await supabaseAdmin + .from('user_profiles') + .insert({ + id: invited.user.id, + email, + role, + display_name: display_name ?? null, + }) + .select() + .single(); + + if (profileError) { + // Best-effort cleanup: eliminar el usuario auth si el perfil falló + await supabaseAdmin.auth.admin.deleteUser(invited.user.id).catch(() => {}); + return res.status(500).json({ error: profileError.message }); + } + + return res.status(201).json({ user: profile }); +}); + +// PATCH /api/users/:id — actualizar rol o display_name +router.patch('/:id', requireAdmin, async (req, res) => { + const { id } = req.params; + const { role, display_name } = req.body as { + role?: UserRole; + display_name?: string; + }; + + if (role !== undefined && !VALID_ROLES.includes(role)) { + return res.status(400).json({ error: 'Rol inválido' }); + } + + const updates: Record = {}; + if (role !== undefined) updates.role = role; + if (display_name !== undefined) updates.display_name = display_name; + + if (Object.keys(updates).length === 0) { + return res.status(400).json({ error: 'Nada que actualizar' }); + } + + const { data, error } = await supabaseAdmin + .from('user_profiles') + .update(updates) + .eq('id', id) + .select() + .single(); + + if (error) { + return res.status(500).json({ error: error.message }); + } + return res.json({ user: data }); +}); + +// DELETE /api/users/:id — eliminar usuario auth + perfil +router.delete('/:id', requireAdmin, async (req, res) => { + const id = req.params.id as string; + const callerId = res.locals.callerId as string; + + if (id === callerId) { + return res.status(400).json({ error: 'No puedes eliminar tu propia cuenta' }); + } + + // ON DELETE CASCADE en user_profiles.id elimina el perfil al eliminar el usuario auth. + const { error } = await supabaseAdmin.auth.admin.deleteUser(id); + if (error) { + return res.status(500).json({ error: error.message }); + } + + return res.json({ ok: true }); +}); + +export { router as usersRouter }; diff --git a/apps/api/src/services/email.ts b/apps/api/src/services/email.ts new file mode 100644 index 0000000..c7fe816 --- /dev/null +++ b/apps/api/src/services/email.ts @@ -0,0 +1,50 @@ +import { env } from '../config/env.js'; + +interface SendEmailOptions { + to: string | string[]; + subject: string; + html: string; + replyTo?: string; +} + +interface ResendResponse { + id?: string; + error?: { message: string; name: string }; +} + +/** + * Envía un email usando la API de Resend. + * Docs: https://resend.com/docs/api-reference/emails/send-email + */ +export async function sendEmail(options: SendEmailOptions): Promise<{ success: boolean; id?: string; error?: string }> { + try { + const res = await fetch('https://api.resend.com/emails', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${env.RESEND_API_KEY}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + from: env.EMAIL_FROM, + to: Array.isArray(options.to) ? options.to : [options.to], + subject: options.subject, + html: options.html, + ...(options.replyTo && { reply_to: options.replyTo }), + }), + }); + + const data = await res.json() as ResendResponse; + + if (!res.ok || data.error) { + const errorMsg = data.error?.message ?? `HTTP ${res.status}`; + console.error('[email] Error al enviar:', errorMsg); + return { success: false, error: errorMsg }; + } + + return { success: true, id: data.id }; + } catch (err) { + const errorMsg = err instanceof Error ? err.message : 'Error desconocido'; + console.error('[email] Error de red:', errorMsg); + return { success: false, error: errorMsg }; + } +} diff --git a/apps/api/src/templates/invoice-10d.html b/apps/api/src/templates/invoice-10d.html new file mode 100644 index 0000000..e22d750 --- /dev/null +++ b/apps/api/src/templates/invoice-10d.html @@ -0,0 +1,64 @@ + + + + + Segunda Factura en 10 días + + + +
+
+

📋 Segunda Factura — Natur

+

Aviso automático 10 días antes · Naturcalabacera

+
+
+
+ Aviso: La reserva de {{CLIENT_NAME}} comienza en 10 días. Pendiente segunda factura. +
+
+
+ + {{CLIENT_NAME}} +
+
+ + {{PROPERTY}} +
+
+ + {{INVOICE_NUMBER}} +
+
+ + {{TOTAL_PERSONS}} +
+
+ + {{START_DATE}} +
+
+ + {{END_DATE}} +
+
+
+ +
+ + diff --git a/apps/api/src/templates/natur-crud.html b/apps/api/src/templates/natur-crud.html new file mode 100644 index 0000000..706c9c5 --- /dev/null +++ b/apps/api/src/templates/natur-crud.html @@ -0,0 +1,120 @@ + + + + + {{ACTION_LABEL}} — Natur + + + +
+ + +
+
{{ACTION_LABEL}}
+

{{CLIENT_NAME}}

+

{{PROPERTY}}  ·  {{NIGHTS}}  ·  Natur

+

{{DATE_RANGE}}

+
+ +
+ + + {{CANCEL_ALERT}} + + +

Datos de la reserva

+
+
+ + {{PROPERTY}} +
+
+ + {{INVOICE_NUMBER}} +
+
+ + {{START_DATE}} +
+
+ + {{END_DATE}} +
+
+ + {{ADULTS}} +
+
+ + {{CHILDREN}} +
+
+ + {{GOVERNMENT_REG}} +
+
+ + {{SERVICES}} +
+
+ + + {{OBSERVATIONS_BLOCK}} + + + {{CHANGES_BLOCK}} + +
+ + +
+ + diff --git a/apps/api/src/templates/pool-heating-48h.html b/apps/api/src/templates/pool-heating-48h.html new file mode 100644 index 0000000..8e52a17 --- /dev/null +++ b/apps/api/src/templates/pool-heating-48h.html @@ -0,0 +1,61 @@ + + + + + Aviso Calefacción de Piscina + + + +
+
+

🌡️ Calefacción de Piscina — 48h

+

Aviso automático · Naturcalabacera

+
+
+
+ Acción requerida: En 48 horas llega {{CLIENT_NAME}} a {{PROPERTY}} con calefacción de piscina activada. + Por favor, encender la calefacción de piscina con suficiente antelación. +
+
+
+ + {{CLIENT_NAME}} +
+
+ + {{PROPERTY}} +
+
+ + {{START_DATE}} +
+
+ + {{END_DATE}} +
+
+ + {{TOTAL_PERSONS}} +
+
+
+ +
+ + diff --git a/apps/api/src/templates/reminder-24h.html b/apps/api/src/templates/reminder-24h.html new file mode 100644 index 0000000..d3083a4 --- /dev/null +++ b/apps/api/src/templates/reminder-24h.html @@ -0,0 +1,60 @@ + + + + + Recordatorio Check-in Mañana + + + +
+
+

⏰ Check-in Mañana — Los Dragos

+

Recordatorio automático 24h · Naturcalabacera

+
+
+
+ Recordatorio: Mañana llega {{CLIENT_NAME}} a Los Dragos. +
+
+
+ + {{CLIENT_NAME}} +
+
+ + {{INVOICE_NUMBER}} +
+
+ + {{START_DATE}} +
+
+ + {{END_DATE}} +
+
+ + {{TOTAL_PERSONS}} +
+
+
+ +
+ + diff --git a/apps/api/src/templates/teneriffa-crud.html b/apps/api/src/templates/teneriffa-crud.html new file mode 100644 index 0000000..5c83da0 --- /dev/null +++ b/apps/api/src/templates/teneriffa-crud.html @@ -0,0 +1,112 @@ + + + + + {{ACTION_LABEL}} — Teneriffa + + + +
+ + +
+
{{ACTION_LABEL}}
+

{{CLIENT_NAME}}

+

{{PROPERTY}}  ·  {{NIGHTS}}  ·  Teneriffa

+

{{DATE_RANGE}}

+
+ +
+ + + {{CANCEL_ALERT}} + + +

Datos de la reserva

+
+
+ + {{PROPERTY}} +
+
+ + {{INVOICE_NUMBER}} +
+
+ + {{START_DATE}} +
+
+ + {{END_DATE}} +
+
+ + {{ADULTS}} +
+
+ + {{CHILDREN}} +
+
+ + {{GOVERNMENT_REG}} +
+
+ + {{SERVICES}} +
+
+ + + {{OBSERVATIONS_BLOCK}} + + + {{CHANGES_BLOCK}} + +
+ + +
+ + diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 0000000..2d23d6c --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "skipLibCheck": true, + "esModuleInterop": true, + "declaration": true, + "paths": { + "@naturcalabacera/shared": ["../../packages/shared/src/index.ts"], + "@naturcalabacera/shared/*": ["../../packages/shared/src/*"] + } + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/web/.env.example b/apps/web/.env.example new file mode 100644 index 0000000..4a9ea84 --- /dev/null +++ b/apps/web/.env.example @@ -0,0 +1,15 @@ +# ───────────────────────────────────────────── +# apps/web — Variables de entorno +# Copia este archivo como .env y rellena los valores. +# Los prefijos VITE_ son accesibles en el navegador. +# ───────────────────────────────────────────── + +# Supabase (self-hosted) +VITE_SUPABASE_URL=https://tu-supabase.tudominio.com +VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... + +# URL del backend API (apps/api) +VITE_API_URL=http://localhost:3001 + +# Chatbot — poner true para mostrar el contenedor inferior +VITE_CHATBOT_ENABLED=false diff --git a/apps/web/eslint.config.js b/apps/web/eslint.config.js new file mode 100644 index 0000000..5e6b472 --- /dev/null +++ b/apps/web/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..eac8330 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,13 @@ + + + + + + + reservas-app + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..3730646 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,42 @@ +{ + "name": "@naturcalabacera/web", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@naturcalabacera/shared": "workspace:*", + "@supabase/supabase-js": "^2.95.3", + "clsx": "^2.1.1", + "date-fns": "^4.1.0", + "framer-motion": "^12.33.0", + "lucide-react": "^0.563.0", + "react": "^19.2.0", + "react-dom": "^19.2.0", + "react-hook-form": "^7.71.1", + "sonner": "^2.0.7", + "tailwind-merge": "^3.4.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@types/node": "^24.10.1", + "@types/react": "^19.2.5", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.1.1", + "autoprefixer": "^10.4.24", + "eslint": "^9.39.1", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.4.24", + "globals": "^16.5.0", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.19", + "typescript": "~5.9.3", + "typescript-eslint": "^8.46.4", + "vite": "^7.2.4" + } +} diff --git a/apps/web/postcss.config.js b/apps/web/postcss.config.js new file mode 100644 index 0000000..2e7af2b --- /dev/null +++ b/apps/web/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/apps/web/public/vite.svg b/apps/web/public/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/apps/web/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/App.css b/apps/web/src/App.css new file mode 100644 index 0000000..b9d355d --- /dev/null +++ b/apps/web/src/App.css @@ -0,0 +1,42 @@ +#root { + max-width: 1280px; + margin: 0 auto; + padding: 2rem; + text-align: center; +} + +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx new file mode 100644 index 0000000..dea6919 --- /dev/null +++ b/apps/web/src/App.tsx @@ -0,0 +1,275 @@ +import { useState, useEffect } from 'react'; +import { useReservations } from './hooks/useReservations'; +import { usePropertyTheme } from './hooks/usePropertyTheme'; +import { Sidebar } from './components/Sidebar'; +import { MobileNavigation } from './components/MobileNavigation'; +import { CalendarGrid } from './components/CalendarGrid'; +import { ReservationModal } from './components/ReservationModal'; +import { SearchBar } from './components/SearchBar'; +import { SettingsPage } from './components/SettingsPage'; +import { YearlyCalendar } from './components/YearlyCalendar'; +import { UserManagement } from './components/UserManagement'; +import { LoginPage } from './components/LoginPage'; +import { ChatbotContainer } from './components/ChatbotContainer'; +import { useAuth } from './hooks/useAuth'; +import { PropertyProvider, useProperty } from './contexts/PropertyContext'; +import { UserRoleProvider, useUserRoleContext } from './contexts/UserRoleContext'; +import type { NewReservation, Reservation } from './types'; +import { format } from 'date-fns'; +import { Plus, Loader2 } from 'lucide-react'; +import { Toaster, toast } from 'sonner'; + +// Componente interno que ya tiene acceso al PropertyContext y UserRoleContext +function AppContent() { + const { property } = useProperty(); + const theme = usePropertyTheme(); + const { isViewer, isStaff, isAdmin } = useUserRoleContext(); + const { + reservations, + loading: reservationsLoading, + createReservation, + updateReservation, + deleteReservation, + refreshResolver, + } = useReservations(property); + + const [currentView, setCurrentView] = useState('calendar'); + const [modalOpen, setModalOpen] = useState(false); + const [modalMode, setModalMode] = useState<'create' | 'edit'>('create'); + const [selectedReservation, setSelectedReservation] = useState>({}); + const [searchTerm, setSearchTerm] = useState(''); + + const filteredReservations = reservations.filter(res => + res.client_name.toLowerCase().includes(searchTerm.toLowerCase()) + ); + + const handleSelectReservation = (event: Reservation) => { + setSelectedReservation(event); + setModalMode('edit'); + setModalOpen(true); + }; + + const handleSelectDay = (day: Date) => { + setSelectedReservation({ + start_date: format(day, 'yyyy-MM-dd'), + end_date: format(day, 'yyyy-MM-dd'), + origin: 'Teneriffa2000', + adults_count: 2, + children_count: 0, + }); + setModalMode('create'); + setModalOpen(true); + }; + + const handleSelectRange = (start: Date, end: Date) => { + setSelectedReservation({ + start_date: format(start, 'yyyy-MM-dd'), + end_date: format(end, 'yyyy-MM-dd'), + origin: 'Teneriffa2000', + adults_count: 2, + children_count: 0, + }); + setModalMode('create'); + setModalOpen(true); + }; + + const handleSave = async (data: NewReservation): Promise => { + try { + let savedReservation: Reservation; + const previousSnapshot = modalMode === 'edit' ? { ...selectedReservation } as Reservation : undefined; + if (modalMode === 'create') { + savedReservation = await createReservation(data); + } else { + if (selectedReservation.id) { + await updateReservation(selectedReservation.id, data); + savedReservation = { ...selectedReservation, ...data } as Reservation; + } else { + return; + } + } + refreshResolver(); + toast.success('Reserva guardada correctamente'); + + // Notificar al API backend para programar notificaciones + const operation = modalMode === 'create' ? 'created' : 'updated'; + void notifyApi(savedReservation, operation, previousSnapshot); + return savedReservation; + } catch (error) { + console.error('Error saving:', error); + toast.error('Error al guardar la reserva'); + } + }; + + const handleDelete = async (id: string) => { + try { + const reservationToDelete = reservations.find(r => r.id === id); + await deleteReservation(id); + setModalOpen(false); + refreshResolver(); + toast.success('Reserva eliminada correctamente'); + + if (reservationToDelete) { + void notifyApi(reservationToDelete, 'cancelled'); + } + } catch (error) { + console.error('Error deleting:', error); + toast.error('Error al eliminar la reserva'); + } + }; + + return ( +
+ + + +
+
+ {/* Relative container: center title absolutely, left/right content on sides */} +
+ {/* Left: status dot + tagline (desktop only) */} +
+ + + Gestiona tus reservas y disponibilidad + +
+ + {/* Center: property name — always truly centered */} +

+ {theme.name} +

+ + {/* Right: Nueva Reserva button */} + {isStaff && ( +
+ +
+ )} +
+ + {/* Mobile subtitle below title */} +
+ + + Gestiona tus reservas y disponibilidad + +
+
+ +
+ {currentView === 'calendar' && ( + <> + + + + )} + {currentView === 'settings' && } + {currentView === 'yearly' && ( + + )} + {currentView === 'users' && isAdmin && } +
+ + +
+ + + + {isStaff && ( + setModalOpen(false)} + onSave={handleSave} + onDelete={handleDelete} + /> + )} +
+ ); +} + +// Llama al API backend para programar notificaciones (fire-and-forget) +async function notifyApi( + reservation: Reservation, + operation: 'created' | 'updated' | 'cancelled', + previousReservation?: Reservation +) { + const apiUrl = import.meta.env.VITE_API_URL; + if (!apiUrl) return; // Si no hay API configurada, skip silencioso + + try { + await fetch(`${apiUrl}/api/notifications/reservation-event`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ reservation, operation, previousReservation }), + }); + } catch { + // No bloquear la UI si el API no está disponible + console.warn('[notifications] API no disponible'); + } +} + +function App() { + // Initialize theme from localStorage + useEffect(() => { + const savedTheme = localStorage.getItem('theme'); + const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; + if (savedTheme === 'dark' || (!savedTheme && systemPrefersDark)) { + document.documentElement.classList.add('dark'); + } else { + document.documentElement.classList.remove('dark'); + } + }, []); + + const { session, loading: authLoading } = useAuth(); + + if (authLoading) { + return ( +
+ +
+ ); + } + + if (!session) { + return ( + <> + + + + ); + } + + return ( + + + + + + ); +} + +export default App; diff --git a/apps/web/src/assets/react.svg b/apps/web/src/assets/react.svg new file mode 100644 index 0000000..6c87de9 --- /dev/null +++ b/apps/web/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/apps/web/src/components/CalendarGrid.tsx b/apps/web/src/components/CalendarGrid.tsx new file mode 100644 index 0000000..2829520 --- /dev/null +++ b/apps/web/src/components/CalendarGrid.tsx @@ -0,0 +1,508 @@ +import { useEffect, useRef, useState } from 'react'; +import { + format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, + eachDayOfInterval, isSameMonth, addMonths, subMonths, + isSameDay, differenceInDays, parseISO, isWithinInterval +} from 'date-fns'; +import { es } from 'date-fns/locale/es'; +import { ChevronLeft, ChevronRight, Users, Moon } from 'lucide-react'; +import type { Reservation } from '../types'; +import { useProperty } from '../contexts/PropertyContext'; +import { PROPERTY_CONFIG } from '@naturcalabacera/shared'; +import { ServiceIcons } from './ServiceIcons'; + +interface Props { + reservations: Reservation[]; + onSelectDay: (day: Date) => void; + onSelectReservation: (reservation: Reservation) => void; + onSelectRange?: (start: Date, end: Date) => void; + isLoading?: boolean; + viewerMode?: boolean; +} + +export function CalendarGrid({ + reservations, + onSelectDay, + onSelectReservation, + onSelectRange, + isLoading: _isLoading = false, + viewerMode = false, +}: Props) { + const { property } = useProperty(); + const propertyConfig = PROPERTY_CONFIG[property]; + const [currentDate, setCurrentDate] = useState(new Date()); + + // Drag-to-select state + const [dragStart, setDragStart] = useState(null); + const [dragEnd, setDragEnd] = useState(null); + const [isDragging, setIsDragging] = useState(false); + const gridBodyRef = useRef(null); + // Tracks mouse movement to distinguish click vs drag + const mouseMoved = useRef(false); + // Prevents the click event that fires after mouseUp from triggering onSelectDay + const dragJustFinished = useRef(false); + + const monthStart = startOfMonth(currentDate); + const monthEnd = endOfMonth(monthStart); + const calendarStart = startOfWeek(monthStart, { weekStartsOn: 0 }); + const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 0 }); + + const calendarDays = eachDayOfInterval({ start: calendarStart, end: calendarEnd }); + + const weeks: Date[][] = []; + for (let i = 0; i < calendarDays.length; i += 7) { + weeks.push(calendarDays.slice(i, i + 7)); + } + + const nextMonth = () => setCurrentDate(addMonths(currentDate, 1)); + const prevMonth = () => setCurrentDate(subMonths(currentDate, 1)); + + // Display occupancy: a day is occupied for rendering if within [start, end] inclusive + const isDayOccupied = (day: Date): boolean => { + return reservations.some(res => { + const s = parseISO(res.start_date); + const e = parseISO(res.end_date); + return isWithinInterval(day, { start: s, end: e }) || isSameDay(day, s) || isSameDay(day, e); + }); + }; + + // Get reservation for a specific day (for click-through on occupied cells) + const getReservationForDay = (day: Date): Reservation | undefined => { + return reservations.find(res => { + const s = parseISO(res.start_date); + const e = parseISO(res.end_date); + return isWithinInterval(day, { start: s, end: e }) || isSameDay(day, s) || isSameDay(day, e); + }); + }; + + // Calculate which calendar day is under a given coordinate + const getDayFromCoords = (clientX: number, clientY: number): Date | null => { + const el = gridBodyRef.current; + if (!el) return null; + const rect = el.getBoundingClientRect(); + const x = clientX - rect.left; + const y = clientY - rect.top; + if (x < 0 || x >= rect.width || y < 0 || y >= rect.height) return null; + const col = Math.min(Math.floor(x / (rect.width / 7)), 6); + const row = Math.min(Math.floor(y / (rect.height / weeks.length)), weeks.length - 1); + return weeks[row]?.[col] ?? null; + }; + + // Is a day inside the current drag selection range? + const isInDragSelection = (day: Date): boolean => { + if (!dragStart || !dragEnd) return false; + const start = dragStart <= dragEnd ? dragStart : dragEnd; + const end = dragStart <= dragEnd ? dragEnd : dragStart; + return day >= start && day <= end; + }; + + // Confirm drag and open modal + const confirmDrag = (start: Date, end: Date) => { + const s = start <= end ? start : end; + const e = start <= end ? end : start; + if (isSameDay(s, e)) { + onSelectDay(s); + } else if (onSelectRange) { + onSelectRange(s, e); + } else { + onSelectDay(s); + } + }; + + // --- Grid body mouse events --- + + const handleGridMouseDown = (ev: React.MouseEvent) => { + if (viewerMode) return; + const day = getDayFromCoords(ev.clientX, ev.clientY); + if (!day) return; + // Allow drag start on any day (free or occupied boundary) + // Drag is only initiated on non-occupied days + if (isDayOccupied(day)) return; + ev.preventDefault(); + mouseMoved.current = false; + setDragStart(day); + setDragEnd(day); + setIsDragging(true); + }; + + const handleGridMouseMove = (ev: React.MouseEvent) => { + if (!isDragging || !dragStart) return; + mouseMoved.current = true; + const day = getDayFromCoords(ev.clientX, ev.clientY); + if (day) setDragEnd(day); + }; + + const handleGridMouseUp = (ev: React.MouseEvent) => { + if (!isDragging || !dragStart || !dragEnd) return; + const hasMoved = mouseMoved.current; + const start = dragStart; + const end = dragEnd; + setIsDragging(false); + setDragStart(null); + setDragEnd(null); + if (hasMoved && !isSameDay(start, end)) { + dragJustFinished.current = true; + confirmDrag(start, end); + } + // Single clicks are handled entirely by handleGridClick + ev.stopPropagation(); + }; + + // Handle click on grid body (for free-day single clicks when drag is not involved) + const handleGridClick = (ev: React.MouseEvent) => { + if (viewerMode || isDragging) return; + // Ignore the synthetic click that fires immediately after a drag ends + if (dragJustFinished.current) { + dragJustFinished.current = false; + return; + } + const day = getDayFromCoords(ev.clientX, ev.clientY); + if (!day) return; + const res = getReservationForDay(day); + if (res) { + // Click on occupied day — open reservation + onSelectReservation(res); + } else { + // Click on free day — open create modal + onSelectDay(day); + } + }; + + // --- Touch events (mobile drag) --- + + const handleTouchStart = (ev: React.TouchEvent) => { + if (viewerMode) return; + const touch = ev.touches[0]; + const day = getDayFromCoords(touch.clientX, touch.clientY); + if (!day || isDayOccupied(day)) return; + mouseMoved.current = false; + setDragStart(day); + setDragEnd(day); + setIsDragging(true); + }; + + const handleTouchMove = (ev: React.TouchEvent) => { + if (!isDragging) return; + mouseMoved.current = true; + const touch = ev.touches[0]; + const day = getDayFromCoords(touch.clientX, touch.clientY); + if (day) setDragEnd(day); + }; + + const handleTouchEnd = () => { + if (!isDragging || !dragStart || !dragEnd) return; + const hasMoved = mouseMoved.current; + const start = dragStart; + const end = dragEnd; + setIsDragging(false); + setDragStart(null); + setDragEnd(null); + if (hasMoved && !isSameDay(start, end)) { + dragJustFinished.current = true; + confirmDrag(start, end); + } else { + onSelectDay(start); + } + }; + + // Cancel drag if mouse leaves the window + useEffect(() => { + const cancel = () => { + if (isDragging) { + setIsDragging(false); + setDragStart(null); + setDragEnd(null); + } + }; + document.addEventListener('mouseup', cancel); + return () => document.removeEventListener('mouseup', cancel); + }, [isDragging]); + + // --- Reservation blocks (visual only — clicks handled at grid body level) --- + const renderReservationBlocks = () => { + const blocks: React.ReactElement[] = []; + + reservations.forEach((res) => { + const startDate = parseISO(res.start_date); + const endDate = parseISO(res.end_date); + + const startIndex = calendarDays.findIndex(day => isSameDay(day, startDate)); + if (startIndex === -1) return; + + const endIndex = calendarDays.findIndex(day => isSameDay(day, endDate)); + if (endIndex === -1) return; + + const totalDuration = differenceInDays(endDate, startDate) + 1; + const nights = totalDuration - 1; + + const isTeneriffa = res.origin === 'Teneriffa2000'; + const gradient = viewerMode + ? 'bg-stone-400/30 dark:bg-stone-500/30' + : isTeneriffa + ? 'bg-blue-600/30 dark:bg-blue-500/30' + : 'bg-yellow-500/30 dark:bg-yellow-400/30'; + + const borderClass = viewerMode + ? 'border-l-4 border-stone-400' + : isTeneriffa + ? 'border-l-4 border-blue-500' + : 'border-l-4 border-yellow-500'; + const textShadow = 'drop-shadow-[0_1px_1px_rgba(0,0,0,0.8)]'; + + let currentDayIndex = startIndex; + let blockIndex = 0; + + while (currentDayIndex <= endIndex) { + const weekIndex = Math.floor(currentDayIndex / 7); + const dayOfWeek = currentDayIndex % 7; + const daysUntilWeekEnd = 7 - dayOfWeek; + const daysRemaining = endIndex - currentDayIndex + 1; + const daysInThisWeek = Math.min(daysUntilWeekEnd, daysRemaining); + const isFirstBlock = blockIndex === 0; + + blocks.push( +
+ {/* Desktop */} +
+
+ {viewerMode ? 'Ocupado' : res.client_name} +
+ {!viewerMode && isFirstBlock && ( +
+
+ + {nights}n +
+
+ + {res.adults_count + res.children_count}p +
+ +
+ )} +
+ + {/* Mobile */} +
+ {daysInThisWeek > 1 && ( + + {viewerMode ? 'Ocupado' : res.client_name} + + )} + {!viewerMode && daysInThisWeek > 2 && isFirstBlock && ( + + )} +
+
+ ); + + currentDayIndex += daysInThisWeek; + blockIndex++; + } + }); + + return blocks; + }; + + // Drag selection highlight blocks + const renderDragSelection = () => { + if (!isDragging || !dragStart || !dragEnd) return null; + const start = dragStart <= dragEnd ? dragStart : dragEnd; + const end = dragStart <= dragEnd ? dragEnd : dragStart; + const startIndex = calendarDays.findIndex(d => d >= start); + if (startIndex === -1) return null; + const endIndex = calendarDays.findIndex(d => d >= end); + const effectiveEnd = endIndex === -1 ? calendarDays.length - 1 : endIndex; + + const selBlocks: React.ReactElement[] = []; + let cur = startIndex; + while (cur <= effectiveEnd) { + const weekIndex = Math.floor(cur / 7); + const dayOfWeek = cur % 7; + const daysUntilWeekEnd = 7 - dayOfWeek; + const daysRemaining = effectiveEnd - cur + 1; + const span = Math.min(daysUntilWeekEnd, daysRemaining); + selBlocks.push( +
+ ); + cur += span; + } + return selBlocks; + }; + + // Days count label during drag + const dragNights = dragStart && dragEnd + ? Math.abs(differenceInDays(dragEnd, dragStart)) + : 0; + + return ( +
+ + + + {/* Header */} +
+
+
+

+ {format(currentDate, 'MMMM yyyy', { locale: es })} +

+ {/* Drag hint — shown only during active drag */} + {isDragging && dragNights > 0 && ( + + {dragNights} noche{dragNights !== 1 ? 's' : ''} + + )} +
+
+

+ {viewerMode ? 'Vista de disponibilidad' : 'Clic para crear · Arrastra para rango'} +

+ + {propertyConfig.label} + +
+
+
+ + +
+
+ + {/* Grid container */} +
+
+ + {/* Days header */} +
+ {['D', 'L', 'M', 'X', 'J', 'V', 'S'].map((day, i) => ( +
+ {day} + {['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'][i]} +
+ ))} +
+ + {/* Grid body — handles all pointer interactions via coordinates */} +
+ {/* Grid cells — purely visual, no pointer-events needed */} + {weeks.map((week, weekIdx) => ( +
+ {week.map((day) => { + const isCurrentMonth = isSameMonth(day, monthStart); + const isOccupied = isDayOccupied(day); + const inSel = isInDragSelection(day); + const isToday = isSameDay(day, new Date()); + + return ( +
+ + {format(day, 'd')} + +
+ ); + })} +
+ ))} + + {/* Reservation color blocks */} + {renderReservationBlocks()} + + {/* Drag selection overlay */} + {renderDragSelection()} +
+
+
+ + {/* Legend */} +
+
+
+ Teneriffa +
+
+
+ Natur +
+
+
+ ); +} diff --git a/apps/web/src/components/CalendarGrid.tsx.backup b/apps/web/src/components/CalendarGrid.tsx.backup new file mode 100644 index 0000000..f8b541b --- /dev/null +++ b/apps/web/src/components/CalendarGrid.tsx.backup @@ -0,0 +1,222 @@ +import { useState } from 'react'; +import { + format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, + eachDayOfInterval, isSameMonth, addMonths, subMonths, + isSameDay, differenceInDays, parseISO, isWithinInterval +} from 'date-fns'; +import { es } from 'date-fns/locale/es'; +import { ChevronLeft, ChevronRight, Users, Moon, Ban } from 'lucide-react'; +import type { Reservation } from '../types'; + +interface Props { + reservations: Reservation[]; + onSelectDay: (day: Date) => void; + onSelectReservation: (reservation: Reservation) => void; +} + +export function CalendarGrid({ reservations, onSelectDay, onSelectReservation }: Props) { + const [currentDate, setCurrentDate] = useState(new Date()); + + const monthStart = startOfMonth(currentDate); + const monthEnd = endOfMonth(monthStart); + const calendarStart = startOfWeek(monthStart, { weekStartsOn: 0 }); + const calendarEnd = endOfWeek(monthEnd, { weekStartsOn: 0 }); + + const calendarDays = eachDayOfInterval({ start: calendarStart, end: calendarEnd }); + + // Organizar en semanas + const weeks: Date[][] = []; + for (let i = 0; i < calendarDays.length; i += 7) { + weeks.push(calendarDays.slice(i, i + 7)); + } + + const nextMonth = () => setCurrentDate(addMonths(currentDate, 1)); + const prevMonth = () => setCurrentDate(subMonths(currentDate, 1)); + + // Función para verificar si un día está ocupado + const isDayOccupied = (day: Date): boolean => { + return reservations.some(res => { + const startDate = parseISO(res.start_date); + const endDate = parseISO(res.end_date); + + // Un día está ocupado si está dentro del rango [start_date, end_date] (ambos inclusive) + return isWithinInterval(day, { start: startDate, end: endDate }) || + isSameDay(day, startDate) || + isSameDay(day, endDate); + }); + }; + + // Renderizar bloques de reserva + const renderReservationBlocks = () => { + return reservations.map((res) => { + const startDate = parseISO(res.start_date); + const endDate = parseISO(res.end_date); + + const dayIndex = calendarDays.findIndex(day => isSameDay(day, startDate)); + if (dayIndex === -1) return null; + + const weekIndex = Math.floor(dayIndex / 7); + const dayOfWeek = dayIndex % 7; + + const duration = differenceInDays(endDate, startDate) + 1; + const nights = duration - 1; + + const isTeneriffa = res.origin === 'Teneriffa2000'; + const gradient = isTeneriffa + ? 'from-blue-600/90 via-blue-500/90 to-blue-400/90' + : 'from-yellow-600/90 via-yellow-500/90 to-yellow-400/90'; + + const borderColor = isTeneriffa ? 'border-blue-400' : 'border-yellow-400'; + const shadowColor = isTeneriffa ? 'shadow-blue-500/50' : 'shadow-yellow-500/50'; + + return ( +
onSelectReservation(res)} + className={` + absolute cursor-pointer group + bg-gradient-to-r ${gradient} ${borderColor} + border-l-4 rounded-2xl p-3 + hover:scale-105 transition-all duration-300 + shadow-2xl ${shadowColor} + backdrop-blur-xl + z-10 + `} + style={{ + top: `${weekIndex * 100 + 50}px`, + left: `${(dayOfWeek * 100 / 7) + 0.75}%`, + width: `${Math.min(duration, 7 - dayOfWeek) * (100 / 7) - 1.5}%`, + height: '60px' + }} + > +
+
{res.client_name}
+
+ < div className =\"flex items-center gap-1 text-white/90\"> + < Moon className =\"w-3 h-3\" /> + < span className =\"text-[11px] font-semibold\">{nights}n +
+
+ < Users className =\"w-3 h-3\" /> + < span className =\"text-[11px] font-semibold\">{res.adults_count + res.children_count}p +
+
+
+
+ ); +}); + }; + +return ( +
+{/* Header */ } +
+ < div > +

+{ format(currentDate, 'MMMM yyyy', { locale: es }) } +

+

Vista mensual de reservas

+
+
+ < button +onClick = { prevMonth } +className =\"p-3 rounded-xl bg-gradient-to-br from-slate-700 to-slate-800 hover:from-slate-600 hover:to-slate-700 text-slate-200 transition-all duration-300 shadow-lg hover:shadow-xl hover:scale-110 border border-slate-600/50\" + > + + + +
+
+ + {/* Calendar */ } + < div className =\"bg-slate-800/30 backdrop-blur-xl rounded-2xl overflow-hidden border border-slate-700/50 shadow-2xl\"> +{/* Days header */ } +
+{ + ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'].map((day) => ( +
+ { day } +
+ )) +} +
+ + {/* Calendar grid */ } + < div className =\"relative\"> +{ + weeks.map((week, weekIdx) => ( +
+ { + week.map((day) => { + const isCurrentMonth = isSameMonth(day, monthStart); + const isOccupied = isDayOccupied(day); + + return ( +
{ + if (!isOccupied) { + onSelectDay(day); + } + }} + className={` + relative h-28 p-3 border-r border-slate-700/30 last:border-r-0 + transition-all duration-300 group + ${!isCurrentMonth ? 'bg-slate-900/50' : ''} + ${isOccupied + ? 'cursor-not-allowed bg-red-900/10' + : 'cursor-pointer hover:bg-gradient-to-br hover:from-slate-700/50 hover:to-slate-600/30' + } + `} + > + + {format(day, 'd')} + + + {/* Indicador visual de día ocupado */} + {isOccupied && isCurrentMonth && ( +
+ +
+ ) + } +
+ ); + }) +} +
+ ))} + +{/* Reservation blocks */ } +{ renderReservationBlocks() } +
+
+ + {/* Legend */ } + < div className =\"mt-6 flex items-center gap-8 text-sm text-slate-400\"> + < div className =\"flex items-center gap-3 px-4 py-2 bg-gradient-to-r from-blue-500/10 to-transparent rounded-xl border border-blue-500/20\"> + < div className =\"w-4 h-4 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 shadow-lg shadow-blue-500/50\"> + < span className =\"font-semibold\">Teneriffa2000 + +
+ < div className =\"w-4 h-4 rounded-lg bg-gradient-to-br from-yellow-500 to-yellow-600 shadow-lg shadow-yellow-500/50\">
+ < span className =\"font-semibold\">Naturcalabacera + + + + ); +} diff --git a/apps/web/src/components/ChatbotContainer.tsx b/apps/web/src/components/ChatbotContainer.tsx new file mode 100644 index 0000000..482eaf3 --- /dev/null +++ b/apps/web/src/components/ChatbotContainer.tsx @@ -0,0 +1,591 @@ +/** + * ChatbotContainer — asistente conversacional con datos reales de Supabase. + * + * Arquitectura lista para IA real: la función processMessage() actualmente + * usa un motor de reglas. Para conectar un LLM, sustituye su cuerpo por + * una llamada a la API (Claude, GPT, etc.) pasando los datos de reservas + * como contexto del sistema. + */ + +import { useState, useEffect, useRef, useCallback } from 'react'; +import { MessageCircle, X, Send, Home, RefreshCw } from 'lucide-react'; +import { supabase } from '../lib/supabase'; +import type { Reservation, Property } from '../types'; +import { format, parseISO, isAfter, isBefore, differenceInDays } from 'date-fns'; +import { es } from 'date-fns/locale/es'; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +interface Message { + id: string; + role: 'user' | 'assistant'; + content: string; + timestamp: Date; +} + +// ─── Helpers ───────────────────────────────────────────────────────────────── + +function fmtDate(d: string) { + return format(parseISO(d), "d MMM yyyy", { locale: es }); +} + +function fmtShort(d: string) { + return format(parseISO(d), "d MMM", { locale: es }); +} + +function propertyLabel(p: Property) { + return p === 'los_dragos' ? 'Los Dragos' : 'La Esquinita'; +} + +function nightsBetween(start: string, end: string) { + return differenceInDays(parseISO(end), parseISO(start)); +} + +// ─── Response engine ────────────────────────────────────────────────────────── + +function guestDetail(r: Reservation): string { + const nights = nightsBetween(r.start_date, r.end_date); + const pax = r.adults_count + r.children_count; + const lines: string[] = [ + `👤 **${r.client_name}**`, + `📅 ${fmtDate(r.start_date)} → ${fmtDate(r.end_date)} (${nights} noche${nights !== 1 ? 's' : ''})`, + `👥 ${pax} persona${pax !== 1 ? 's' : ''} (${r.adults_count} adultos, ${r.children_count} niños)`, + `🏷️ Origen: ${r.origin}`, + ]; + if (r.government_registration) { + lines.push(`🏛️ Reg. gubernamental: \`${r.government_registration}\``); + } else { + lines.push(`⚠️ Sin registro gubernamental`); + } + if (r.invoice_number) lines.push(`🧾 Factura: ${r.invoice_number}`); + if (r.has_cleaning) lines.push(`🧹 Servicio de limpieza incluido`); + if (r.has_pool_heating) lines.push(`♨️ Calefacción de piscina incluida`); + if (r.has_flies_products) lines.push(`🦟 Productos anti-mosquitos incluidos`); + if (r.is_event) { + lines.push(`🎉 Evento: ${r.event_type ?? ''}${r.event_type_other ? ` (${r.event_type_other})` : ''}`); + if (r.attendees_count) lines.push(` Asistentes: ${r.attendees_count}`); + } + if (r.pricing_snapshot) { + const p = r.pricing_snapshot; + lines.push(`💶 Total: ${p.total.toLocaleString('es-ES', { style: 'currency', currency: 'EUR' })}`); + } + if (r.observations) lines.push(`📝 Notas: ${r.observations}`); + return lines.join('\n'); +} + +function statsInfo(reservations: Reservation[], property: Property): string { + const now = new Date(); + const label = propertyLabel(property); + const total = reservations.length; + const active = reservations.filter(r => + !isAfter(parseISO(r.start_date), now) && !isBefore(parseISO(r.end_date), now) + ); + const upcoming = reservations.filter(r => isAfter(parseISO(r.start_date), now)); + const past = reservations.filter(r => isBefore(parseISO(r.end_date), now)); + const teneriffa = reservations.filter(r => r.origin === 'Teneriffa2000'); + const natur = reservations.filter(r => r.origin === 'Naturcalabacera'); + const withReg = reservations.filter(r => r.government_registration); + const withoutReg = reservations.filter(r => !r.government_registration); + const totalNights = reservations.reduce((sum, r) => sum + nightsBetween(r.start_date, r.end_date), 0); + + const lines = [ + `📊 **Resumen — ${label}**\n`, + `• Total reservas: **${total}**`, + `• Activas ahora: ${active.length}`, + `• Próximas: ${upcoming.length}`, + `• Pasadas: ${past.length}`, + `• Noches totales reservadas: ${totalNights}`, + ``, + `📋 **Por origen:**`, + `• Teneriffa2000: ${teneriffa.length}`, + `• Naturcalabacera: ${natur.length}`, + ``, + `🏛️ **Registros gubernamentales:**`, + `• Con registro: ${withReg.length}`, + `• Sin registro: ${withoutReg.length}${withoutReg.length > 0 ? ' ⚠️' : ' ✅'}`, + ]; + return lines.join('\n'); +} + +function contractsInfo(reservations: Reservation[]): string { + const now = new Date(); + const withReg = reservations.filter(r => r.government_registration); + const pendingReg = reservations.filter( + r => !r.government_registration && !isBefore(parseISO(r.end_date), now) + ); + + const lines: string[] = ['🏛️ **Registros y contratos**\n']; + + if (withReg.length > 0) { + lines.push(`✅ **Con registro (${withReg.length}):**`); + withReg.forEach(r => { + lines.push(`• ${r.client_name} — \`${r.government_registration}\``); + if (r.invoice_number) lines.push(` Factura: ${r.invoice_number}`); + lines.push(` ${fmtShort(r.start_date)} → ${fmtShort(r.end_date)}`); + }); + } + + if (pendingReg.length > 0) { + lines.push(`\n⚠️ **Sin registro (activas/futuras) — ${pendingReg.length}:**`); + pendingReg.forEach(r => { + lines.push(`• ${r.client_name} (${fmtShort(r.start_date)} → ${fmtShort(r.end_date)})`); + }); + } + + if (withReg.length === 0 && pendingReg.length === 0) { + lines.push('No hay reservas con información de contratos disponible.'); + } + + return lines.join('\n'); +} + +function upcomingInfo(reservations: Reservation[]): string { + const now = new Date(); + const upcoming = reservations + .filter(r => isAfter(parseISO(r.start_date), now)) + .sort((a, b) => a.start_date.localeCompare(b.start_date)) + .slice(0, 6); + + if (upcoming.length === 0) return 'No hay reservas futuras registradas.'; + + const lines = [`📅 **Próximas reservas (${upcoming.length}):**\n`]; + upcoming.forEach(r => { + const daysTo = differenceInDays(parseISO(r.start_date), now); + const nights = nightsBetween(r.start_date, r.end_date); + lines.push( + `**${r.client_name}** — en ${daysTo} día${daysTo !== 1 ? 's' : ''}\n` + + ` ${fmtShort(r.start_date)} → ${fmtShort(r.end_date)} · ${nights} noches · ${r.adults_count + r.children_count} pax\n` + + (r.government_registration ? ` ✅ Reg: \`${r.government_registration}\`` : ` ⚠️ Sin registro`) + ); + }); + return lines.join('\n'); +} + +function availabilityInfo(reservations: Reservation[]): string { + const now = new Date(); + const future = reservations + .filter(r => !isBefore(parseISO(r.end_date), now)) + .sort((a, b) => a.start_date.localeCompare(b.start_date)); + + if (future.length === 0) { + return '✅ No hay reservas futuras. La propiedad está completamente disponible.'; + } + + const lines = ['🗓️ **Disponibilidad próxima:**\n']; + + // Gap before first reservation + const firstStart = parseISO(future[0].start_date); + const daysToFirst = differenceInDays(firstStart, now); + if (daysToFirst > 0) { + lines.push(`✅ Libre ahora → ${fmtShort(future[0].start_date)} (${daysToFirst} días)`); + } + + // Gaps between reservations + for (let i = 0; i < future.length; i++) { + lines.push(`🔴 Ocupado: ${fmtShort(future[i].start_date)} → ${fmtShort(future[i].end_date)} (${future[i].client_name})`); + if (i < future.length - 1) { + const gapStart = parseISO(future[i].end_date); + const gapEnd = parseISO(future[i + 1].start_date); + const gapDays = differenceInDays(gapEnd, gapStart); + if (gapDays > 0) { + lines.push(`✅ Libre: ${fmtShort(future[i].end_date)} → ${fmtShort(future[i + 1].start_date)} (${gapDays} días)`); + } + } + } + + return lines.join('\n'); +} + +function allReservationsInfo(reservations: Reservation[]): string { + if (reservations.length === 0) return 'No hay reservas registradas.'; + + const sorted = [...reservations].sort((a, b) => a.start_date.localeCompare(b.start_date)); + const now = new Date(); + const lines = [`📋 **Todas las reservas (${sorted.length}):**\n`]; + + sorted.forEach(r => { + const isPast = isBefore(parseISO(r.end_date), now); + const isActive = !isAfter(parseISO(r.start_date), now) && !isBefore(parseISO(r.end_date), now); + const icon = isPast ? '⬜' : isActive ? '🟢' : '🔵'; + lines.push( + `${icon} **${r.client_name}** — ${fmtShort(r.start_date)} → ${fmtShort(r.end_date)}` + + (r.government_registration ? ` ✅` : ` ⚠️`) + ); + }); + + return lines.join('\n'); +} + +function processMessage(input: string, reservations: Reservation[], property: Property): string { + const lower = input.toLowerCase().trim(); + const now = new Date(); + const label = propertyLabel(property); + + // Greeting + if (/^(hola|buenos|buenas|hey|hi|ey|qué tal|que tal|buen)/.test(lower)) { + const total = reservations.length; + const upcoming = reservations.filter(r => isAfter(parseISO(r.start_date), now)).length; + const active = reservations.filter(r => + !isAfter(parseISO(r.start_date), now) && !isBefore(parseISO(r.end_date), now) + ).length; + return [ + `¡Hola! Soy tu asistente para **${label}** 🏡`, + ``, + `Estado actual:`, + `• ${active > 0 ? `🟢 ${active} reserva${active !== 1 ? 's' : ''} activa${active !== 1 ? 's' : ''} ahora mismo` : '⬜ Sin reservas activas hoy'}`, + `• 🔵 ${upcoming} próxima${upcoming !== 1 ? 's' : ''}`, + `• 📋 ${total} reserva${total !== 1 ? 's' : ''} en total`, + ``, + `¿Qué necesitas saber?`, + ].join('\n'); + } + + // Stats / summary + if (/estadist|resumen|total|cuántas|cuantas|dato|cifra|número|numeros|summary/.test(lower)) { + return statsInfo(reservations, property); + } + + // Contracts / government registration + if (/contrat|registro|viajero|govern|código|codigos|rvtca|factura|invoice|número de registro/.test(lower)) { + return contractsInfo(reservations); + } + + // Upcoming + if (/próxim|siguiente|futuras|upcoming|pronto|esta semana|este mes|entran|llegan/.test(lower)) { + return upcomingInfo(reservations); + } + + // Availability + if (/disponib|libre|ocup|vac|hueco|cuando|free|gap|abierto/.test(lower)) { + return availabilityInfo(reservations); + } + + // List all + if (/lista|todas|todos|ver todo|todas las|show all|all reserv/.test(lower)) { + return allReservationsInfo(reservations); + } + + // Search by guest name — scan all words in input against client names + const words = lower.split(/\s+/).filter(w => w.length > 2); + for (const word of words) { + const found = reservations.find(r => + r.client_name.toLowerCase().includes(word) + ); + if (found) return guestDetail(found); + } + + // Help / default + return [ + `Puedo ayudarte con información de **${label}**. Pregúntame sobre:`, + ``, + `• 📋 **Reservas** — "lista todas", "reservas de mayo"`, + `• 📅 **Próximas** — "próximas reservas"`, + `• 🗓️ **Disponibilidad** — "¿cuándo está libre?"`, + `• 🏛️ **Contratos** — "registros gubernamentales", "contratos"`, + `• 👤 **Huésped** — escribe el nombre del cliente`, + `• 📊 **Estadísticas** — "dame un resumen"`, + ].join('\n'); +} + +// ─── Quick-reply suggestions ────────────────────────────────────────────────── + +const QUICK_REPLIES = [ + { label: 'Próximas reservas', text: 'próximas reservas' }, + { label: 'Disponibilidad', text: '¿cuándo está libre?' }, + { label: 'Contratos y registros', text: 'registros gubernamentales' }, + { label: 'Resumen estadístico', text: 'dame un resumen' }, + { label: 'Todas las reservas', text: 'lista todas las reservas' }, +]; + +// ─── Message renderer (markdown-lite) ──────────────────────────────────────── + +function RenderMessage({ content }: { content: string }) { + const lines = content.split('\n'); + return ( +
+ {lines.map((line, i) => { + // Bold: **text** + const parts = line.split(/(\*\*[^*]+\*\*)/g).map((part, j) => { + if (part.startsWith('**') && part.endsWith('**')) { + return {part.slice(2, -2)}; + } + // Inline code: `text` + return part.split(/(`[^`]+`)/g).map((seg, k) => { + if (seg.startsWith('`') && seg.endsWith('`')) { + return ( + + {seg.slice(1, -1)} + + ); + } + return seg; + }); + }); + if (line === '') return
; + return

{parts}

; + })} +
+ ); +} + +// ─── Main component ─────────────────────────────────────────────────────────── + +export function ChatbotContainer() { + const [isOpen, setIsOpen] = useState(false); + const [messages, setMessages] = useState([]); + const [input, setInput] = useState(''); + const [selectedProperty, setSelectedProperty] = useState('los_dragos'); + const [reservationsMap, setReservationsMap] = useState>({ + los_dragos: [], + la_esquinita: [], + }); + const [loadingData, setLoadingData] = useState(false); + const [isTyping, setIsTyping] = useState(false); + const messagesEndRef = useRef(null); + const inputRef = useRef(null); + + // Fetch all reservations for both properties + const fetchAll = useCallback(async () => { + setLoadingData(true); + try { + const { data } = await supabase + .from('reservations') + .select('*') + .order('start_date', { ascending: true }); + if (data) { + setReservationsMap({ + los_dragos: data.filter((r: Reservation) => r.property === 'los_dragos'), + la_esquinita: data.filter((r: Reservation) => r.property === 'la_esquinita'), + }); + } + } finally { + setLoadingData(false); + } + }, []); + + useEffect(() => { + if (isOpen && messages.length === 0) { + fetchAll(); + // Initial greeting + const greeting: Message = { + id: crypto.randomUUID(), + role: 'assistant', + content: `¡Hola! 👋 Soy tu asistente de reservas.\n\nSelecciona una propiedad arriba y pregúntame lo que necesites: disponibilidad, contratos, huéspedes, estadísticas…`, + timestamp: new Date(), + }; + setMessages([greeting]); + } + }, [isOpen, messages.length, fetchAll]); + + useEffect(() => { + messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [messages, isTyping]); + + const handleSend = useCallback(async (text?: string) => { + const userText = (text ?? input).trim(); + if (!userText) return; + + const userMsg: Message = { + id: crypto.randomUUID(), + role: 'user', + content: userText, + timestamp: new Date(), + }; + setMessages(prev => [...prev, userMsg]); + setInput(''); + setIsTyping(true); + + // Simulate processing delay for UX + await new Promise(resolve => setTimeout(resolve, 400)); + + const reservations = reservationsMap[selectedProperty]; + const response = processMessage(userText, reservations, selectedProperty); + + const botMsg: Message = { + id: crypto.randomUUID(), + role: 'assistant', + content: response, + timestamp: new Date(), + }; + setIsTyping(false); + setMessages(prev => [...prev, botMsg]); + }, [input, reservationsMap, selectedProperty]); + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + handleSend(); + } + }; + + const handlePropertySwitch = (p: Property) => { + setSelectedProperty(p); + const switchMsg: Message = { + id: crypto.randomUUID(), + role: 'assistant', + content: `Cambiado a **${propertyLabel(p)}**. ¿Qué necesitas saber sobre esta propiedad?`, + timestamp: new Date(), + }; + setMessages(prev => [...prev, switchMsg]); + }; + + const isDragos = selectedProperty === 'los_dragos'; + const accentGradient = isDragos + ? 'from-emerald-600 to-teal-600' + : 'from-amber-600 to-orange-600'; + const accentBorder = isDragos ? 'border-emerald-500/30' : 'border-amber-500/30'; + const accentShadow = isDragos ? 'shadow-emerald-500/20' : 'shadow-amber-500/20'; + const accentBg = isDragos ? 'bg-emerald-600/20' : 'bg-amber-600/20'; + const accentText = isDragos ? 'text-emerald-300' : 'text-amber-300'; + const activePropBg = isDragos + ? 'bg-gradient-to-r from-emerald-600 to-teal-600 text-white shadow-lg shadow-emerald-500/30' + : 'bg-gradient-to-r from-amber-600 to-orange-600 text-white shadow-lg shadow-amber-500/30'; + + return ( + <> + {/* Floating button */} + + + {/* Chat panel */} + {isOpen && ( +
+ {/* Header */} +
+
+
+ +
+
+

Asistente de Reservas

+

{propertyLabel(selectedProperty)}

+
+
+
+ + +
+
+ + {/* Property selector */} +
+ {(['los_dragos', 'la_esquinita'] as Property[]).map(p => ( + + ))} +
+ + {/* Messages */} +
+ {messages.map(msg => ( +
+ {msg.role === 'assistant' && ( +
+ +
+ )} +
+ +

+ {format(msg.timestamp, 'HH:mm')} +

+
+
+ ))} + + {/* Typing indicator */} + {isTyping && ( +
+
+ +
+
+ + + +
+
+ )} + +
+
+ + {/* Quick replies */} + {messages.length <= 2 && ( +
+ {QUICK_REPLIES.map(qr => ( + + ))} +
+ )} + + {/* Input */} +
+ setInput(e.target.value)} + onKeyDown={handleKeyDown} + placeholder="Escribe tu pregunta…" + className="flex-1 bg-slate-800 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white placeholder-slate-500 outline-none focus:border-white/25 transition-colors" + /> + +
+
+ )} + + ); +} diff --git a/apps/web/src/components/ContractUpload.tsx b/apps/web/src/components/ContractUpload.tsx new file mode 100644 index 0000000..b9758fc --- /dev/null +++ b/apps/web/src/components/ContractUpload.tsx @@ -0,0 +1,234 @@ +import { useEffect, useRef, useState } from 'react'; +import { Upload, Trash2, FileText, AlertCircle, Loader2, X, Maximize2 } from 'lucide-react'; +import { useFileUpload, type UploadedContract } from '../hooks/useFileUpload'; +import { motion, AnimatePresence } from 'framer-motion'; + +interface Props { + reservationId: string; +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +const isImage = (mimeType: string) => mimeType.startsWith('image/'); + +export function ContractUpload({ reservationId }: Props) { + const { uploading, error, uploadFile, fetchContracts, getSignedUrl, deleteContract } = useFileUpload(reservationId); + const [contracts, setContracts] = useState([]); + const [thumbnails, setThumbnails] = useState>({}); + const [lightboxUrl, setLightboxUrl] = useState(null); + const [loadingOpen, setLoadingOpen] = useState(null); + const [deletingId, setDeletingId] = useState(null); + const inputRef = useRef(null); + const [dragging, setDragging] = useState(false); + + useEffect(() => { + fetchContracts().then(list => { + setContracts(list); + // Pre-fetch signed URLs for image thumbnails + list.filter(c => isImage(c.mime_type)).forEach(async c => { + const url = await getSignedUrl(c.file_path); + if (url) setThumbnails(prev => ({ ...prev, [c.id]: url })); + }); + }); + }, [fetchContracts, getSignedUrl]); + + const handleFiles = async (files: FileList | null) => { + if (!files || files.length === 0) return; + for (const file of Array.from(files)) { + const result = await uploadFile(file); + if (result) { + setContracts(prev => [result, ...prev]); + // Pre-fetch thumbnail for image + if (isImage(result.mime_type)) { + const url = await getSignedUrl(result.file_path); + if (url) setThumbnails(prev => ({ ...prev, [result.id]: url })); + } + } + } + }; + + const handleOpen = async (contract: UploadedContract) => { + if (isImage(contract.mime_type) && thumbnails[contract.id]) { + setLightboxUrl(thumbnails[contract.id]); + return; + } + setLoadingOpen(contract.id); + const url = await getSignedUrl(contract.file_path); + setLoadingOpen(null); + if (url) { + if (isImage(contract.mime_type)) { + setLightboxUrl(url); + } else { + window.open(url, '_blank', 'noopener,noreferrer'); + } + } + }; + + const handleDelete = async (contract: UploadedContract) => { + setDeletingId(contract.id); + const ok = await deleteContract(contract.id, contract.file_path); + setDeletingId(null); + if (ok) { + setContracts(prev => prev.filter(c => c.id !== contract.id)); + setThumbnails(prev => { const n = { ...prev }; delete n[contract.id]; return n; }); + } + }; + + return ( + <> +
+ {/* Drop zone */} +
{ e.preventDefault(); setDragging(true); }} + onDragLeave={() => setDragging(false)} + onDrop={e => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files); }} + onClick={() => inputRef.current?.click()} + className={` + border-2 border-dashed rounded-xl p-4 cursor-pointer transition-all text-center + ${dragging + ? 'border-emerald-500 bg-emerald-900/20' + : 'border-slate-600 bg-slate-800/50 hover:border-slate-500 hover:bg-slate-800' + } + `} + > + handleFiles(e.target.files)} + /> + {uploading ? ( +
+ + Subiendo... +
+ ) : ( +
+ + + Arrastra archivos o pulsa para seleccionar + + PDF, JPEG, PNG · máx. 10 MB +
+ )} +
+ + {/* Error */} + {error && ( +
+ + {error} +
+ )} + + {/* File list */} + {contracts.length > 0 && ( +
    + {contracts.map(contract => ( +
  • + {/* Image thumbnail */} + {isImage(contract.mime_type) && ( + + )} + + {/* File info row */} +
    + {!isImage(contract.mime_type) && ( +
    + +
    + )} +
    +

    {contract.filename}

    +

    {formatBytes(contract.size_bytes)}

    +
    + {!isImage(contract.mime_type) && ( + + )} + +
    +
  • + ))} +
+ )} +
+ + {/* Lightbox */} + + {lightboxUrl && ( + setLightboxUrl(null)} + className="fixed inset-0 bg-black/92 z-[100] flex items-center justify-center p-4" + > + + e.stopPropagation()} + /> + + )} + + + ); +} diff --git a/apps/web/src/components/CustomMobileCalendar.tsx b/apps/web/src/components/CustomMobileCalendar.tsx new file mode 100644 index 0000000..c7262e7 --- /dev/null +++ b/apps/web/src/components/CustomMobileCalendar.tsx @@ -0,0 +1,155 @@ +import { useState } from 'react'; +import { + format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, + eachDayOfInterval, isSameMonth, isSameDay, addMonths, subMonths, + isWithinInterval, parseISO, isBefore +} from 'date-fns'; +import { es } from 'date-fns/locale/es'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { toast } from 'sonner'; +import type { Reservation } from '../types'; + +interface Props { + reservations: Reservation[]; + onSelectRange: (start: Date, end: Date) => void; + onSelectReservation: (reservation: Reservation) => void; +} + +export function CustomMobileCalendar({ reservations, onSelectRange, onSelectReservation }: Props) { + const [currentDate, setCurrentDate] = useState(new Date()); + const [selectionStart, setSelectionStart] = useState(null); + + const monthStart = startOfMonth(currentDate); + const monthEnd = endOfMonth(monthStart); + const startDate = startOfWeek(monthStart, { locale: es }); + const endDate = endOfWeek(monthEnd, { locale: es }); + + const days = eachDayOfInterval({ start: startDate, end: endDate }); + + const nextMonth = () => setCurrentDate(addMonths(currentDate, 1)); + const prevMonth = () => setCurrentDate(subMonths(currentDate, 1)); + + const getReservationForDay = (day: Date) => { + return reservations.find(res => + isWithinInterval(day, { start: parseISO(res.start_date), end: parseISO(res.end_date) }) + ); + }; + + const rangeHasOverlap = (start: Date, end: Date) => { + const rangeDays = eachDayOfInterval({ start, end }); + return rangeDays.some(day => getReservationForDay(day)); + }; + + const handleDayClick = (day: Date) => { + const existingRes = getReservationForDay(day); + + if (existingRes) { + onSelectReservation(existingRes); + setSelectionStart(null); + return; + } + + if (!selectionStart) { + setSelectionStart(day); + return; + } + + let start = selectionStart; + let end = day; + + if (isBefore(day, selectionStart)) { + start = day; + end = selectionStart; + } + + if (rangeHasOverlap(start, end)) { + toast.error("No puedes seleccionar un rango que incluya días ya reservados."); + setSelectionStart(null); + return; + } + + onSelectRange(start, end); + setSelectionStart(null); + }; + + return ( +
+ {/* Header */} +
+

+ {format(currentDate, 'MMMM yyyy', { locale: es })} +

+
+ + +
+
+ + {/* Week Days */} +
+ {['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'].map(day => ( +
+ {day} +
+ ))} +
+ + {/* Days Grid - NUEVO DISEÑO TIPO AIRBNB */} +
+ {days.map((day) => { + const dayRes = getReservationForDay(day); + const isSelected = selectionStart && isSameDay(day, selectionStart); + const isCurrentMonth = isSameMonth(day, monthStart); + + // Palette de colores según referencia + let bgColor = 'bg-white'; + let numberBgColor = ''; + let numberTextColor = 'text-gray-400'; + + if (dayRes) { + if (dayRes.origin === 'Teneriffa2000') { + bgColor = 'bg-blue-100'; // Fondo azul pastel + numberBgColor = 'bg-blue-500'; // Círculo azul intenso + numberTextColor = 'text-white'; + } else { + bgColor = 'bg-yellow-100'; // Fondo amarillo pastel + numberBgColor = 'bg-yellow-500'; // Círculo amarillo intenso + numberTextColor = 'text-white'; + } + } else if (isSelected) { + bgColor = 'bg-gray-800'; + numberBgColor = 'bg-white'; + numberTextColor = 'text-gray-800'; + } else if (isCurrentMonth) { + numberTextColor = 'text-gray-900'; + } + + return ( +
handleDayClick(day)} + className={` + relative h-12 flex items-center justify-center cursor-pointer + transition-all duration-150 + ${bgColor} + `} + > +
+ {format(day, 'd')} +
+
+ ); + })} +
+
+ ); +} diff --git a/apps/web/src/components/DocumentUpload.tsx b/apps/web/src/components/DocumentUpload.tsx new file mode 100644 index 0000000..f0a19b3 --- /dev/null +++ b/apps/web/src/components/DocumentUpload.tsx @@ -0,0 +1,390 @@ +import { useEffect, useImperativeHandle, useRef, useState, forwardRef } from 'react'; +import { Upload, Trash2, FileText, AlertCircle, Loader2, X, Maximize2 } from 'lucide-react'; +import { + useFileUpload, + validateFile, + uploadDocumentFile, + type UploadedContract, + type DocumentType, +} from '../hooks/useFileUpload'; +import { motion, AnimatePresence } from 'framer-motion'; + +/** + * Imperativo que expone el componente al padre. Cuando el modal se monta en + * modo "create" no hay reservation_id todavía, así que los archivos quedan en + * `pendingFiles`. Tras crear la reserva, el padre llama a `flushPending(id)` + * para subir todos los pendientes a la nueva reserva. + */ +export interface DocumentUploadHandle { + hasPending: () => boolean; + flushPending: (reservationId: string) => Promise; +} + +interface Props { + /** ID de la reserva. Si es undefined, los archivos se acumulan localmente. */ + reservationId?: string; + documentType: DocumentType; +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +const isImage = (mimeType: string) => mimeType.startsWith('image/'); + +interface PendingFile { + id: string; // local id (uuid-ish) + file: File; + previewUrl: string | null; // para imágenes locales +} + +export const DocumentUpload = forwardRef(function DocumentUpload( + { reservationId, documentType }, + ref, +) { + const safeId = reservationId ?? '__pending__'; + const { uploading, error: uploadError, uploadFile, fetchContracts, getSignedUrl, deleteContract } = + useFileUpload(safeId, documentType); + const [contracts, setContracts] = useState([]); + const [thumbnails, setThumbnails] = useState>({}); + const [lightboxUrl, setLightboxUrl] = useState(null); + const [loadingOpen, setLoadingOpen] = useState(null); + const [deletingId, setDeletingId] = useState(null); + const [pending, setPending] = useState([]); + const [localError, setLocalError] = useState(null); + const inputRef = useRef(null); + const [dragging, setDragging] = useState(false); + + const error = localError ?? uploadError; + + // Carga lista de archivos remotos solo si hay reservationId + useEffect(() => { + if (!reservationId) { + setContracts([]); + return; + } + fetchContracts().then(list => { + setContracts(list); + list.filter(c => isImage(c.mime_type)).forEach(async c => { + const url = await getSignedUrl(c.file_path); + if (url) setThumbnails(prev => ({ ...prev, [c.id]: url })); + }); + }); + }, [reservationId, fetchContracts, getSignedUrl]); + + // Limpia las URLs de objeto al desmontar + useEffect(() => { + return () => { + pending.forEach(p => p.previewUrl && URL.revokeObjectURL(p.previewUrl)); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useImperativeHandle(ref, () => ({ + hasPending: () => pending.length > 0, + flushPending: async (newReservationId: string) => { + for (const p of pending) { + try { + await uploadDocumentFile(p.file, newReservationId, documentType); + } catch (err) { + console.error('Error subiendo archivo pendiente:', err); + } + } + pending.forEach(p => p.previewUrl && URL.revokeObjectURL(p.previewUrl)); + setPending([]); + }, + }), [pending, documentType]); + + const handleFiles = async (files: FileList | null) => { + if (!files || files.length === 0) return; + setLocalError(null); + + if (!reservationId) { + // Modo diferido: acumular localmente + const newPending: PendingFile[] = []; + for (const file of Array.from(files)) { + const validationError = validateFile(file); + if (validationError) { + setLocalError(validationError); + continue; + } + newPending.push({ + id: `pending-${Date.now()}-${Math.random().toString(36).slice(2)}`, + file, + previewUrl: isImage(file.type) ? URL.createObjectURL(file) : null, + }); + } + if (newPending.length > 0) { + setPending(prev => [...newPending, ...prev]); + } + return; + } + + // Modo directo: subir al servidor + for (const file of Array.from(files)) { + const result = await uploadFile(file); + if (result) { + setContracts(prev => [result, ...prev]); + if (isImage(result.mime_type)) { + const url = await getSignedUrl(result.file_path); + if (url) setThumbnails(prev => ({ ...prev, [result.id]: url })); + } + } + } + }; + + const handleOpen = async (contract: UploadedContract) => { + if (isImage(contract.mime_type) && thumbnails[contract.id]) { + setLightboxUrl(thumbnails[contract.id]); + return; + } + setLoadingOpen(contract.id); + const url = await getSignedUrl(contract.file_path); + setLoadingOpen(null); + if (url) { + if (isImage(contract.mime_type)) { + setLightboxUrl(url); + } else { + window.open(url, '_blank', 'noopener,noreferrer'); + } + } + }; + + const handleDelete = async (contract: UploadedContract) => { + setDeletingId(contract.id); + const ok = await deleteContract(contract.id, contract.file_path); + setDeletingId(null); + if (ok) { + setContracts(prev => prev.filter(c => c.id !== contract.id)); + setThumbnails(prev => { const n = { ...prev }; delete n[contract.id]; return n; }); + } + }; + + const handleDeletePending = (id: string) => { + setPending(prev => { + const target = prev.find(p => p.id === id); + if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl); + return prev.filter(p => p.id !== id); + }); + }; + + const handleOpenPending = (p: PendingFile) => { + if (p.previewUrl) { + setLightboxUrl(p.previewUrl); + } else { + // Para PDFs locales, abre en nueva pestaña con object URL + const url = URL.createObjectURL(p.file); + window.open(url, '_blank', 'noopener,noreferrer'); + // No revocamos inmediatamente: el navegador lo necesita mientras esté abierto + } + }; + + return ( + <> +
+ {/* Drop zone */} +
{ e.preventDefault(); setDragging(true); }} + onDragLeave={() => setDragging(false)} + onDrop={e => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files); }} + onClick={() => inputRef.current?.click()} + className={` + border-2 border-dashed rounded-xl p-4 cursor-pointer transition-all text-center + ${dragging + ? 'border-emerald-500 bg-emerald-900/20' + : 'border-slate-600 bg-slate-800/50 hover:border-slate-500 hover:bg-slate-800' + } + `} + > + handleFiles(e.target.files)} + /> + {uploading ? ( +
+ + Subiendo... +
+ ) : ( +
+ + + Arrastra archivos o pulsa para seleccionar + + PDF, JPEG, PNG · máx. 10 MB + {!reservationId && (pending.length > 0) && ( + + Se subirán al guardar la reserva + + )} +
+ )} +
+ + {/* Error */} + {error && ( +
+ + {error} +
+ )} + + {/* Pending files (modo diferido) */} + {pending.length > 0 && ( +
    + {pending.map(p => ( +
  • + {isImage(p.file.type) && p.previewUrl && ( + + )} +
    + {!isImage(p.file.type) && ( +
    + +
    + )} +
    +

    {p.file.name}

    +

    {formatBytes(p.file.size)} · pendiente

    +
    + {!isImage(p.file.type) && ( + + )} + +
    +
  • + ))} +
+ )} + + {/* Uploaded files */} + {contracts.length > 0 && ( +
    + {contracts.map(contract => ( +
  • + {isImage(contract.mime_type) && ( + + )} +
    + {!isImage(contract.mime_type) && ( +
    + +
    + )} +
    +

    {contract.filename}

    +

    {formatBytes(contract.size_bytes)}

    +
    + {!isImage(contract.mime_type) && ( + + )} + +
    +
  • + ))} +
+ )} +
+ + {/* Lightbox */} + + {lightboxUrl && ( + setLightboxUrl(null)} + className="fixed inset-0 bg-black/92 z-[100] flex items-center justify-center p-4" + > + + e.stopPropagation()} + /> + + )} + + + ); +}); diff --git a/apps/web/src/components/LoginPage.tsx b/apps/web/src/components/LoginPage.tsx new file mode 100644 index 0000000..bd21dcc --- /dev/null +++ b/apps/web/src/components/LoginPage.tsx @@ -0,0 +1,108 @@ +import React, { useState } from 'react'; +import { supabase } from '../lib/supabase'; +import { Calendar, Loader2, Lock, Mail, ArrowRight } from 'lucide-react'; +import { toast } from 'sonner'; + +export function LoginPage() { + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [loading, setLoading] = useState(false); + + const handleLogin = async (e: React.FormEvent) => { + e.preventDefault(); + setLoading(true); + + try { + const { error } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (error) { + toast.error('Error al iniciar sesión: ' + error.message); + } else { + toast.success('¡Bienvenido de nuevo!'); + } + } catch (err) { + toast.error('Ocurrió un error inesperado'); + console.error(err); + } finally { + setLoading(false); + } + }; + + return ( +
+
+ + {/* Header */} +
+
+ +
+

+ Naturcalabacera +

+

+ Sistema de Gestión de Reservas +

+
+ + {/* Form */} +
+
+ +
+ + setEmail(e.target.value)} + className="w-full bg-stone-50 dark:bg-black/40 border border-stone-200 dark:border-emerald-900/30 rounded-xl py-3 pl-12 pr-4 text-stone-900 dark:text-white placeholder:text-stone-400 dark:placeholder:text-emerald-800/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500/50 transition-all font-medium" + placeholder="nombre@empresa.com" + /> +
+
+ +
+ +
+ + setPassword(e.target.value)} + className="w-full bg-stone-50 dark:bg-black/40 border border-stone-200 dark:border-emerald-900/30 rounded-xl py-3 pl-12 pr-4 text-stone-900 dark:text-white placeholder:text-stone-400 dark:placeholder:text-emerald-800/40 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500/50 transition-all font-medium" + placeholder="••••••••" + /> +
+
+ + +
+ + {/* Footer */} +
+

+ Protegido por autenticación segura +

+
+
+
+ ); +} diff --git a/apps/web/src/components/MobileNavigation.tsx b/apps/web/src/components/MobileNavigation.tsx new file mode 100644 index 0000000..8c1acc8 --- /dev/null +++ b/apps/web/src/components/MobileNavigation.tsx @@ -0,0 +1,89 @@ +import { Calendar, Settings, CalendarDays, Home, Users } from 'lucide-react'; +import { useProperty } from '../contexts/PropertyContext'; +import { PROPERTY_CONFIG, PROPERTIES } from '@naturcalabacera/shared'; +import type { Property } from '@naturcalabacera/shared'; + +interface Props { + currentView: string; + onNavigate: (view: string) => void; + isViewer?: boolean; + isAdmin?: boolean; +} + +export function MobileNavigation({ currentView, onNavigate, isViewer = false, isAdmin = false }: Props) { + const { property, setProperty } = useProperty(); + const allMenuItems = [ + { id: 'calendar', label: 'Mensual', icon: Calendar, requires: 'all' as const }, + { id: 'yearly', label: 'Anual', icon: CalendarDays, requires: 'all' as const }, + { id: 'users', label: 'Usuarios', icon: Users, requires: 'admin' as const }, + { id: 'settings', label: 'Ajustes', icon: Settings, requires: 'staff' as const }, + ]; + const menuItems = allMenuItems.filter(item => { + if (item.requires === 'all') return true; + if (item.requires === 'admin') return isAdmin; + if (item.requires === 'staff') return !isViewer; + return false; + }); + + return ( +
+ {/* Selector de propiedad en mobile — fila superior compacta (solo staff) */} + {!isViewer && ( +
+ {PROPERTIES.map((p: Property) => { + const config = PROPERTY_CONFIG[p]; + const isActive = property === p; + return ( + + ); + })} +
+ )} + + {/* Navegación principal */} +
+ {menuItems.map((item) => { + const Icon = item.icon; + const isActive = currentView === item.id; + + return ( + + ); + })} +
+
+ ); +} diff --git a/apps/web/src/components/PricingSection.tsx b/apps/web/src/components/PricingSection.tsx new file mode 100644 index 0000000..90a9bba --- /dev/null +++ b/apps/web/src/components/PricingSection.tsx @@ -0,0 +1,87 @@ +import { calculateNaturPrice, formatPrice, DEFAULT_IGIC_RATE } from '@naturcalabacera/shared'; +import { differenceInDays, parseISO } from 'date-fns'; +import { Calculator } from 'lucide-react'; +import type { Property } from '../types'; + +interface Props { + property: Property; + startDate: string; + endDate: string; + adults: number; + children: number; + igicRate?: number; +} + +/** + * Muestra el desglose de precios para reservas Naturcalabacera vacacional. + * El cálculo es en tiempo real — no requiere guardar para ver los precios. + * Al guardar, el llamador debe congelar el snapshot en pricing_snapshot. + */ +export function PricingSection({ property, startDate, endDate, adults, children, igicRate = DEFAULT_IGIC_RATE }: Props) { + const nights = startDate && endDate + ? Math.max(0, differenceInDays(parseISO(endDate), parseISO(startDate))) + : 0; + const totalPersons = (Number(adults) || 0) + (Number(children) || 0); + + if (nights <= 0 || totalPersons <= 0) { + return ( +
+ +

+ Introduce fechas y personas para ver el cálculo de precio +

+
+ ); + } + + const year = startDate ? parseISO(startDate).getFullYear() : new Date().getFullYear(); + const pricing = calculateNaturPrice({ property, nights, totalPersons, igicRate, year }); + + return ( +
+
+ + Precio Natur + + {nights}n · {totalPersons}p + +
+ +
+
+ Canon base ({nights} noches) + {formatPrice(pricing.basePrice)} +
+ + {pricing.extraPersons > 0 && ( +
+ + +{pricing.extraPersons} persona{pricing.extraPersons !== 1 ? 's' : ''} extra + (sobre {pricing.includedPersons} incluidas) + + {formatPrice(pricing.extraPersonsFee)} +
+ )} + +
+ Subtotal + {formatPrice(pricing.subtotal)} +
+ +
+ IGIC ({(igicRate * 100).toFixed(0)}%) + {formatPrice(pricing.igicAmount)} +
+ +
+ Total + {formatPrice(pricing.total)} +
+
+ +

+ * Precio calculado al vuelo. Se congela al guardar la reserva. +

+
+ ); +} diff --git a/apps/web/src/components/PropertySelector.tsx b/apps/web/src/components/PropertySelector.tsx new file mode 100644 index 0000000..7093afc --- /dev/null +++ b/apps/web/src/components/PropertySelector.tsx @@ -0,0 +1,43 @@ +import { useProperty } from '../contexts/PropertyContext'; +import { PROPERTY_CONFIG, PROPERTIES } from '@naturcalabacera/shared'; +import type { Property } from '@naturcalabacera/shared'; + +export function PropertySelector() { + const { property, setProperty } = useProperty(); + + return ( +
+ + Propiedad + +
+ {PROPERTIES.map((p: Property) => { + const config = PROPERTY_CONFIG[p]; + const isActive = property === p; + return ( + + ); + })} +
+
+ ); +} diff --git a/apps/web/src/components/ReservationModal.tsx b/apps/web/src/components/ReservationModal.tsx new file mode 100644 index 0000000..e5af702 --- /dev/null +++ b/apps/web/src/components/ReservationModal.tsx @@ -0,0 +1,628 @@ +import { useEffect, useRef, useState } from 'react'; +import { useForm } from 'react-hook-form'; +import type { NewReservation, Reservation, Property } from '../types'; +import { X, Check, Trash2, AlertCircle, ChevronDown, Zap, Paperclip, Receipt } from 'lucide-react'; +import { differenceInDays, parseISO } from 'date-fns'; +import { motion, AnimatePresence } from 'framer-motion'; +import { PROPERTY_CONFIG, getExtraPersonRate } from '@naturcalabacera/shared'; +import { useProperty } from '../contexts/PropertyContext'; +import { PricingSection } from './PricingSection'; +import { DocumentUpload, type DocumentUploadHandle } from './DocumentUpload'; + +interface Props { + isOpen: boolean; + mode: 'create' | 'edit'; + initialData?: Partial; + existingReservations?: Reservation[]; + onClose: () => void; + onSave: (data: NewReservation) => Promise; + onDelete?: (id: string) => Promise; +} + +const EVENT_TYPES = ['Boda', 'Comunión', 'Cumpleaños', 'Evento privado', 'Corporativo', 'Otro'] as const; + +export function ReservationModal({ + isOpen, + mode, + initialData, + existingReservations = [], + onClose, + onSave, + onDelete, +}: Props) { + const { property } = useProperty(); + const propertyConfig = PROPERTY_CONFIG[property]; + + const { + register, + handleSubmit, + watch, + reset, + setValue, + setError, + clearErrors, + formState: { errors }, + } = useForm(); + + // Event toggle — local state (not a form field, controls section visibility) + const [isEvent, setIsEvent] = useState(false); + + // Override manual de la tarifa por persona extra (€/pax/noche). + // null = usar tarifa automática por año. + const [extraRateOverride, setExtraRateOverride] = useState(null); + + // Refs a los DocumentUpload para hacer flush de archivos pendientes tras crear la reserva. + const contractUploadRef = useRef(null); + const invoiceUploadRef = useRef(null); + + useEffect(() => { + if (isOpen) { + reset({ + origin: 'Teneriffa2000', + adults_count: 2, + children_count: 0, + government_registration: '', + has_cleaning: false, + has_pool_heating: false, + has_flies_products: false, + observations: '', + is_event: false, + event_type: '', + event_type_other: '', + attendees_count: 0, + ...initialData, + }); + setIsEvent(initialData?.is_event ?? false); + const snapshotOverride = initialData?.pricing_snapshot?.extraPersonRateOverride; + setExtraRateOverride(snapshotOverride ?? null); + clearErrors(); + } + }, [isOpen, initialData, reset, clearErrors]); + + const startDate = watch('start_date'); + const endDate = watch('end_date'); + const adults = watch('adults_count'); + const children = watch('children_count'); + const origin = watch('origin'); + const eventType = watch('event_type'); + + const totalDays = startDate && endDate + ? Math.max(0, differenceInDays(parseISO(endDate), parseISO(startDate))) + : 0; + const totalPeople = (Number(adults) || 0) + (Number(children) || 0); + + // Auto-correct: if start_date moves ahead of end_date, set end_date = start_date + useEffect(() => { + if (startDate && endDate && parseISO(endDate) < parseISO(startDate)) { + setValue('end_date', startDate); + clearErrors('end_date'); + } + }, [startDate, endDate, setValue, clearErrors]); + + // Event pricing: uses totalPeople (adults + children) as attendee count. + // La tarifa por persona extra depende del año de start_date (12€ en 2026, 14€ desde 2027) + // y puede sobrescribirse manualmente con extraRateOverride. + const reservationYear = startDate ? parseISO(startDate).getFullYear() : new Date().getFullYear(); + const autoExtraRate = getExtraPersonRate(property, reservationYear); + const effectiveExtraRate = extraRateOverride ?? autoExtraRate; + const eventPricing = (() => { + const cfg = PROPERTY_CONFIG[property]; + const extra = Math.max(0, totalPeople - cfg.pricing.includedPersons); + const subtotal = cfg.pricing.baseRatePerNight + extra * effectiveExtraRate; + return { extra, subtotal, cfg, extraRate: effectiveExtraRate, isOverride: extraRateOverride !== null }; + })(); + + /** + * Overlap check — intervalos semi-abiertos [start, end). + * El día de salida de una reserva existente SÍ permite entrada ese mismo día: + * si res=[19, 20] y new=[20, 21], no hay solapamiento (check-out y check-in mismo día). + * Fórmula: overlap iff newStart < resEnd AND newEnd > resStart + */ + const checkOverlap = (start: string, end: string, currentProperty: Property): boolean => { + const newStart = parseISO(start); + const newEnd = parseISO(end); + const toCheck = existingReservations.filter(r => { + if (mode === 'edit' && r.id === initialData?.id) return false; + return r.property === currentProperty; + }); + return toCheck.some(res => { + const resStart = parseISO(res.start_date); + const resEnd = parseISO(res.end_date); + return newStart < resEnd && newEnd > resStart; + }); + }; + + const onSubmit = async (data: NewReservation) => { + if (!data.start_date || !data.end_date) { + setError('start_date', { type: 'manual', message: 'Las fechas son obligatorias' }); + return; + } + if (parseISO(data.end_date) < parseISO(data.start_date)) { + setError('end_date', { type: 'manual', message: 'La fecha de salida no puede ser anterior a la de entrada' }); + return; + } + if (checkOverlap(data.start_date, data.end_date, property)) { + setError('start_date', { + type: 'manual', + message: `Las fechas seleccionadas se superponen con otra reserva en ${propertyConfig.label}`, + }); + return; + } + + // Build a clean payload: only include event fields when actually used, + // to avoid sending unknown columns to Supabase if the migration hasn't run. + const saveData: NewReservation = { + origin: data.origin, + client_name: data.client_name, + start_date: data.start_date, + end_date: data.end_date, + adults_count: Number(data.adults_count) || 0, + children_count: Number(data.children_count) || 0, + has_cleaning: Boolean(data.has_cleaning), + has_pool_heating: Boolean(data.has_pool_heating), + has_flies_products: Boolean(data.has_flies_products), + government_registration: data.government_registration || undefined, + observations: data.observations || undefined, + igic_rate: data.igic_rate, + pricing_snapshot: data.pricing_snapshot, + property, + }; + + if (isEvent) { + saveData.is_event = true; + if (data.event_type) saveData.event_type = data.event_type; + if (data.event_type === 'Otro' && data.event_type_other) saveData.event_type_other = data.event_type_other; + if (totalPeople > 0) saveData.attendees_count = totalPeople; + + // Congelar el cálculo del canon en pricing_snapshot + const cfg = PROPERTY_CONFIG[property].pricing; + const igicRate = data.igic_rate ?? 0.07; + const basePrice = cfg.baseRatePerNight; + const extraPersonsFee = eventPricing.extra * effectiveExtraRate; + const subtotal = basePrice + extraPersonsFee; + const igicAmount = Math.round(subtotal * igicRate * 100) / 100; + const total = Math.round((subtotal + igicAmount) * 100) / 100; + saveData.pricing_snapshot = { + basePrice, + extraPersonsFee, + subtotal, + igicAmount, + total, + calculatedAt: new Date().toISOString(), + extraPersonRate: effectiveExtraRate, + ...(extraRateOverride !== null ? { extraPersonRateOverride: extraRateOverride } : {}), + }; + } + + const result = await onSave(saveData); + if (!result) { + // onSave abortó (error o falta de id en edit). No cerramos el modal. + return; + } + // Si creamos una reserva nueva, sube los documentos pendientes ahora que tenemos id + const newId = typeof result === 'object' && 'id' in result ? (result as Reservation).id : undefined; + if (newId) { + try { + await Promise.all([ + contractUploadRef.current?.flushPending(newId), + invoiceUploadRef.current?.flushPending(newId), + ]); + } catch (err) { + console.error('Error subiendo documentos pendientes:', err); + } + } + onClose(); + }; + + return ( + + {isOpen && ( + <> + {/* Backdrop */} + + + {/* Sheet — always dark */} + + {/* Drag handle */} +
+
+
+ +
+ {/* Header */} +
+
+

+ {mode === 'create' ? 'Nueva Estancia' : 'Editar Estancia'} +

+

+ {totalDays} noches · {totalPeople} personas +

+
+
+ {propertyConfig.label} +
+
+ +
+ +
+ + {/* Validation error */} + {(errors.start_date || errors.end_date) && ( +
+ +
+

Error de validación

+

+ {errors.start_date?.message || errors.end_date?.message} +

+
+
+ )} + + {/* 1. Empresa / Origen */} +
+ +
+