@ffstack/turnos 0.3.1 → 0.4.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,146 +1,71 @@
1
- # turnos
1
+ # @ffstack/turnos
2
2
 
3
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
4
 
5
- [![npm](https://img.shields.io/npm/v/turnos)](https://www.npmjs.com/package/turnos)
5
+ [![npm](https://img.shields.io/npm/v/@ffstack/turnos)](https://www.npmjs.com/package/@ffstack/turnos)
6
6
  [![GitHub](https://img.shields.io/badge/GitHub-Fran249%2Fturnos--react-blue)](https://github.com/Fran249/turnos-react)
7
7
 
8
- **Live repo:** <https://github.com/Fran249/turnos-react>
8
+ ## Instalación rápida (Recomendado)
9
9
 
10
- Al instalarse, `turnos` genera en tu proyecto:
10
+ Configura todo tu proyecto (componentes, base de datos y dependencias) con un solo comando:
11
+
12
+ ```bash
13
+ npx @ffstack/turnos init
14
+ ```
15
+
16
+ Este comando interactivo:
17
+ 1. Te preguntará qué base de datos quieres usar (**Firebase**, **Supabase** o **Memoria/Demo**).
18
+ 2. Generará los componentes `TurnoPicker` y `TurnoAdmin` en tu carpeta `src/turnos/`.
19
+ 3. Instalará automáticamente las dependencias necesarias (`@supabase/supabase-js`, `firebase`, etc.).
20
+ 4. Creará un archivo `.env.example` con las variables de entorno requeridas.
21
+
22
+ ---
23
+
24
+ ## Qué genera `turnos` en tu proyecto:
11
25
 
12
26
  | Archivo | Para qué |
13
27
  |---|---|
14
28
  | `src/turnos/TurnoPicker.jsx` | Componente del usuario: ve los turnos del día y elige uno |
15
29
  | `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` |
30
+ | `src/turnos/turnos.css` | Estilos autónomos: talones con perforación y registro rayado. |
31
+ | `src/turnos/turnos.config.js` | Config de tu proveedor + cliente `turnos` |
18
32
  | `firestore.rules` *(firebase)* | Reglas Firestore: lectura pública, escritura de admin |
19
33
  | `supabase-migrations/0001_turnos.sql` *(supabase)* | Tabla `public.turnos`, RLS y RPC `book_turno` atómico |
20
34
 
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
35
  ## Uso
45
36
 
46
37
  ```jsx
47
- // App del usuario
48
38
  import { turnos } from './src/turnos/turnos.config'
49
39
  import TurnoPicker from './src/turnos/TurnoPicker'
50
40
 
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
- })
41
+ function App() {
42
+ return (
43
+ <TurnoPicker
44
+ adapter={turnos}
45
+ user="id-del-usuario"
46
+ onBooked={(turn) => console.log('Turno reservado:', turn)}
47
+ />
48
+ )
49
+ }
92
50
  ```
93
51
 
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`.
52
+ ## Adaptadores y Proveedores
95
53
 
96
- ## Tema (colores y tipografía son tuyos)
54
+ - **Firebase**: Usa Firestore con transacciones para asegurar la capacidad de los turnos.
55
+ - **Supabase**: Usa Postgres con Row Level Security y funciones RPC atómicas.
56
+ - **Memoria (Demo)**: Ideal para prototipos. Permite visualizar el turnero sin base de datos, bloqueando las reservas hasta que se configure un proveedor real.
97
57
 
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.
58
+ ## Personalización (CSS)
99
59
 
100
- Sobreescribí los tokens desde tu CSS:
60
+ El componente hereda la fuente y colores de tu app por defecto. Puedes personalizarlo sobreescribiendo estos tokens:
101
61
 
102
62
  ```css
103
63
  .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;
64
+ --turnos-bg: #faf7f1;
65
+ --turnos-primary-bg: #221a12;
66
+ --turnos-accent: #3f5a2f;
67
+ --turnos-radius: 12px;
117
68
  }
118
69
  ```
119
70
 
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
- ```
71
+ Licencia MIT. Hecho por [@ffstack](https://github.com/Fran249).
package/bin/turnos.js CHANGED
@@ -8,12 +8,60 @@ import { ENV_TEMPLATES } from '../src/utils/env-templates.js';
8
8
  import fs from 'fs';
9
9
  import path from 'path';
10
10
 
11
+ const PROVIDERS = [
12
+ { name: 'firebase', value: 'firebase', label: 'Firebase (Firestore)' },
13
+ { name: 'supabase', value: 'supabase', label: 'Supabase' },
14
+ { name: 'memory', value: 'memory', label: 'Memoria (demo sin base de datos)' },
15
+ ];
16
+
17
+ const DEMO_SEED = [
18
+ {
19
+ id: 'demo-1',
20
+ title: 'Consulta médica general',
21
+ staff: 'Dr. García',
22
+ date: '2026-11-20',
23
+ hour: '09:00',
24
+ durationMin: 30,
25
+ capacity: 1,
26
+ priority: 'medium',
27
+ status: 'pending',
28
+ notes: 'Chequeo anual de rutina',
29
+ booked: [],
30
+ },
31
+ {
32
+ id: 'demo-2',
33
+ title: 'Limpieza dental',
34
+ staff: 'Dra. López',
35
+ date: '2026-11-20',
36
+ hour: '10:30',
37
+ durationMin: 45,
38
+ capacity: 1,
39
+ priority: 'low',
40
+ status: 'pending',
41
+ notes: 'Limpieza profiláctica',
42
+ booked: [],
43
+ },
44
+ {
45
+ id: 'demo-3',
46
+ title: 'Revisión de vista',
47
+ staff: 'Dr. Méndez',
48
+ date: '2026-11-20',
49
+ hour: '14:00',
50
+ durationMin: 20,
51
+ capacity: 2,
52
+ priority: 'high',
53
+ status: 'pending',
54
+ notes: 'Control de graduación',
55
+ booked: [],
56
+ },
57
+ ];
58
+
11
59
  const program = new Command();
12
60
 
13
61
  program
14
62
  .name('turnos')
15
63
  .description('CLI para instalar y configurar turnos en tu proyecto')
16
- .version('0.2.0');
64
+ .version('0.3.1');
17
65
 
18
66
  program
19
67
  .command('init')
@@ -21,27 +69,54 @@ program
21
69
  .option('-f, --force', 'Sobrescribir archivos existentes')
22
70
  .option('-d, --dir <ruta>', 'Directorio destino')
23
71
  .action(async (options) => {
24
- let { provider } = await inquirer.prompt([
72
+ const { provider } = await inquirer.prompt([
25
73
  {
26
74
  type: 'list',
27
75
  name: 'provider',
28
76
  message: '¿Qué base de datos quieres usar?',
29
- choices: ['firebase', 'supabase'],
77
+ choices: PROVIDERS,
30
78
  },
31
79
  ]);
32
80
 
81
+ const targetDir = options.dir || resolveTargetDir();
82
+
83
+ // Si es modo demo (memory), generar config con memoria y semilla de ejemplo
84
+ if (provider === 'memory') {
85
+ const res = await generateFiles({
86
+ provider: 'memory',
87
+ targetDir,
88
+ force: options.force,
89
+ demoSeed: DEMO_SEED,
90
+ });
91
+
92
+ // Generar .env.example vacío para modo demo (no hay credenciales)
93
+ fs.writeFileSync(path.join(targetDir, '.env.example'), '# Modo demo: sin credenciales necesarias');
94
+
95
+ if (res.self) {
96
+ console.log('Estás en el propio paquete "turnos".');
97
+ return;
98
+ }
99
+
100
+ res.generated.forEach((f) => console.log(` + ${f}`));
101
+ res.skipped.forEach((f) => console.log(` = ${f} (ya existía)`));
102
+ console.log(`\n✅ Modo demo activado (memoria). Los turnos se muestran pero no se pueden reservar hasta que configures Firebase o Supabase.`);
103
+ return;
104
+ }
105
+
106
+ // Firebase o Supabase: generar config real, instalar dependencias y .env
33
107
  const res = await generateFiles({
34
108
  provider,
35
- targetDir: options.dir || resolveTargetDir(),
109
+ targetDir,
36
110
  force: options.force,
37
111
  });
38
112
 
39
113
  // Automatizar instalación de dependencias
40
- const deps = provider === 'supabase' ? ['@supabase/supabase-js'] : ['firebase'];
114
+ const deps = provider === 'supabase' ? ['@supabase/supabase-js'] : provider === 'firebase' ? ['firebase'] : [];
115
+ // Siempre asegurar que el propio paquete esté instalado en el proyecto local
116
+ deps.push('@ffstack/turnos');
41
117
  installDependencies(deps);
42
118
 
43
119
  // Generar .env.example
44
- const targetDir = options.dir || resolveTargetDir();
45
120
  fs.writeFileSync(path.join(targetDir, '.env.example'), ENV_TEMPLATES[provider].trim());
46
121
  console.log(`\n + .env.example creado con configuración para ${provider}`);
47
122
 
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@ffstack/turnos",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "description": "Turnero npm: componentes usuario/admin de turnos sobre Firebase (Firestore) o Supabase, generados al instalar (npx turnos init --firebase | --supabase).",
7
+ "description": "Turnero npm: componentes usuario/admin de turnos sobre Firebase (Firestore) o Supabase, generados al instalar (npx @ffstack/turnos init).",
8
8
  "type": "module",
9
9
  "license": "MIT",
10
10
  "main": "src/core/index.js",
@@ -19,6 +19,7 @@
19
19
  "./adapters/supabase": "./src/adapters/supabase.js"
20
20
  },
21
21
  "bin": {
22
+ "@ffstack/turnos": "bin/turnos.js",
22
23
  "turnos": "bin/turnos.js"
23
24
  },
24
25
  "files": [
@@ -40,8 +41,7 @@
40
41
  "preview": "vite preview",
41
42
  "test": "vitest run",
42
43
  "test:watch": "vitest",
43
- "test:coverage": "vitest run --coverage",
44
- "postinstall": "node bin/turnos.js postinstall"
44
+ "test:coverage": "vitest run --coverage"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "react": "^18.0.0 || ^19.0.0",
@@ -16,7 +16,7 @@ import { uid, dayKey, normalizeTurn, validateTurno, bookingDecision } from './va
16
16
  * subscribe(cb) cb(turns[]) fires immediately, then on every mutation; returns unsubscribe()
17
17
  */
18
18
  export function createMemoryClient(config = {}) {
19
- const { turns: seed = [] } = config;
19
+ const { turns: seed = [], readOnly = false } = config;
20
20
  // Seeded turns may arrive without an id (a hand-written demo seed, a CSV
21
21
  // import). Every turn needs one: it is the React key of the generated
22
22
  // lists and the handle for bookTurno/upsertTurno/removeTurno.
@@ -28,8 +28,15 @@ export function createMemoryClient(config = {}) {
28
28
  for (const cb of [...listeners]) cb(snapshot);
29
29
  }
30
30
 
31
+ // When readOnly is true (demo mode, no real database configured), the
32
+ // adapter still exposes turns for visualization but refuses any write.
33
+ function denyWrite() {
34
+ return { ok: false, error: 'read-only' };
35
+ }
36
+
31
37
  return {
32
38
  provider: 'memory',
39
+ readOnly,
33
40
 
34
41
  async listTurnos({ date } = {}) {
35
42
  const all = state.map(normalizeTurn);
@@ -37,6 +44,7 @@ export function createMemoryClient(config = {}) {
37
44
  },
38
45
 
39
46
  async upsertTurno(input) {
47
+ if (readOnly) return denyWrite();
40
48
  const idx = state.findIndex((t) => t.id === input.id);
41
49
  const candidate = idx >= 0 ? { ...state[idx], ...input } : { ...input };
42
50
  const errors = validateTurno(candidate);
@@ -51,6 +59,7 @@ export function createMemoryClient(config = {}) {
51
59
  },
52
60
 
53
61
  async removeTurno(id) {
62
+ if (readOnly) return denyWrite();
54
63
  const before = state.length;
55
64
  state = state.filter((t) => t.id !== id);
56
65
  const removed = state.length < before;
@@ -59,6 +68,7 @@ export function createMemoryClient(config = {}) {
59
68
  },
60
69
 
61
70
  async bookTurno(turnId, user) {
71
+ if (readOnly) return denyWrite();
62
72
  const turn = state.find((t) => t.id === turnId);
63
73
  const problem = bookingDecision(turn, user);
64
74
  if (problem) return { ok: false, error: problem };
@@ -68,6 +78,7 @@ export function createMemoryClient(config = {}) {
68
78
  },
69
79
 
70
80
  async unbookTurno(turnId, user) {
81
+ if (readOnly) return denyWrite();
71
82
  const turn = state.find((t) => t.id === turnId);
72
83
  if (!turn) return { ok: false, error: 'inexistente' };
73
84
  turn.booked = (turn.booked || []).filter((u) => u !== user);
package/src/generator.js CHANGED
@@ -53,6 +53,7 @@ const TEMPLATE_SOURCES = {
53
53
  const CONFIG_SOURCES = {
54
54
  supabase: 'config.turnos.supabase.js',
55
55
  firebase: 'config.turnos.firebase.js',
56
+ memory: 'config.turnos.memory.js',
56
57
  };
57
58
 
58
59
  /** Extra provider artifact (schema / rules). */
@@ -71,11 +72,12 @@ export function resolveTargetDir() {
71
72
  return process.env.INIT_CWD || process.env.npm_config_local_prefix || process.cwd();
72
73
  }
73
74
 
74
- export async function generateFiles({ provider, targetDir, force = false } = {}) {
75
- if (provider !== 'supabase' && provider !== 'firebase') {
76
- throw new Error(`proveedor desconocido: "${provider}". Usa --firebase o --supabase.`);
75
+ export async function generateFiles({ provider, targetDir, force = false, demoSeed } = {}) {
76
+ if (provider !== 'supabase' && provider !== 'firebase' && provider !== 'memory') {
77
+ throw new Error(`proveedor desconocido: "${provider}". Usa --firebase, --supabase o --memory.`);
77
78
  }
78
- const targets = [...GENERATED_FILES.common, ...GENERATED_FILES[provider]];
79
+ const targets = [...GENERATED_FILES.common];
80
+ if (GENERATED_FILES[provider]) targets.push(...GENERATED_FILES[provider]);
79
81
 
80
82
  // Self guard: refuse to write artifacts into the turnos package itself
81
83
  // (e.g. `npm i` run from a git clone where package.json name === 'turnos').
@@ -94,7 +96,7 @@ export async function generateFiles({ provider, targetDir, force = false } = {})
94
96
  const srcRel =
95
97
  rel === 'src/turnos/turnos.config.js'
96
98
  ? CONFIG_SOURCES[provider]
97
- : (EXTRA_SOURCES[provider][rel] || TEMPLATE_SOURCES[rel]);
99
+ : (EXTRA_SOURCES[provider]?.[rel] || TEMPLATE_SOURCES[rel]);
98
100
  const dst = path.join(targetDir, rel);
99
101
  const exists = await fsp.access(dst).then(() => true, () => false);
100
102
  if (exists && !force) {
@@ -102,7 +104,17 @@ export async function generateFiles({ provider, targetDir, force = false } = {})
102
104
  continue;
103
105
  }
104
106
  await fsp.mkdir(path.dirname(dst), { recursive: true });
105
- const content = await fsp.readFile(path.join(TEMPLATES_DIR, srcRel), 'utf8');
107
+ let content = await fsp.readFile(path.join(TEMPLATES_DIR, srcRel), 'utf8');
108
+
109
+ // Si es modo memoria y tiene demoSeed, inyectar las turns en el config generado
110
+ if (provider === 'memory' && rel === 'src/turnos/turnos.config.js' && demoSeed) {
111
+ const seedJSON = JSON.stringify(demoSeed, null, 2);
112
+ content = content.replace(
113
+ /turns:\s*\[[\s\S]*?\],/,
114
+ `turns: ${seedJSON},`
115
+ );
116
+ }
117
+
106
118
  await fsp.writeFile(dst, content);
107
119
  generated.push(rel);
108
120
  }
@@ -46,6 +46,7 @@ function fechaBonita(iso) {
46
46
  }
47
47
 
48
48
  export default function TurnoAdmin({ adapter, titulo = 'Administrar turnos' }) {
49
+ const readOnly = adapter.readOnly === true
49
50
  const [turnos, setTurnos] = useState([])
50
51
  const [form, setForm] = useState({ ...FORM_VACIO, date: hoy() })
51
52
  const [errores, setErrores] = useState([])
@@ -59,12 +60,17 @@ export default function TurnoAdmin({ adapter, titulo = 'Administrar turnos' }) {
59
60
  }, [adapter])
60
61
 
61
62
  function cambiar(e) {
63
+ if (readOnly) return
62
64
  const { name, value } = e.target
63
65
  setForm((f) => ({ ...f, [name]: value }))
64
66
  }
65
67
 
66
68
  async function crear(e) {
67
69
  e.preventDefault()
70
+ if (readOnly) {
71
+ setAviso('Configura Firebase o Supabase para crear turnos.')
72
+ return
73
+ }
68
74
  setOcupado(true)
69
75
  setErrores([])
70
76
  setAviso('')
@@ -89,11 +95,13 @@ export default function TurnoAdmin({ adapter, titulo = 'Administrar turnos' }) {
89
95
  }
90
96
 
91
97
  async function cambiarEstado(t, status) {
98
+ if (readOnly) return
92
99
  const res = await adapter.upsertTurno({ id: t.id, status })
93
100
  if (!res.ok) setAviso(`Sin cambios en "${t.title}": ${(res.errors || []).join(' ')}`)
94
101
  }
95
102
 
96
103
  function eliminar(t) {
104
+ if (readOnly) return
97
105
  if (!window.confirm(`¿Eliminar el turno "${t.title}" (${t.date} ${t.hour})?`)) return
98
106
  adapter.removeTurno(t.id).catch(() => {})
99
107
  }
@@ -64,6 +64,7 @@ export default function TurnoPicker({ adapter, user, date, onDateChange, showDat
64
64
  const [turnos, setTurnos] = useState([])
65
65
  const [ocupado, setOcupado] = useState('')
66
66
  const [aviso, setAviso] = useState({ kind: '', text: '' })
67
+ const readOnly = adapter.readOnly === true
67
68
 
68
69
  /** Change day from inside the component and tell the host, if any. */
69
70
  function cambiarDia(next) {
@@ -84,6 +85,10 @@ export default function TurnoPicker({ adapter, user, date, onDateChange, showDat
84
85
  }, [adapter, diaSel])
85
86
 
86
87
  async function elegir(t) {
88
+ if (readOnly) {
89
+ setAviso({ kind: 'err', text: 'Configura Firebase o Supabase para reservar turnos.' })
90
+ return
91
+ }
87
92
  if (!user) {
88
93
  setAviso({ kind: 'err', text: 'Falta el identificador del usuario (prop `user`). El componente necesita saber quién reserva.' })
89
94
  return
@@ -101,6 +106,7 @@ export default function TurnoPicker({ adapter, user, date, onDateChange, showDat
101
106
  }
102
107
 
103
108
  function soltar(t) {
109
+ if (readOnly) return
104
110
  adapter
105
111
  .unbookTurno(t.id, user)
106
112
  .then((res) => {
@@ -158,10 +164,10 @@ export default function TurnoPicker({ adapter, user, date, onDateChange, showDat
158
164
  <button
159
165
  type="button"
160
166
  className="turnos-btn turnos-btn--primary"
161
- disabled={lleno || ocupado === t.id}
167
+ disabled={readOnly || lleno || ocupado === t.id}
162
168
  onClick={() => elegir(t)}
163
169
  >
164
- {lleno ? 'Completado' : 'Elegir'}
170
+ {readOnly ? 'Sin base de datos' : lleno ? 'Completado' : 'Elegir'}
165
171
  </button>
166
172
  )}
167
173
  </div>
@@ -0,0 +1,53 @@
1
+ // Generado por `npx turnos init --memory` (turnos v0.3.1).
2
+ // Modo demo sin base de datos: usa el adaptador en memoria integrado.
3
+ // Los turnos se visualizan pero NO se pueden reservar ni crear hasta que
4
+ // cambies a Firebase o Supabase.
5
+ // Para cambiar de proveedor, edita este archivo y ejecuta:
6
+ // npx turnos init --firebase (o --supabase)
7
+ import { createClient } from 'turnos'
8
+
9
+ export const turnos = createClient({
10
+ provider: 'memory',
11
+ readOnly: true,
12
+ turns: [
13
+ {
14
+ id: 'demo-1',
15
+ title: 'Consulta médica general',
16
+ staff: 'Dr. García',
17
+ date: '2026-11-20',
18
+ hour: '09:00',
19
+ durationMin: 30,
20
+ capacity: 1,
21
+ priority: 'medium',
22
+ status: 'pending',
23
+ notes: 'Chequeo anual de rutina',
24
+ booked: [],
25
+ },
26
+ {
27
+ id: 'demo-2',
28
+ title: 'Limpieza dental',
29
+ staff: 'Dra. López',
30
+ date: '2026-11-20',
31
+ hour: '10:30',
32
+ durationMin: 45,
33
+ capacity: 1,
34
+ priority: 'low',
35
+ status: 'pending',
36
+ notes: 'Limpieza profiláctica',
37
+ booked: [],
38
+ },
39
+ {
40
+ id: 'demo-3',
41
+ title: 'Revisión de vista',
42
+ staff: 'Dr. Méndez',
43
+ date: '2026-11-20',
44
+ hour: '14:00',
45
+ durationMin: 20,
46
+ capacity: 2,
47
+ priority: 'high',
48
+ status: 'pending',
49
+ notes: 'Control de graduación',
50
+ booked: [],
51
+ },
52
+ ],
53
+ })