@ffstack/turnos 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # turnos
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Turnero instalable por npm: componentes de React para que un **usuario elija un turno** y un **administrador controle los turnos**, sobre **Firebase (Firestore)** o **Supabase**, con un adaptador **memoria** para demos y tests.
4
+
5
+ [![npm](https://img.shields.io/npm/v/turnos)](https://www.npmjs.com/package/turnos)
6
+ [![GitHub](https://img.shields.io/badge/GitHub-Fran249%2Fturnos--react-blue)](https://github.com/Fran249/turnos-react)
7
+
8
+ **Live repo:** <https://github.com/Fran249/turnos-react>
9
+
10
+ Al instalarse, `turnos` genera en tu proyecto:
11
+
12
+ | Archivo | Para qué |
13
+ |---|---|
14
+ | `src/turnos/TurnoPicker.jsx` | Componente del usuario: ve los turnos del día y elige uno |
15
+ | `src/turnos/TurnoAdmin.jsx` | Componente del administrador: crea, cambia estado y elimina turnos |
16
+ | `src/turnos/turnos.css` | Estilos autónomos (sin Tailwind ni fuentes web): talones con perforación, registro rayado y formulario del admin. **No trae paleta ni tipografía**: hereda las de tu app |
17
+ | `src/turnos/turnos.config.js` | Config de tu proveedor (Firebase **o** Supabase) + cliente `turnos` |
18
+ | `firestore.rules` *(firebase)* | Reglas Firestore: lectura pública, escritura de admin |
19
+ | `supabase-migrations/0001_turnos.sql` *(supabase)* | Tabla `public.turnos`, RLS y RPC `book_turno` atómico |
20
+
21
+ ## Instalación y configuración
22
+
23
+ npm **no** reenvía flags de CLI (`npm i turnos --firebase` no llega al postinstall). Las formas soportadas:
24
+
25
+ ```bash
26
+ # 1) CLI explícita (recomendada, determinista):
27
+ npm i turnos
28
+ npx turnos init --firebase # o: npx turnos init --supabase
29
+
30
+ # 2) Variable de entorno (el postinstall genera solo con esto):
31
+ TURNOS_PROVIDER=firebase npm i turnos
32
+ TURNOS_PROVIDER=supabase npm i turnos
33
+
34
+ # 3) Instalación simple: no escribe nada; el postinstall muestra la guía
35
+ # (siempre termina en 0, nunca rompe el `npm i`).
36
+ npm i turnos
37
+ ```
38
+
39
+ Opciones del CLI: `npx turnos init --firebase|--supabase [--force] [--dir <ruta>]`.
40
+ `--force` sobreescribe archivos ya generados; por defecto los respeta y te los lista.
41
+
42
+ La config generada contiene **solo placeholders** (`TU_API_KEY`, `TU_ORG.supabase.co`, `TU_ANON_KEY`): rellénala con tus credenciales.
43
+
44
+ ## Uso
45
+
46
+ ```jsx
47
+ // App del usuario
48
+ import { turnos } from './src/turnos/turnos.config'
49
+ import TurnoPicker from './src/turnos/TurnoPicker'
50
+
51
+ <TurnoPicker adapter={turnos} user="elsil" />
52
+ // props: user (obligatorio), date? 'YYYY-MM-DD' (default hoy),
53
+ // onBooked?(turn), onUnbooked?(turn)
54
+ ```
55
+
56
+ ```jsx
57
+ // App del administrador
58
+ import { turnos } from './src/turnos/turnos.config'
59
+ import TurnoAdmin from './src/turnos/TurnoAdmin'
60
+
61
+ <TurnoAdmin adapter={turnos} />
62
+ // props: titulo? 'Administrar turnos'
63
+ ```
64
+
65
+ El componente solo consume el **contrato del cliente** (mismo API con cualquier proveedor):
66
+
67
+ | Método | Devuelve |
68
+ |---|---|
69
+ | `listTurnos({ date })` | `Promise<Turno[]>` del día (filter por `dayKey`) |
70
+ | `upsertTurno(input)` | `{ ok, turn }` si válido; `{ ok:false, errors[] }` si la validación del merge falla |
71
+ | `removeTurno(id)` | `{ ok, removed }` |
72
+ | `bookTurno(id, user)` | `{ ok, turn }` o `{ ok:false, error: 'lleno' \| 'cancelado' \| 'duplicado' \| 'inexistente' }` |
73
+ | `unbookTurno(id, user)` | `{ ok, turn }` |
74
+ | `subscribe(cb)` | dispara al instante y en cada mutación; devuelve `unsubscribe()` |
75
+
76
+ Turno: `{ id, title, staff, hour: "HH:MM", durationMin (def 30), priority: low|medium|high (def medium), status: pending|confirmed|completed|cancelled, date: "YYYY-MM-DD", notes, capacity (def 1), booked: string[] }`.
77
+
78
+ ## Proveedores
79
+
80
+ - **Firebase** — `src/adapters/firebase.js`: consulta por `date` con `where`, streaming con `onSnapshot`, reserva en `runTransaction` (la integridad de capacidad/duplicados la garantiza la transacción; las reglas no pueden expresar `booked.length < capacity`). Deploy: `firebase deploy --only firestore:rules`.
81
+ - **Supabase** — `src/adapters/supabase.js`: tabla `public.turnos` + RPC `book_turno(turno_id, user)` con `for update` (atómico para capacidad), realtime por `.channel()`. Push: `supabase db push` o aplica la migración.
82
+ - **Memoria** — `provider: 'memory'` + `turns` iniciales: para demos, previews y tests.
83
+
84
+ Ejemplo de cliente con memoria:
85
+
86
+ ```js
87
+ import { createClient } from 'turnos'
88
+ const turnos = createClient({
89
+ provider: 'memory',
90
+ turns: [{ title: 'Mañana', staff: 'Equipo A', hour: '09:00', date: '2026-11-11', status: 'confirmed' }],
91
+ })
92
+ ```
93
+
94
+ Los turnos iniciales que no traen `id` reciben uno generado: el `id` es la key de las listas y el identificador de `bookTurno` / `upsertTurno` / `removeTurno`.
95
+
96
+ ## Tema (colores y tipografía son tuyos)
97
+
98
+ El componente instalado **no impone paleta ni tipografía**: por defecto usa el color de texto y la fuente heredados de tu app (`currentColor` / `inherit`). Los valores por defecto viven en `:where(.turnos)` (especificidad 0), así que cualquier regla tuya gana sin importar el orden de import.
99
+
100
+ Sobreescribí los tokens desde tu CSS:
101
+
102
+ ```css
103
+ .turnos {
104
+ --turnos-font: "Inter", system-ui, sans-serif; /* fuente base */
105
+ --turnos-serif: Georgia, serif; /* hora y título */
106
+ --turnos-bg: #faf7f1; /* fondo de la tarjeta */
107
+ --turnos-surface: #ffffff; /* filas, talones, panel del form */
108
+ --turnos-field: #faf7f1; /* inputs del admin */
109
+ --turnos-ink: #221a12; /* texto y bordes fuertes */
110
+ --turnos-soft: #6b6257; /* texto secundario */
111
+ --turnos-line: #e6ded2; /* líneas y bordes */
112
+ --turnos-accent: #3f5a2f; /* foco y avisos OK */
113
+ --turnos-danger: #9c3b2e; /* errores y "Eliminar" */
114
+ --turnos-primary-bg: #221a12; /* botón primario */
115
+ --turnos-primary-ink: #faf7f1;
116
+ --turnos-primary-bg-hover: #3a2c1f;
117
+ }
118
+ ```
119
+
120
+ También podés mapear estados y prioridades: `--turnos-status-*` (`pending`, `confirmed`, `completed`, `cancelled`) y `--turnos-priority-*` (`low`, `medium`, `high`).
121
+
122
+ Qué **no** es un token, a propósito: los tamaños de texto, el espaciado y la estructura (talón, registro, rejilla del formulario). Eso es el componente y no debería cambiar con el tema. No hay `prefers-color-scheme` forzado: si tu app tiene modo oscuro, remapeá los mismos tokens.
123
+
124
+ > La perforación del talón se dibuja con `--turnos-bg`. Si dejás la tarjeta transparente, poné ahí el fondo real de la página para que las muescas se vean.
125
+
126
+ ## Rutas de la demo
127
+
128
+ El repo incluye una demo Vite (`npm run dev`) con **dos superficies, una por rol**. No se publica en el paquete.
129
+
130
+ | Ruta | Superficie |
131
+ |---|---|
132
+ | `/` y `/user` | **Usuario**: agenda del día + `TurnoPicker` para reservar. El calendario del mes es el índice; la tira semanal y el calendario mueven el día. Sin crear, sin estadísticas, sin eliminar |
133
+ | `/admin` | **Administrador**: `TurnoAdmin` para crear, cambiar estado y eliminar, más el resumen por estado y `StatsView` |
134
+
135
+ Las dos superficies comparten un solo cliente, `src/localClient.js`, que implementa el contrato del paquete sobre el store de `localStorage`. Una reserva hecha en `/user` actualiza el calendario y aparece en el registro de `/admin` sin recargar; un turno creado en `/admin` aparece en la agenda del usuario. Vite sirve `index.html` para rutas desconocidas (`appType: 'spa'`), así que las URLs funcionan también al abrirlas directamente.
136
+
137
+ `TurnoPicker` acepta `date` (fecha inicial), `onDateChange` y `showDateNav` (por defecto `true`). Cuando el anfitrión controla la fecha —como esta demo, que usa la tira semanal y el calendario— pasa `showDateNav={false}` y una `key={date}` para remontar el componente en el día nuevo.
138
+
139
+ ## Desarrollo
140
+
141
+ ```bash
142
+ npm test # vitest (unidades + componentes + generator + postinstall)
143
+ npm run test:coverage # cobertura v8 (src/**, objetivo ≥ 80 %)
144
+ npm run lint # oxlint
145
+ npm run build # vite build
146
+ ```
package/bin/turnos.js ADDED
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { generateFiles, resolveTargetDir } from '../src/generator.js';
4
+ import { runPostinstall } from '../src/postinstall.js';
5
+
6
+ /**
7
+ * CLI de `turnos`:
8
+ * npx turnos init --firebase [--force] [--dir <ruta>]
9
+ * npx turnos init --supabase [--force] [--dir <ruta>]
10
+ * node bin/turnos.js postinstall (lo lanza npm al instalar)
11
+ */
12
+ const { values, positionals } = parseArgs({
13
+ args: process.argv.slice(2),
14
+ allowPositionals: true,
15
+ options: {
16
+ firebase: { type: 'boolean' },
17
+ supabase: { type: 'boolean' },
18
+ force: { type: 'boolean' },
19
+ dir: { type: 'string' },
20
+ help: { type: 'boolean' },
21
+ },
22
+ });
23
+
24
+ const command = positionals[0] || 'postinstall';
25
+
26
+ function usage() {
27
+ console.log(
28
+ 'turnos — turnero npm (Firebase | Supabase)\n\n' +
29
+ 'Uso:\n' +
30
+ ' npx turnos init --firebase [--force] [--dir <ruta>]\n' +
31
+ ' npx turnos init --supabase [--force] [--dir <ruta>]\n' +
32
+ ' node bin/turnos.js postinstall (lo lanza npm al instalar)\n\n' +
33
+ 'También: TURNOS_PROVIDER=firebase npm i turnos (o --supabase)\n',
34
+ );
35
+ }
36
+
37
+ if (values.help || command === 'help') {
38
+ usage();
39
+ process.exit(0);
40
+ }
41
+
42
+ if (command === 'postinstall') {
43
+ // WARN-ONLY: runPostinstall nunca lanza; la instalación nunca se rompe.
44
+ await runPostinstall({ targetDir: values.dir || resolveTargetDir() });
45
+ process.exit(0);
46
+ }
47
+
48
+ if (command === 'init') {
49
+ const provider = values.firebase ? 'firebase' : values.supabase ? 'supabase' : null;
50
+ if (!provider) {
51
+ console.error('Falta el proveedor. Uso: npx turnos init --firebase (o --supabase)');
52
+ process.exit(1);
53
+ }
54
+ const res = await generateFiles({ provider, targetDir: values.dir || resolveTargetDir(), force: values.force });
55
+ if (res.self) {
56
+ console.log('Estás en el propio paquete "turnos" (no-op). Usa --dir <proyecto-consumidor> para generar en otra parte.');
57
+ process.exit(0);
58
+ }
59
+ for (const f of res.generated) console.log(` + ${f}`);
60
+ for (const f of res.skipped) console.log(` = ${f} (ya existía; usa --force para sobrescribir)`);
61
+ if (provider === 'supabase') {
62
+ console.log('\nSiguiente paso: ejecuta la migración en tu Supabase: supabase db push (o psql "$DATABASE_URL" < supabase-migrations/0001_turnos.sql)');
63
+ } else {
64
+ console.log('\nSiguiente paso: publica las reglas: firebase deploy --only firestore:rules');
65
+ }
66
+ process.exit(0);
67
+ }
68
+
69
+ console.error(`Comando desconocido: ${command}\n\n`);
70
+ usage();
71
+ process.exit(1);
package/package.json CHANGED
@@ -1,6 +1,86 @@
1
1
  {
2
2
  "name": "@ffstack/turnos",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Turnero npm: componentes usuario/admin de turnos sobre Firebase (Firestore) o Supabase, generados al instalar (npx turnos init --firebase | --supabase).",
8
+ "type": "module",
9
+ "license": "MIT",
10
+ "main": "src/core/index.js",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/Fran249/turnos-react.git"
14
+ },
15
+ "exports": {
16
+ ".": "./src/core/index.js",
17
+ "./core": "./src/core/index.js",
18
+ "./adapters/firebase": "./src/adapters/firebase.js",
19
+ "./adapters/supabase": "./src/adapters/supabase.js"
20
+ },
21
+ "bin": {
22
+ "turnos": "bin/turnos.js"
23
+ },
24
+ "files": [
25
+ "bin",
26
+ "src/core",
27
+ "src/adapters",
28
+ "src/generator.js",
29
+ "src/postinstall.js",
30
+ "templates",
31
+ "README.md",
32
+ "!**/*.test.js",
33
+ "!**/*.test.jsx"
34
+ ],
35
+ "scripts": {
36
+ "dev": "vite",
37
+ "build": "vite build",
38
+ "lint": "oxlint",
39
+ "preview": "vite preview",
40
+ "test": "vitest run",
41
+ "test:watch": "vitest",
42
+ "test:coverage": "vitest run --coverage",
43
+ "postinstall": "node bin/turnos.js postinstall"
44
+ },
45
+ "peerDependencies": {
46
+ "react": "^18.0.0 || ^19.0.0",
47
+ "react-dom": "^18.0.0 || ^19.0.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "firebase": {
51
+ "optional": true
52
+ },
53
+ "@supabase/supabase-js": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "keywords": [
58
+ "turnos",
59
+ "turnero",
60
+ "scheduling",
61
+ "shifts",
62
+ "firebase",
63
+ "supabase"
64
+ ],
65
+ "dependencies": {
66
+ "date-fns": "^4.4.0",
67
+ "lucide-react": "^1.71.0",
68
+ "react": "^19.3.1",
69
+ "react-dom": "^19.3.1"
70
+ },
71
+ "devDependencies": {
72
+ "@testing-library/jest-dom": "^7.0.1",
73
+ "@testing-library/react": "^16.3.3",
74
+ "@testing-library/user-event": "^14.6.9",
75
+ "@types/react": "^19.3.0",
76
+ "@types/react-dom": "^19.3.0",
77
+ "@vitejs/plugin-react": "^6.1.2",
78
+ "@vitest/coverage-v8": "^5.1.0",
79
+ "autoprefixer": "^10.6.2",
80
+ "jsdom": "^31.0.0",
81
+ "oxlint": "^1.90.0",
82
+ "tailwindcss": "^3.4.17",
83
+ "vite": "^8.3.6",
84
+ "vitest": "^5.1.0"
85
+ }
86
+ }
@@ -0,0 +1,104 @@
1
+ import { bookingDecision, dayKey, normalizeTurn, uid, validateTurno } from '../core/validate.js';
2
+
3
+ /**
4
+ * Firebase (Firestore) adapter.
5
+ *
6
+ * No top-level `import 'firebase'`: the consumer's generated config
7
+ * (templates/config.turnos.firebase.js) injects the Firestore instance and
8
+ * the SDK functions this adapter calls. That keeps `import 'turnos'` light
9
+ * and makes the adapter testable with a fake SDK surface.
10
+ *
11
+ * Booking integrity (capacity/duplicate/cancelled) is enforced inside a
12
+ * `runTransaction`; Firestore rules cannot express `booked.length < capacity`,
13
+ * so the transaction is the integrity point (see templates/rules/firestore.rules).
14
+ * Dates are stored padded 'YYYY-MM-DD' and compared through dayKey().
15
+ */
16
+
17
+ /** Padded 'YYYY-MM-DD' from a possibly-unpadded day ('2026-11-3'). */
18
+ function paddedDay(dateStr) {
19
+ const [y, m, d] = dayKey(dateStr).split('-');
20
+ return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
21
+ }
22
+
23
+ export function createFirebaseClient(config = {}) {
24
+ const inj = config.firebase;
25
+ if (!inj?.db || !inj?.sdk) {
26
+ throw new Error(
27
+ 'Adaptador firebase: falta config.firebase = { db, sdk, collectionName } (se genera con `npx turnos init --firebase`).',
28
+ );
29
+ }
30
+ const { db, sdk } = inj;
31
+ const name = inj.collectionName || 'turnos';
32
+
33
+ const docsToTurns = (docs) =>
34
+ (docs || [])
35
+ .filter((d) => d && d.exists)
36
+ .map((d) => normalizeTurn({ id: d.id, ...d.data() }));
37
+
38
+ async function getTurn(id) {
39
+ const snap = await sdk.getDoc(sdk.doc(db, name, id));
40
+ return snap.exists ? normalizeTurn({ id, ...snap.data() }) : null;
41
+ }
42
+
43
+ return {
44
+ provider: 'firebase',
45
+
46
+ async listTurnos({ date } = {}) {
47
+ const q = date
48
+ ? sdk.query(sdk.collection(db, name), sdk.where('date', '==', paddedDay(date)))
49
+ : sdk.collection(db, name);
50
+ const snap = await sdk.getDocs(q);
51
+ return docsToTurns(snap.docs);
52
+ },
53
+
54
+ async upsertTurno(input = {}) {
55
+ if (input.id) {
56
+ const actual = await getTurn(input.id);
57
+ if (!actual) return { ok: false, errors: ['El turno ya no existe.'] };
58
+ const merged = { ...actual, ...input, id: actual.id };
59
+ const errors = validateTurno(merged);
60
+ if (errors.length > 0) return { ok: false, errors };
61
+ const turn = normalizeTurn(merged);
62
+ await sdk.updateDoc(sdk.doc(db, name, actual.id), turn);
63
+ return { ok: true, turn };
64
+ }
65
+ const errors = validateTurno(input);
66
+ if (errors.length > 0) return { ok: false, errors };
67
+ const id = uid();
68
+ const turn = normalizeTurn({ ...input, id });
69
+ await sdk.setDoc(sdk.doc(db, name, id), turn);
70
+ return { ok: true, turn };
71
+ },
72
+
73
+ async removeTurno(id) {
74
+ const exists = (await getTurn(id)) !== null;
75
+ if (exists) await sdk.deleteDoc(sdk.doc(db, name, id));
76
+ return { ok: true, removed: exists };
77
+ },
78
+
79
+ async bookTurno(id, user) {
80
+ return sdk.runTransaction(async (t) => {
81
+ const ref = sdk.doc(db, name, id);
82
+ const snap = await t.get(ref);
83
+ const base = snap.exists ? normalizeTurn({ id, ...snap.data() }) : null;
84
+ const problem = bookingDecision(base, user);
85
+ if (problem) return { ok: false, error: problem };
86
+ const booked = [...base.booked, user];
87
+ await t.update(ref, { booked });
88
+ return { ok: true, turn: normalizeTurn({ ...base, booked }) };
89
+ });
90
+ },
91
+
92
+ async unbookTurno(id, user) {
93
+ const turn = await getTurn(id);
94
+ if (!turn) return { ok: false, error: 'inexistente' };
95
+ const booked = (turn.booked || []).filter((u) => u !== user);
96
+ await sdk.updateDoc(sdk.doc(db, name, id), { booked });
97
+ return { ok: true, turn: normalizeTurn({ ...turn, booked }) };
98
+ },
99
+
100
+ subscribe(cb) {
101
+ return sdk.onSnapshot(sdk.collection(db, name), (snap) => cb(docsToTurns(snap.docs)));
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,147 @@
1
+ import { bookingDecision, dayKey, normalizeTurn, uid, validateTurno } from '../core/validate.js';
2
+
3
+ /**
4
+ * Supabase (Postgres + PostgREST + realtime) adapter.
5
+ *
6
+ * No top-level `import '@supabase/supabase-js'`: the consumer's generated
7
+ * config (templates/config.turnos.supabase.js) injects the supabase client
8
+ * and the table name. That keeps `import 'turnos'` light and makes the
9
+ * adapter testable with a fake client surface.
10
+ *
11
+ * The table is snake_case (`duration_min`, `created_at`, ...) while the
12
+ * turn schema is camelCase — rows are mapped both ways in this adapter.
13
+ *
14
+ * Booking integrity: the SQL function `public.book_turno(turno_id, user)`
15
+ * (templates/sql/0001_turnos.sql) takes a row lock (`for update`) and
16
+ * enforces cancelled/duplicate/capacity server-side, returning a boolean.
17
+ * This adapter pre-checks the guards locally to surface the exact error
18
+ * code, calls the RPC as the atomic integrity point, and re-validates the
19
+ * row when the RPC declines (a concurrent book may have filled the slot).
20
+ * There is no unbook RPC: unbookTurno is a client-side update.
21
+ */
22
+
23
+ /** Padded 'YYYY-MM-DD' from a possibly-unpadded day ('2026-11-3'). */
24
+ function paddedDay(dateStr) {
25
+ const [y, m, d] = dayKey(dateStr).split('-');
26
+ return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
27
+ }
28
+
29
+ /** snake_case row -> camelCase turn (drops DB bookkeeping columns). */
30
+ function rowToTurn(row) {
31
+ const { duration_min, created_at, updated_at, ...rest } = row;
32
+ return normalizeTurn({ ...rest, durationMin: duration_min });
33
+ }
34
+
35
+ /** camelCase turn -> snake_case row payload. */
36
+ function turnToRow(turn) {
37
+ const { durationMin, ...rest } = turn;
38
+ return { ...rest, duration_min: durationMin };
39
+ }
40
+
41
+ export function createSupabaseClient(config = {}) {
42
+ const sdk = config.supabase;
43
+ if (!sdk) {
44
+ throw new Error(
45
+ 'Adaptador supabase: falta config.supabase (cliente @supabase/supabase-js) y config.table ' +
46
+ '(se generan con `npx turnos init --supabase`).',
47
+ );
48
+ }
49
+ const name = config.table || 'turnos';
50
+
51
+ async function getTurn(id) {
52
+ const { data, error } = await sdk.from(name).select('*').eq('id', id);
53
+ if (error) throw new Error(`supabase: ${error.message}`);
54
+ if (!data || data.length === 0) return null;
55
+ return rowToTurn(data[0]);
56
+ }
57
+
58
+ async function loadAll() {
59
+ const { data, error } = await sdk.from(name).select('*').order('hour');
60
+ if (error) throw new Error(`supabase: ${error.message}`);
61
+ return (data || []).map(rowToTurn);
62
+ }
63
+
64
+ return {
65
+ provider: 'supabase',
66
+
67
+ async listTurnos({ date } = {}) {
68
+ if (date) {
69
+ const { data, error } = await sdk.from(name).select('*').eq('date', paddedDay(date)).order('hour');
70
+ if (error) throw new Error(`supabase: ${error.message}`);
71
+ return (data || []).map(rowToTurn);
72
+ }
73
+ return loadAll();
74
+ },
75
+
76
+ async upsertTurno(input = {}) {
77
+ const now = new Date().toISOString();
78
+ if (input.id) {
79
+ const actual = await getTurn(input.id);
80
+ if (!actual) return { ok: false, errors: ['El turno ya no existe.'] };
81
+ const merged = { ...actual, ...input, id: actual.id };
82
+ const errors = validateTurno(merged);
83
+ if (errors.length > 0) return { ok: false, errors };
84
+ const payload = turnToRow(normalizeTurn(merged));
85
+ delete payload.id; // PostgREST: never update the primary key
86
+ payload.updated_at = now;
87
+ const { error } = await sdk.from(name).update(payload).eq('id', actual.id);
88
+ if (error) throw new Error(`supabase: ${error.message}`);
89
+ return { ok: true, turn: normalizeTurn(merged) };
90
+ }
91
+ const errors = validateTurno(input);
92
+ if (errors.length > 0) return { ok: false, errors };
93
+ const turn = normalizeTurn({ ...input, id: uid() });
94
+ const payload = { ...turnToRow(turn), created_at: now, updated_at: now };
95
+ const { error } = await sdk.from(name).insert(payload);
96
+ if (error) throw new Error(`supabase: ${error.message}`);
97
+ return { ok: true, turn };
98
+ },
99
+
100
+ async removeTurno(id) {
101
+ const { data, error } = await sdk.from(name).delete().eq('id', id).select('id');
102
+ if (error) throw new Error(`supabase: ${error.message}`);
103
+ return { ok: true, removed: (data?.length ?? 0) > 0 };
104
+ },
105
+
106
+ async bookTurno(id, user) {
107
+ const current = await getTurn(id);
108
+ if (!current) return { ok: false, error: 'inexistente' };
109
+ const early = bookingDecision(current, user);
110
+ if (early) return { ok: false, error: early };
111
+ const { data: booked, error } = await sdk.rpc('book_turno', { turno_id: id, user });
112
+ if (error) throw new Error(`supabase rpc book_turno: ${error.message}`);
113
+ if (!booked) {
114
+ // Concurrent book won the race: re-read and surface the real reason.
115
+ const fresh = await getTurn(id);
116
+ return { ok: false, error: bookingDecision(fresh, user) || 'lleno' };
117
+ }
118
+ const turn = await getTurn(id);
119
+ return { ok: true, turn };
120
+ },
121
+
122
+ async unbookTurno(id, user) {
123
+ const turn = await getTurn(id);
124
+ if (!turn) return { ok: false, error: 'inexistente' };
125
+ const booked = (turn.booked || []).filter((u) => u !== user);
126
+ const { error } = await sdk
127
+ .from(name)
128
+ .update({ booked, updated_at: new Date().toISOString() })
129
+ .eq('id', id);
130
+ if (error) throw new Error(`supabase: ${error.message}`);
131
+ return { ok: true, turn: normalizeTurn({ ...turn, booked }) };
132
+ },
133
+
134
+ subscribe(cb) {
135
+ const reload = async () => {
136
+ const turns = await loadAll();
137
+ cb(turns);
138
+ };
139
+ const channel = sdk
140
+ .channel(`turnos:${name}`)
141
+ .on('postgres_changes', { event: '*', schema: 'public', table: name }, reload);
142
+ channel.subscribe();
143
+ reload(); // initial delivery
144
+ return () => sdk.removeChannel(channel);
145
+ },
146
+ };
147
+ }
@@ -0,0 +1,32 @@
1
+ import { createMemoryClient } from './memory.js';
2
+ import { createFirebaseClient } from '../adapters/firebase.js';
3
+ import { createSupabaseClient } from '../adapters/supabase.js';
4
+
5
+ export {
6
+ validateTurno, normalizeTurn, bookingDecision,
7
+ STATUSES, PRIORITIES, todayKey, dayKey, uid,
8
+ } from './validate.js';
9
+ export { createMemoryClient } from './memory.js';
10
+ export { createFirebaseClient } from '../adapters/firebase.js';
11
+ export { createSupabaseClient } from '../adapters/supabase.js';
12
+
13
+ /**
14
+ * Provider registry. 'memory' is the built-in backend; 'firebase' and
15
+ * 'supabase' receive their SDK objects from the consumer's generated config
16
+ * file, so importing `turnos` never pulls in a heavy SDK.
17
+ */
18
+ export function createClient(config = {}) {
19
+ switch (config.provider) {
20
+ case 'memory':
21
+ case undefined:
22
+ return createMemoryClient(config);
23
+ case 'firebase':
24
+ return createFirebaseClient(config);
25
+ case 'supabase':
26
+ return createSupabaseClient(config);
27
+ default:
28
+ throw new Error(
29
+ `proveedor desconocido: "${config.provider}". Usa 'firebase', 'supabase' o 'memory'.`,
30
+ );
31
+ }
32
+ }
@@ -0,0 +1,84 @@
1
+ import { uid, dayKey, normalizeTurn, validateTurno, bookingDecision } from './validate.js';
2
+
3
+ /**
4
+ * In-memory adapter: the reference implementation of the provider-agnostic
5
+ * client contract. Pure (no localStorage/network) so it works in tests,
6
+ * SSR and as the default `createClient()` backend. Mutation semantics
7
+ * (merge upsert, timestamps) are ported from the demo app's src/store.js.
8
+ *
9
+ * Client contract implemented here:
10
+ * provider 'memory'
11
+ * listTurnos({date}) normalized turns; date filter goes through dayKey()
12
+ * upsertTurno(input) { ok, turn } | { ok: false, errors } (validation on the merge)
13
+ * removeTurno(id) { ok, removed }
14
+ * bookTurno(id, user) { ok, turn } | { ok: false, error: 'lleno'|'cancelado'|'duplicado'|'inexistente' }
15
+ * unbookTurno(id, user) { ok, turn } | { ok: false, error: 'inexistente' }
16
+ * subscribe(cb) cb(turns[]) fires immediately, then on every mutation; returns unsubscribe()
17
+ */
18
+ export function createMemoryClient(config = {}) {
19
+ const { turns: seed = [] } = config;
20
+ // Seeded turns may arrive without an id (a hand-written demo seed, a CSV
21
+ // import). Every turn needs one: it is the React key of the generated
22
+ // lists and the handle for bookTurno/upsertTurno/removeTurno.
23
+ let state = seed.map((t) => normalizeTurn({ ...t, id: t.id || uid() }));
24
+ const listeners = new Set();
25
+
26
+ function emit() {
27
+ const snapshot = state.map((t) => ({ ...t, booked: [...(t.booked || [])] }));
28
+ for (const cb of [...listeners]) cb(snapshot);
29
+ }
30
+
31
+ return {
32
+ provider: 'memory',
33
+
34
+ async listTurnos({ date } = {}) {
35
+ const all = state.map(normalizeTurn);
36
+ return date ? all.filter((t) => dayKey(t.date) === dayKey(date)) : all;
37
+ },
38
+
39
+ async upsertTurno(input) {
40
+ const idx = state.findIndex((t) => t.id === input.id);
41
+ const candidate = idx >= 0 ? { ...state[idx], ...input } : { ...input };
42
+ const errors = validateTurno(candidate);
43
+ if (errors.length > 0) return { ok: false, errors };
44
+ const now = Date.now();
45
+ const turn = normalizeTurn({ ...candidate, id: candidate.id || uid() });
46
+ const target = idx >= 0 ? idx : state.length;
47
+ if (idx >= 0) state[idx] = { ...turn, updatedAt: now };
48
+ else state.push({ ...turn, createdAt: now, updatedAt: now });
49
+ emit();
50
+ return { ok: true, turn: normalizeTurn(state[target]) };
51
+ },
52
+
53
+ async removeTurno(id) {
54
+ const before = state.length;
55
+ state = state.filter((t) => t.id !== id);
56
+ const removed = state.length < before;
57
+ if (removed) emit();
58
+ return { ok: true, removed };
59
+ },
60
+
61
+ async bookTurno(turnId, user) {
62
+ const turn = state.find((t) => t.id === turnId);
63
+ const problem = bookingDecision(turn, user);
64
+ if (problem) return { ok: false, error: problem };
65
+ turn.booked = [...(turn.booked || []), user];
66
+ emit();
67
+ return { ok: true, turn: { ...turn, booked: [...turn.booked] } };
68
+ },
69
+
70
+ async unbookTurno(turnId, user) {
71
+ const turn = state.find((t) => t.id === turnId);
72
+ if (!turn) return { ok: false, error: 'inexistente' };
73
+ turn.booked = (turn.booked || []).filter((u) => u !== user);
74
+ emit();
75
+ return { ok: true, turn: { ...turn, booked: [...turn.booked] } };
76
+ },
77
+
78
+ subscribe(cb) {
79
+ listeners.add(cb);
80
+ cb(state.map((t) => ({ ...t, booked: [...(t.booked || [])] })));
81
+ return () => listeners.delete(cb);
82
+ },
83
+ };
84
+ }