@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 +145 -2
- package/bin/turnos.js +71 -0
- package/package.json +84 -4
- package/src/adapters/firebase.js +104 -0
- package/src/adapters/supabase.js +147 -0
- package/src/core/index.js +32 -0
- package/src/core/memory.js +84 -0
- package/src/core/validate.js +82 -0
- package/src/generator.js +111 -0
- package/src/postinstall.js +45 -0
- package/templates/TurnoAdmin.jsx +188 -0
- package/templates/TurnoPicker.jsx +180 -0
- package/templates/config.turnos.firebase.js +34 -0
- package/templates/config.turnos.supabase.js +19 -0
- package/templates/rules/firestore.rules +21 -0
- package/templates/sql/0001_turnos.sql +74 -0
- package/templates/turnos.css +363 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package-level domain rules for `turnos` (the npm turnero).
|
|
3
|
+
* Source of truth shared by every provider adapter and by the generated
|
|
4
|
+
* UI components. Error messages mirror the Spanish style of the demo
|
|
5
|
+
* app's src/store.js#validateNew so consumers see a consistent surface.
|
|
6
|
+
*/
|
|
7
|
+
export const STATUSES = ['pending', 'confirmed', 'completed', 'cancelled'];
|
|
8
|
+
export const PRIORITIES = ['low', 'medium', 'high'];
|
|
9
|
+
|
|
10
|
+
export function uid() {
|
|
11
|
+
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Padded ISO today, e.g. `2026-11-11`. */
|
|
15
|
+
export function todayKey() {
|
|
16
|
+
const d = new Date();
|
|
17
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Unpadded date key (`2026-11-03` -> `2026-11-3`). Providers store padded
|
|
22
|
+
* dates while UI calendars may emit unpadded keys — every date comparison
|
|
23
|
+
* must normalize both sides through dayKey() (same fix as ScheduleView).
|
|
24
|
+
*/
|
|
25
|
+
export function dayKey(dateStr) {
|
|
26
|
+
const [y, m, d] = String(dateStr || '').split('-').map(Number);
|
|
27
|
+
return [y, m, d].join('-');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Shared booking semantics across providers. Returns null when bookable. */
|
|
31
|
+
export function bookingDecision(turn, user) {
|
|
32
|
+
if (!turn) return 'inexistente';
|
|
33
|
+
if (turn.status === 'cancelled') return 'cancelado';
|
|
34
|
+
const booked = turn.booked || [];
|
|
35
|
+
if (booked.includes(user)) return 'duplicado';
|
|
36
|
+
if (booked.length >= (turn.capacity ?? 1)) return 'lleno';
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Fill defaults without mutating the input. */
|
|
41
|
+
export function normalizeTurn(raw) {
|
|
42
|
+
const t = { ...raw };
|
|
43
|
+
t.capacity = t.capacity ?? 1;
|
|
44
|
+
t.booked = Array.isArray(t.booked) ? [...t.booked] : [];
|
|
45
|
+
if (t.status === undefined) t.status = 'pending';
|
|
46
|
+
if (t.durationMin === undefined || t.durationMin === null || t.durationMin === '') t.durationMin = 30;
|
|
47
|
+
if (t.priority === undefined) t.priority = 'medium';
|
|
48
|
+
if (t.notes === undefined) t.notes = '';
|
|
49
|
+
return t;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validate a turn to be created or updated. Returns a list of error strings
|
|
54
|
+
* (empty = valid). Absent optional fields are not errors — they get
|
|
55
|
+
* defaults in normalizeTurn().
|
|
56
|
+
*/
|
|
57
|
+
export function validateTurno(input) {
|
|
58
|
+
const errors = [];
|
|
59
|
+
if (!input.title || !input.title.trim()) errors.push('El título es obligatorio.');
|
|
60
|
+
if (!input.staff || !input.staff.trim()) errors.push('El personal es obligatorio.');
|
|
61
|
+
const [h, m] = String(input.hour ?? '').split(':').map(Number);
|
|
62
|
+
if (!input.hour || Number.isNaN(h) || h < 0 || h > 23 || Number.isNaN(m) || m < 0 || m > 59) {
|
|
63
|
+
errors.push('La hora debe ser HH:MM.');
|
|
64
|
+
}
|
|
65
|
+
if (input.durationMin !== undefined && input.durationMin !== null && input.durationMin !== '' &&
|
|
66
|
+
(Number.isNaN(input.durationMin) || input.durationMin < 10)) {
|
|
67
|
+
errors.push('La duración debe ser ≥ 10 min.');
|
|
68
|
+
}
|
|
69
|
+
if (input.priority !== undefined && !PRIORITIES.includes(input.priority)) {
|
|
70
|
+
errors.push('Prioridad inválida.');
|
|
71
|
+
}
|
|
72
|
+
if (input.status !== undefined && !STATUSES.includes(input.status)) {
|
|
73
|
+
errors.push('Estado inválido.');
|
|
74
|
+
}
|
|
75
|
+
if (!input.date || !/^\d{4}-\d{2}-\d{2}$/.test(input.date)) {
|
|
76
|
+
errors.push('La fecha debe ser YYYY-MM-DD.');
|
|
77
|
+
}
|
|
78
|
+
if (input.capacity !== undefined && (!Number.isInteger(input.capacity) || input.capacity < 1)) {
|
|
79
|
+
errors.push('La capacidad debe ser un entero ≥ 1.');
|
|
80
|
+
}
|
|
81
|
+
return errors;
|
|
82
|
+
}
|
package/src/generator.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { promises as fsp } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Install-time generator: creates the consumer-side artifacts of `turnos`
|
|
7
|
+
* (user component, admin component, provider config, design css, provider
|
|
8
|
+
* schema). Invoked from `bin/turnos.js` (init | postinstall).
|
|
9
|
+
*
|
|
10
|
+
* Templates live in <pkg>/templates/ — copied, never templated: the
|
|
11
|
+
* provider-specific config is chosen wholesale by provider so consumers
|
|
12
|
+
* never mix Firebase and Supabase code.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Where the templates live. Real node runtime (CLI/postinstall): the module
|
|
16
|
+
* URL is `file:`. Under Vite/vitest the URL is virtual (`http://localhost`),
|
|
17
|
+
* so fall back to <cwd>/templates — vitest is always run from the package
|
|
18
|
+
* root.
|
|
19
|
+
*/
|
|
20
|
+
function resolveTemplatesDir() {
|
|
21
|
+
try {
|
|
22
|
+
if (new URL(import.meta.url).protocol === 'file:') {
|
|
23
|
+
return fileURLToPath(new URL('../templates/', import.meta.url));
|
|
24
|
+
}
|
|
25
|
+
} catch {
|
|
26
|
+
/* not a parseable module URL: use the cwd fallback */
|
|
27
|
+
}
|
|
28
|
+
return path.resolve(process.cwd(), 'templates');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const TEMPLATES_DIR = resolveTemplatesDir();
|
|
32
|
+
|
|
33
|
+
/** Consumer-relative paths created by a single init. */
|
|
34
|
+
export const GENERATED_FILES = {
|
|
35
|
+
common: [
|
|
36
|
+
'src/turnos/TurnoPicker.jsx',
|
|
37
|
+
'src/turnos/TurnoAdmin.jsx',
|
|
38
|
+
'src/turnos/turnos.css',
|
|
39
|
+
'src/turnos/turnos.config.js',
|
|
40
|
+
],
|
|
41
|
+
firebase: ['firestore.rules'],
|
|
42
|
+
supabase: ['supabase-migrations/0001_turnos.sql'],
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** target -> template source, for the provider-agnostic files. */
|
|
46
|
+
const TEMPLATE_SOURCES = {
|
|
47
|
+
'src/turnos/TurnoPicker.jsx': 'TurnoPicker.jsx',
|
|
48
|
+
'src/turnos/TurnoAdmin.jsx': 'TurnoAdmin.jsx',
|
|
49
|
+
'src/turnos/turnos.css': 'turnos.css',
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** One config file per provider, written to the same consumer path. */
|
|
53
|
+
const CONFIG_SOURCES = {
|
|
54
|
+
supabase: 'config.turnos.supabase.js',
|
|
55
|
+
firebase: 'config.turnos.firebase.js',
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Extra provider artifact (schema / rules). */
|
|
59
|
+
const EXTRA_SOURCES = {
|
|
60
|
+
supabase: { 'supabase-migrations/0001_turnos.sql': 'sql/0001_turnos.sql' },
|
|
61
|
+
firebase: { 'firestore.rules': 'rules/firestore.rules' },
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Where does a consumer's project root live when npm runs postinstall?
|
|
66
|
+
* INIT_CWD is the directory the user typed the install in;
|
|
67
|
+
* npm_config_local_prefix is the package root under install;
|
|
68
|
+
* bare node falls back to cwd (dev + tests).
|
|
69
|
+
*/
|
|
70
|
+
export function resolveTargetDir() {
|
|
71
|
+
return process.env.INIT_CWD || process.env.npm_config_local_prefix || process.cwd();
|
|
72
|
+
}
|
|
73
|
+
|
|
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.`);
|
|
77
|
+
}
|
|
78
|
+
const targets = [...GENERATED_FILES.common, ...GENERATED_FILES[provider]];
|
|
79
|
+
|
|
80
|
+
// Self guard: refuse to write artifacts into the turnos package itself
|
|
81
|
+
// (e.g. `npm i` run from a git clone where package.json name === 'turnos').
|
|
82
|
+
try {
|
|
83
|
+
const pkg = JSON.parse(await fsp.readFile(path.join(targetDir, 'package.json'), 'utf8'));
|
|
84
|
+
if (pkg.name === 'turnos') {
|
|
85
|
+
return { self: true, generated: [], skipped: [], provider, targetDir };
|
|
86
|
+
}
|
|
87
|
+
} catch {
|
|
88
|
+
/* no package.json (scratch dir in tests): proceed */
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const generated = [];
|
|
92
|
+
const skipped = [];
|
|
93
|
+
for (const rel of targets) {
|
|
94
|
+
const srcRel =
|
|
95
|
+
rel === 'src/turnos/turnos.config.js'
|
|
96
|
+
? CONFIG_SOURCES[provider]
|
|
97
|
+
: (EXTRA_SOURCES[provider][rel] || TEMPLATE_SOURCES[rel]);
|
|
98
|
+
const dst = path.join(targetDir, rel);
|
|
99
|
+
const exists = await fsp.access(dst).then(() => true, () => false);
|
|
100
|
+
if (exists && !force) {
|
|
101
|
+
skipped.push(rel);
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
|
105
|
+
const content = await fsp.readFile(path.join(TEMPLATES_DIR, srcRel), 'utf8');
|
|
106
|
+
await fsp.writeFile(dst, content);
|
|
107
|
+
generated.push(rel);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return { self: false, generated, skipped, provider, targetDir };
|
|
111
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { generateFiles, resolveTargetDir } from './generator.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* npm `postinstall` entry. npm never forwards unknown CLI flags to
|
|
5
|
+
* postinstall, so the provider arrives via the environment:
|
|
6
|
+
* TURNOS_PROVIDER=firebase npm i turnos
|
|
7
|
+
* The hook is STRICTLY WARN-ONLY: whatever happens it returns a status
|
|
8
|
+
* string and never throws — a broken postinstall would break `npm i`
|
|
9
|
+
* in every consumer project.
|
|
10
|
+
*/
|
|
11
|
+
export function resolveProvider(env = process.env) {
|
|
12
|
+
const p = String(env.TURNOS_PROVIDER || '').toLowerCase();
|
|
13
|
+
return p === 'firebase' || p === 'supabase' ? p : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function runPostinstall({
|
|
17
|
+
env = process.env,
|
|
18
|
+
targetDir,
|
|
19
|
+
log = console.log,
|
|
20
|
+
gen = generateFiles,
|
|
21
|
+
} = {}) {
|
|
22
|
+
const dir = targetDir || resolveTargetDir();
|
|
23
|
+
const provider = resolveProvider(env);
|
|
24
|
+
|
|
25
|
+
if (!provider) {
|
|
26
|
+
log('turnos: no se detectó TURNOS_PROVIDER. Para generar los componentes:');
|
|
27
|
+
log(' npx turnos init --firebase # Firestore');
|
|
28
|
+
log(' npx turnos init --supabase # Supabase');
|
|
29
|
+
return 'guidance';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const res = await gen({ provider, targetDir: dir });
|
|
34
|
+
if (res.self) {
|
|
35
|
+
log('turnos: postinstall descartado (contexto del propio paquete "turnos").');
|
|
36
|
+
return 'skipped';
|
|
37
|
+
}
|
|
38
|
+
log(`turnos: archivos generados para ${provider}: ${res.generated.join(', ') || 'ninguno (ya existían)'}`);
|
|
39
|
+
if (res.skipped.length > 0) log(`turnos: omitidos porque ya existían: ${res.skipped.join(', ')}`);
|
|
40
|
+
return 'generated';
|
|
41
|
+
} catch (err) {
|
|
42
|
+
log(`turnos: no se pudieron generar los archivos (${err.message}). Ejecuta: npx turnos init --${provider}`);
|
|
43
|
+
return 'error';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react'
|
|
2
|
+
import './turnos.css'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* TurnoAdmin — el administrador controla los turnos: crea, cambia su
|
|
6
|
+
* estado y elimina. Generado por `npx turnos init` (turnos v0.1.0).
|
|
7
|
+
*
|
|
8
|
+
* Uso:
|
|
9
|
+
* import { turnos } from './turnos/turnos.config'
|
|
10
|
+
* import TurnoAdmin from './turnos/TurnoAdmin'
|
|
11
|
+
* <TurnoAdmin adapter={turnos} />
|
|
12
|
+
*
|
|
13
|
+
* Props:
|
|
14
|
+
* - adapter: cliente `turnos` (el que exporta turnos.config.js).
|
|
15
|
+
* - titulo?: texto del encabezado (default 'Administrar turnos').
|
|
16
|
+
*
|
|
17
|
+
* Funciona con el adaptador que sea (Firebase, Supabase o 'memory'):
|
|
18
|
+
* solo usa upsertTurno / removeTurno / subscribe del contrato.
|
|
19
|
+
*/
|
|
20
|
+
const ESTADOS = [
|
|
21
|
+
['pending', 'Pendiente'],
|
|
22
|
+
['confirmed', 'Confirmado'],
|
|
23
|
+
['completed', 'Completado'],
|
|
24
|
+
['cancelled', 'Cancelado'],
|
|
25
|
+
]
|
|
26
|
+
const PRIORIDADES = [
|
|
27
|
+
['low', 'Baja'],
|
|
28
|
+
['medium', 'Media'],
|
|
29
|
+
['high', 'Alta'],
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
const FORM_VACIO = {
|
|
33
|
+
title: '', staff: '', date: '', hour: '', durationMin: '', capacity: '', priority: 'medium', notes: '',
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function hoy() {
|
|
37
|
+
const d = new Date()
|
|
38
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** '2026-11-11' → 'Lunes, 11 de noviembre' (fecha local, sin salto UTC). */
|
|
42
|
+
function fechaBonita(iso) {
|
|
43
|
+
const [y, m, d] = String(iso).split('-').map(Number)
|
|
44
|
+
const texto = new Date(y, m - 1, d).toLocaleDateString('es', { weekday: 'long', day: 'numeric', month: 'long' })
|
|
45
|
+
return texto.charAt(0).toUpperCase() + texto.slice(1)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export default function TurnoAdmin({ adapter, titulo = 'Administrar turnos' }) {
|
|
49
|
+
const [turnos, setTurnos] = useState([])
|
|
50
|
+
const [form, setForm] = useState({ ...FORM_VACIO, date: hoy() })
|
|
51
|
+
const [errores, setErrores] = useState([])
|
|
52
|
+
const [aviso, setAviso] = useState('')
|
|
53
|
+
const [ocupado, setOcupado] = useState(false)
|
|
54
|
+
|
|
55
|
+
useEffect(() => {
|
|
56
|
+
const ordenar = (ts) => [...ts].sort((a, b) => a.date.localeCompare(b.date) || a.hour.localeCompare(b.hour))
|
|
57
|
+
const un = adapter.subscribe((ts) => setTurnos(ordenar(ts)))
|
|
58
|
+
return un
|
|
59
|
+
}, [adapter])
|
|
60
|
+
|
|
61
|
+
function cambiar(e) {
|
|
62
|
+
const { name, value } = e.target
|
|
63
|
+
setForm((f) => ({ ...f, [name]: value }))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function crear(e) {
|
|
67
|
+
e.preventDefault()
|
|
68
|
+
setOcupado(true)
|
|
69
|
+
setErrores([])
|
|
70
|
+
setAviso('')
|
|
71
|
+
const res = await adapter.upsertTurno({
|
|
72
|
+
title: form.title,
|
|
73
|
+
staff: form.staff,
|
|
74
|
+
date: form.date,
|
|
75
|
+
hour: form.hour,
|
|
76
|
+
durationMin: form.durationMin ? Number(form.durationMin) : undefined,
|
|
77
|
+
capacity: form.capacity ? Number(form.capacity) : undefined,
|
|
78
|
+
priority: form.priority,
|
|
79
|
+
status: 'pending',
|
|
80
|
+
notes: form.notes,
|
|
81
|
+
})
|
|
82
|
+
if (res.ok) {
|
|
83
|
+
setForm({ ...FORM_VACIO, date: hoy() })
|
|
84
|
+
setAviso('Turno creado.')
|
|
85
|
+
} else {
|
|
86
|
+
setErrores(res.errors || ['No se pudo crear el turno.'])
|
|
87
|
+
}
|
|
88
|
+
setOcupado(false)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function cambiarEstado(t, status) {
|
|
92
|
+
const res = await adapter.upsertTurno({ id: t.id, status })
|
|
93
|
+
if (!res.ok) setAviso(`Sin cambios en "${t.title}": ${(res.errors || []).join(' ')}`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function eliminar(t) {
|
|
97
|
+
if (!window.confirm(`¿Eliminar el turno "${t.title}" (${t.date} ${t.hour})?`)) return
|
|
98
|
+
adapter.removeTurno(t.id).catch(() => {})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// turnos ya vienen ordenados por fecha + hora; agrupa por fecha (días vacíos fuera)
|
|
102
|
+
const grupos = [...new Set(turnos.map((t) => t.date))]
|
|
103
|
+
.map((f) => [f, turnos.filter((t) => t.date === f)])
|
|
104
|
+
.filter(([, ts]) => ts.length > 0)
|
|
105
|
+
|
|
106
|
+
return (
|
|
107
|
+
<section className="turnos" data-testid="turno-admin">
|
|
108
|
+
<div className="turnos-cabecera">
|
|
109
|
+
<h2 className="turnos-titulo">{titulo}</h2>
|
|
110
|
+
<span className="turnos-cupo">{turnos.length} turnos</span>
|
|
111
|
+
</div>
|
|
112
|
+
|
|
113
|
+
<form className="turnos-form" onSubmit={crear}>
|
|
114
|
+
<label className="turnos-f-titulo">Título
|
|
115
|
+
<input name="title" value={form.title} onChange={cambiar} placeholder="Título *" />
|
|
116
|
+
</label>
|
|
117
|
+
<label className="turnos-f-staff">Personal
|
|
118
|
+
<input name="staff" value={form.staff} onChange={cambiar} placeholder="Equipo B *" />
|
|
119
|
+
</label>
|
|
120
|
+
<label className="turnos-f-fecha">Fecha
|
|
121
|
+
<input type="date" name="date" value={form.date} onChange={cambiar} />
|
|
122
|
+
</label>
|
|
123
|
+
<label className="turnos-f-hora">Hora
|
|
124
|
+
<input name="hour" value={form.hour} onChange={cambiar} placeholder="HH:MM *" />
|
|
125
|
+
</label>
|
|
126
|
+
<label className="turnos-f-duracion">Duración (min)
|
|
127
|
+
<input type="number" min="10" name="durationMin" value={form.durationMin} onChange={cambiar} placeholder="30" />
|
|
128
|
+
</label>
|
|
129
|
+
<label className="turnos-f-capacidad">Capacidad
|
|
130
|
+
<input type="number" min="1" name="capacity" value={form.capacity} onChange={cambiar} placeholder="1" />
|
|
131
|
+
</label>
|
|
132
|
+
<label className="turnos-f-prioridad">Prioridad
|
|
133
|
+
<select name="priority" value={form.priority} onChange={cambiar}>
|
|
134
|
+
{PRIORIDADES.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
|
135
|
+
</select>
|
|
136
|
+
</label>
|
|
137
|
+
<label className="turnos-f-notas">Notas
|
|
138
|
+
<input name="notes" value={form.notes} onChange={cambiar} placeholder="Opcional" />
|
|
139
|
+
</label>
|
|
140
|
+
<button type="submit" className="turnos-btn turnos-btn--primary" disabled={ocupado}>Crear turno</button>
|
|
141
|
+
</form>
|
|
142
|
+
|
|
143
|
+
{errores.length > 0 && (
|
|
144
|
+
<ul className="turnos-error-lista" role="alert">
|
|
145
|
+
{errores.map((er) => <li key={er}>{er}</li>)}
|
|
146
|
+
</ul>
|
|
147
|
+
)}
|
|
148
|
+
{aviso && <p className="turnos-aviso turnos-aviso--ok" role="status">{aviso}</p>}
|
|
149
|
+
|
|
150
|
+
{turnos.length === 0 ? (
|
|
151
|
+
<p className="turnos-vacio">Sin turnos todavía. Crea el primero arriba.</p>
|
|
152
|
+
) : (
|
|
153
|
+
<div>
|
|
154
|
+
{grupos.map(([fecha, ts]) => (
|
|
155
|
+
<div key={fecha} className="turnos-franja-grupo">
|
|
156
|
+
<p className="turnos-franja">{fechaBonita(fecha)}</p>
|
|
157
|
+
<ul className="turnos-lista">
|
|
158
|
+
{ts.map((t) => (
|
|
159
|
+
<li key={t.id} className="turnos-fila">
|
|
160
|
+
<span className="turnos-fecha">{t.date}</span>
|
|
161
|
+
<span className="turnos-hora">{t.hour}</span>
|
|
162
|
+
<div className="turnos-cuerpo">
|
|
163
|
+
<strong>{t.title}</strong>
|
|
164
|
+
<span className="turnos-bajito">{t.staff}</span>
|
|
165
|
+
<span className="turnos-bajito">{t.booked?.length ?? 0}/{t.capacity ?? 1} elegidos</span>
|
|
166
|
+
</div>
|
|
167
|
+
<span className={`turnos-prio turnos-prio--${t.priority}`}>
|
|
168
|
+
{PRIORIDADES.find(([v]) => v === t.priority)?.[1] || t.priority}
|
|
169
|
+
</span>
|
|
170
|
+
<select
|
|
171
|
+
className="turnos-estado"
|
|
172
|
+
value={t.status}
|
|
173
|
+
onChange={(e) => cambiarEstado(t, e.target.value)}
|
|
174
|
+
aria-label={`Estado de ${t.title}`}
|
|
175
|
+
>
|
|
176
|
+
{ESTADOS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
|
177
|
+
</select>
|
|
178
|
+
<button type="button" className="turnos-btn turnos-btn--danger" onClick={() => eliminar(t)}>Eliminar</button>
|
|
179
|
+
</li>
|
|
180
|
+
))}
|
|
181
|
+
</ul>
|
|
182
|
+
</div>
|
|
183
|
+
))}
|
|
184
|
+
</div>
|
|
185
|
+
)}
|
|
186
|
+
</section>
|
|
187
|
+
)
|
|
188
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react'
|
|
2
|
+
import './turnos.css'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* TurnoPicker — el usuario ve los turnos de un día y elige uno.
|
|
6
|
+
* Generado por `npx turnos init` (turnos v0.1.0).
|
|
7
|
+
*
|
|
8
|
+
* Uso:
|
|
9
|
+
* import { turnos } from './turnos/turnos.config'
|
|
10
|
+
* import TurnoPicker from './turnos/TurnoPicker'
|
|
11
|
+
* <TurnoPicker adapter={turnos} user="Elsil" />
|
|
12
|
+
*
|
|
13
|
+
* Props:
|
|
14
|
+
* - adapter: cliente `turnos` (el que exporta turnos.config.js).
|
|
15
|
+
* - user: identificador (nombre, email, uid…) que se registra en `booked`.
|
|
16
|
+
* - date?: fecha inicial 'YYYY-MM-DD' (default: hoy). Si el anfitrión controla
|
|
17
|
+
* la fecha (tira semanal, calendario), pasale una `key={date}` para que el
|
|
18
|
+
* componente se remonte al día nuevo y arranque en esa fecha.
|
|
19
|
+
* - onDateChange?: (date) => void se llama cuando el usuario cambia de día
|
|
20
|
+
* con el navegador propio del componente.
|
|
21
|
+
* - showDateNav?: boolean (default true). Ponlo en `false` cuando la fecha
|
|
22
|
+
* la controla el anfitrión (tira semanal, calendario) para no duplicar
|
|
23
|
+
* los controles de día.
|
|
24
|
+
* - onBooked?: (turn) => void / onUnbooked?: (turn) => void
|
|
25
|
+
*
|
|
26
|
+
* El componente es autónomo: solo consume el contrato del cliente
|
|
27
|
+
* (listTurnos/bookTurno/unbookTurno/subscribe), así que funciona igual
|
|
28
|
+
* con Firebase, Supabase o el adaptador 'memory'.
|
|
29
|
+
*/
|
|
30
|
+
const ETIQUETA_ESTADO = { pending: 'Pendiente', confirmed: 'Confirmado', completed: 'Completado', cancelled: 'Cancelado' }
|
|
31
|
+
const MENSAJE_ERROR = {
|
|
32
|
+
lleno: 'El turno está completo.',
|
|
33
|
+
cancelado: 'Este turno fue cancelado.',
|
|
34
|
+
duplicado: 'Ya elegiste este turno.',
|
|
35
|
+
inexistente: 'El turno ya no existe.',
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function hoy() {
|
|
39
|
+
const d = new Date()
|
|
40
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Llave de día sin padding ('2026-01-02' y '2026-1-2' son el mismo día). */
|
|
44
|
+
function dia(d) {
|
|
45
|
+
return String(d || '').split('-').map(Number).join('-')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function sumarDias(diaIso, delta) {
|
|
49
|
+
const [y, m, dd] = diaIso.split('-').map(Number)
|
|
50
|
+
const f = new Date(y, m - 1, dd + delta)
|
|
51
|
+
return `${f.getFullYear()}-${String(f.getMonth() + 1).padStart(2, '0')}-${String(f.getDate()).padStart(2, '0')}`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const FRANJAS = ['Mañana', 'Tarde', 'Noche']
|
|
55
|
+
|
|
56
|
+
/** Franja de la hora: Mañana 00–11 h, Tarde 12–17 h, Noche 18–23 h. */
|
|
57
|
+
function franjaDe(hour) {
|
|
58
|
+
const h = Number(String(hour || '00:00').slice(0, 2))
|
|
59
|
+
return h < 12 ? 'Mañana' : h < 18 ? 'Tarde' : 'Noche'
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export default function TurnoPicker({ adapter, user, date, onDateChange, showDateNav = true, onBooked, onUnbooked }) {
|
|
63
|
+
const [diaSel, setDiaSel] = useState(date || hoy())
|
|
64
|
+
const [turnos, setTurnos] = useState([])
|
|
65
|
+
const [ocupado, setOcupado] = useState('')
|
|
66
|
+
const [aviso, setAviso] = useState({ kind: '', text: '' })
|
|
67
|
+
|
|
68
|
+
/** Change day from inside the component and tell the host, if any. */
|
|
69
|
+
function cambiarDia(next) {
|
|
70
|
+
setDiaSel(next)
|
|
71
|
+
onDateChange?.(next)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
let vivo = true
|
|
76
|
+
const refrescar = () => {
|
|
77
|
+
adapter.listTurnos({ date: diaSel }).then((ts) => vivo && setTurnos(ts)).catch(() => {})
|
|
78
|
+
}
|
|
79
|
+
refrescar()
|
|
80
|
+
const un = adapter.subscribe((ts) => {
|
|
81
|
+
if (vivo) setTurnos(ts.filter((t) => dia(t.date) === dia(diaSel)))
|
|
82
|
+
})
|
|
83
|
+
return () => { vivo = false; un() }
|
|
84
|
+
}, [adapter, diaSel])
|
|
85
|
+
|
|
86
|
+
async function elegir(t) {
|
|
87
|
+
if (!user) {
|
|
88
|
+
setAviso({ kind: 'err', text: 'Falta el identificador del usuario (prop `user`). El componente necesita saber quién reserva.' })
|
|
89
|
+
return
|
|
90
|
+
}
|
|
91
|
+
setOcupado(t.id)
|
|
92
|
+
setAviso({ kind: '', text: '' })
|
|
93
|
+
const res = await adapter.bookTurno(t.id, user)
|
|
94
|
+
if (res.ok) {
|
|
95
|
+
setAviso({ kind: 'ok', text: `¡Listo! Turno elegido: ${t.title}.` })
|
|
96
|
+
onBooked?.(res.turn)
|
|
97
|
+
} else {
|
|
98
|
+
setAviso({ kind: 'err', text: MENSAJE_ERROR[res.error] || 'No se pudo elegir el turno.' })
|
|
99
|
+
}
|
|
100
|
+
setOcupado('')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function soltar(t) {
|
|
104
|
+
adapter
|
|
105
|
+
.unbookTurno(t.id, user)
|
|
106
|
+
.then((res) => {
|
|
107
|
+
if (res.ok) onUnbooked?.(res.turn)
|
|
108
|
+
})
|
|
109
|
+
.catch(() => {})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const ordenados = [...turnos].sort((a, b) => a.hour.localeCompare(b.hour))
|
|
113
|
+
const porFranja = FRANJAS.map((f) => [f, ordenados.filter((t) => franjaDe(t.hour) === f)]).filter(([, ts]) => ts.length > 0)
|
|
114
|
+
|
|
115
|
+
return (
|
|
116
|
+
<section className="turnos" data-testid="turno-picker">
|
|
117
|
+
<div className="turnos-cabecera">
|
|
118
|
+
<h2 className="turnos-titulo">Elegir turno</h2>
|
|
119
|
+
{showDateNav && (
|
|
120
|
+
<div className="turnos-nav">
|
|
121
|
+
<button type="button" className="turnos-btn" onClick={() => cambiarDia(sumarDias(diaSel, -1))} aria-label="Día anterior">‹</button>
|
|
122
|
+
<input type="date" className="turnos-campo" value={diaSel} onChange={(e) => cambiarDia(e.target.value)} aria-label="Fecha" />
|
|
123
|
+
<button type="button" className="turnos-btn" onClick={() => cambiarDia(sumarDias(diaSel, 1))} aria-label="Día siguiente">›</button>
|
|
124
|
+
</div>
|
|
125
|
+
)}
|
|
126
|
+
</div>
|
|
127
|
+
|
|
128
|
+
{ordenados.length === 0 ? (
|
|
129
|
+
<p className="turnos-vacio">No hay turnos para este día.</p>
|
|
130
|
+
) : (
|
|
131
|
+
<div>
|
|
132
|
+
{porFranja.map(([nombre, ts]) => (
|
|
133
|
+
<div key={nombre} className="turnos-franja-grupo">
|
|
134
|
+
<p className="turnos-franja">{nombre}</p>
|
|
135
|
+
<ul className="turnos-lista">
|
|
136
|
+
{ts.map((t) => {
|
|
137
|
+
const elegido = (t.booked || []).includes(user)
|
|
138
|
+
const lleno = !elegido && (t.booked?.length ?? 0) >= (t.capacity ?? 1)
|
|
139
|
+
const cancelado = t.status === 'cancelled'
|
|
140
|
+
return (
|
|
141
|
+
<li key={t.id} className={`turnos-talon ${cancelado ? 'turnos-talon--cancelada' : ''}`}>
|
|
142
|
+
<div className="turnos-talon-hora">
|
|
143
|
+
<span className="turnos-hora">{t.hour}</span>
|
|
144
|
+
<span className="turnos-dur">+{t.durationMin} min</span>
|
|
145
|
+
</div>
|
|
146
|
+
<div className="turnos-talon-datos">
|
|
147
|
+
<strong className="turnos-talon-titulo">{t.title}</strong>
|
|
148
|
+
<span className="turnos-bajito">{t.staff}</span>
|
|
149
|
+
</div>
|
|
150
|
+
<span className={`turnos-sello turnos-sello--${t.status}`}>{ETIQUETA_ESTADO[t.status] || t.status}</span>
|
|
151
|
+
<span className="turnos-cupo">{t.booked?.length ?? 0}/{t.capacity ?? 1} elegidos</span>
|
|
152
|
+
<div className="turnos-talon-accion">
|
|
153
|
+
{cancelado ? (
|
|
154
|
+
<button type="button" className="turnos-btn" disabled>Cancelado</button>
|
|
155
|
+
) : elegido ? (
|
|
156
|
+
<button type="button" className="turnos-btn turnos-btn--soft" disabled={ocupado === t.id} onClick={() => soltar(t)}>Quitar</button>
|
|
157
|
+
) : (
|
|
158
|
+
<button
|
|
159
|
+
type="button"
|
|
160
|
+
className="turnos-btn turnos-btn--primary"
|
|
161
|
+
disabled={lleno || ocupado === t.id}
|
|
162
|
+
onClick={() => elegir(t)}
|
|
163
|
+
>
|
|
164
|
+
{lleno ? 'Completado' : 'Elegir'}
|
|
165
|
+
</button>
|
|
166
|
+
)}
|
|
167
|
+
</div>
|
|
168
|
+
</li>
|
|
169
|
+
)
|
|
170
|
+
})}
|
|
171
|
+
</ul>
|
|
172
|
+
</div>
|
|
173
|
+
))}
|
|
174
|
+
</div>
|
|
175
|
+
)}
|
|
176
|
+
|
|
177
|
+
{aviso.text && <p className={`turnos-aviso turnos-aviso--${aviso.kind}`} role="status">{aviso.text}</p>}
|
|
178
|
+
</section>
|
|
179
|
+
)
|
|
180
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Generado por `npx turnos init --firebase` (turnos v0.1.0).
|
|
2
|
+
// 1) Instala: npm i firebase
|
|
3
|
+
// 2) Reemplaza la config por la de TU proyecto (Firebase console →
|
|
4
|
+
// Project settings → Your apps). NUNCA subas credenciales reales al repo:
|
|
5
|
+
// para apps públicas usa solo las keys web (apiKey/appId).
|
|
6
|
+
// 3) Publica las reglas: firebase deploy --only firestore:rules
|
|
7
|
+
import { initializeApp } from 'firebase/app'
|
|
8
|
+
import {
|
|
9
|
+
getFirestore,
|
|
10
|
+
collection, getDocs, getDoc, query, where, onSnapshot,
|
|
11
|
+
doc, deleteDoc, setDoc, updateDoc, runTransaction,
|
|
12
|
+
} from 'firebase/firestore'
|
|
13
|
+
import { createClient } from 'turnos'
|
|
14
|
+
|
|
15
|
+
const app = initializeApp({
|
|
16
|
+
apiKey: 'TU_API_KEY',
|
|
17
|
+
authDomain: 'TU_PROYECTO.firebaseapp.com',
|
|
18
|
+
projectId: 'TU_PROYECTO',
|
|
19
|
+
storageBucket: 'TU_PROYECTO.appspot.com',
|
|
20
|
+
appId: 'TU_APP_ID',
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
// Cliente del paquete `turnos` — mismo contrato para todos los proveedores:
|
|
24
|
+
// listTurnos / upsertTurno / removeTurno / bookTurno / unbookTurno / subscribe
|
|
25
|
+
export const turnos = createClient({
|
|
26
|
+
provider: 'firebase',
|
|
27
|
+
firebase: {
|
|
28
|
+
db: getFirestore(app),
|
|
29
|
+
// El paquete `turnos` no empaqueta el SDK: el config generado inyecta
|
|
30
|
+
// las funciones de Firestore para que el adaptador no dependa de nada.
|
|
31
|
+
sdk: { collection, getDocs, getDoc, query, where, onSnapshot, doc, deleteDoc, setDoc, updateDoc, runTransaction },
|
|
32
|
+
collectionName: 'turnos',
|
|
33
|
+
},
|
|
34
|
+
})
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Generado por `npx turnos init --supabase` (turnos v0.1.0).
|
|
2
|
+
// 1) Instala el cliente: npm i @supabase/supabase-js
|
|
3
|
+
// 2) Reemplaza URL y ANON KEY (Supabase Dashboard → Project Settings → API).
|
|
4
|
+
// 3) Ejecuta la migración: supabase-migrations/0001_turnos.sql
|
|
5
|
+
import { createClient as createSupabaseClient } from '@supabase/supabase-js'
|
|
6
|
+
import { createClient } from 'turnos'
|
|
7
|
+
|
|
8
|
+
const supabase = createSupabaseClient(
|
|
9
|
+
'https://TU_ORG.supabase.co', // ← reemplazar por tu URL
|
|
10
|
+
'TU_ANON_KEY', // ← reemplazar por tu anon key
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
// Cliente del paquete `turnos` — mismo contrato para todos los proveedores:
|
|
14
|
+
// listTurnos / upsertTurno / removeTurno / bookTurno / unbookTurno / subscribe
|
|
15
|
+
export const turnos = createClient({
|
|
16
|
+
provider: 'supabase',
|
|
17
|
+
supabase,
|
|
18
|
+
table: 'turnos',
|
|
19
|
+
})
|