@ffstack/turnos 0.2.0 → 0.3.3

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/bin/turnos.js CHANGED
@@ -1,71 +1,138 @@
1
1
  #!/usr/bin/env node
2
- import { parseArgs } from 'node:util';
2
+ import { Command } from 'commander';
3
+ import inquirer from 'inquirer';
3
4
  import { generateFiles, resolveTargetDir } from '../src/generator.js';
4
5
  import { runPostinstall } from '../src/postinstall.js';
6
+ import { installDependencies } from '../src/utils/cli-utils.js';
7
+ import { ENV_TEMPLATES } from '../src/utils/env-templates.js';
8
+ import fs from 'fs';
9
+ import path from 'path';
5
10
 
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' },
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: [],
21
56
  },
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);
57
+ ];
58
+
59
+ const program = new Command();
60
+
61
+ program
62
+ .name('turnos')
63
+ .description('CLI para instalar y configurar turnos en tu proyecto')
64
+ .version('0.3.1');
65
+
66
+ program
67
+ .command('init')
68
+ .description('Inicializa los componentes de turnos en tu proyecto')
69
+ .option('-f, --force', 'Sobrescribir archivos existentes')
70
+ .option('-d, --dir <ruta>', 'Directorio destino')
71
+ .action(async (options) => {
72
+ const { provider } = await inquirer.prompt([
73
+ {
74
+ type: 'list',
75
+ name: 'provider',
76
+ message: '¿Qué base de datos quieres usar?',
77
+ choices: PROVIDERS,
78
+ },
79
+ ]);
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
107
+ const res = await generateFiles({
108
+ provider,
109
+ targetDir,
110
+ force: options.force,
111
+ });
112
+
113
+ // Automatizar instalación de dependencias
114
+ const deps = provider === 'supabase' ? ['@supabase/supabase-js'] : ['firebase'];
115
+ installDependencies(deps);
116
+
117
+ // Generar .env.example
118
+ fs.writeFileSync(path.join(targetDir, '.env.example'), ENV_TEMPLATES[provider].trim());
119
+ console.log(`\n + .env.example creado con configuración para ${provider}`);
120
+
121
+ if (res.self) {
122
+ console.log('Estás en el propio paquete "turnos".');
123
+ return;
124
+ }
125
+
126
+ res.generated.forEach((f) => console.log(` + ${f}`));
127
+ res.skipped.forEach((f) => console.log(` = ${f} (ya existía)`));
128
+
129
+ console.log(`\n¡Turnos inicializado con ${provider}!`);
130
+ });
131
+
132
+ program
133
+ .command('postinstall')
134
+ .action(async () => {
135
+ await runPostinstall({ targetDir: resolveTargetDir() });
136
+ });
137
+
138
+ program.parse(process.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ffstack/turnos",
3
- "version": "0.2.0",
3
+ "version": "0.3.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -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": [
@@ -27,6 +28,7 @@
27
28
  "src/adapters",
28
29
  "src/generator.js",
29
30
  "src/postinstall.js",
31
+ "src/utils",
30
32
  "templates",
31
33
  "README.md",
32
34
  "!**/*.test.js",
@@ -63,6 +65,8 @@
63
65
  "supabase"
64
66
  ],
65
67
  "dependencies": {
68
+ "commander": "^13.0.0",
69
+ "inquirer": "^12.0.0",
66
70
  "date-fns": "^4.4.0",
67
71
  "lucide-react": "^1.71.0",
68
72
  "react": "^19.3.1",
@@ -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
  }
@@ -0,0 +1,19 @@
1
+ import { execSync } from 'child_process';
2
+ import fs from 'fs';
3
+
4
+ export function getPackageManager() {
5
+ if (fs.existsSync('package-lock.json')) return 'npm';
6
+ if (fs.existsSync('pnpm-lock.yaml')) return 'pnpm';
7
+ if (fs.existsSync('yarn.lock')) return 'yarn';
8
+ if (fs.existsSync('bun.lockb')) return 'bun';
9
+ return 'npm';
10
+ }
11
+
12
+ export function installDependencies(dependencies) {
13
+ const pm = getPackageManager();
14
+ const installCmd = pm === 'npm' ? 'install' : 'add';
15
+ const command = `${pm} ${installCmd} ${dependencies.join(' ')}`;
16
+
17
+ console.log(`\nEjecutando: ${command}...`);
18
+ execSync(command, { stdio: 'inherit' });
19
+ }
@@ -0,0 +1,16 @@
1
+ export const ENV_TEMPLATES = {
2
+ firebase: `
3
+ # Firebase Configuration
4
+ VITE_FIREBASE_API_KEY=
5
+ VITE_FIREBASE_AUTH_DOMAIN=
6
+ VITE_FIREBASE_PROJECT_ID=
7
+ VITE_FIREBASE_STORAGE_BUCKET=
8
+ VITE_FIREBASE_MESSAGING_SENDER_ID=
9
+ VITE_FIREBASE_APP_ID=
10
+ `,
11
+ supabase: `
12
+ # Supabase Configuration
13
+ VITE_SUPABASE_URL=
14
+ VITE_SUPABASE_ANON_KEY=
15
+ `,
16
+ };
@@ -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
+ })