Files
recordalexia/frontend/src/app/features/parents/routines-tab.component.ts
Jaume Garriga Maestre 3ec611d373 fix(rutinas): cascade al borrar del catálogo, orden por día y test de migración real
- Changeset 004: ON DELETE CASCADE en fk_routine_assignment_task; borrar
  una rutina del catálogo arrastra sus asignaciones en vez de fallar (test).
- El orderIndex de la asignación multi-día lo calcula el backend al final
  de CADA día destino (antes lo enviaba el front desde el día visible).
- MigrationIT con Testcontainers: el changelog completo y el mapeo JPA se
  verifican contra Postgres 16 real (H2 no detecta su tipado estricto).
- DataSeeder delega en InitialDatasetService: una sola fuente de verdad
  del dataset inicial; la demo solo añade sus extras.
- Eliminado .gitkeep de changes/ (WARN de Liquibase en cada arranque).
2026-07-12 22:02:22 +02:00

242 lines
8.8 KiB
TypeScript

import { Component, Input, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ParentApiService } from '../../core/parent-api.service';
import { I18nService } from '../../core/i18n.service';
import { RoutineTaskView, RoutineView } from '../../core/models';
import { EmojiPickerComponent } from '../../shared/emoji-picker.component';
import { ColorPickerComponent } from '../../shared/color-picker.component';
const DAYS: { key: string; es: string; ca: string }[] = [
{ key: 'MONDAY', es: 'Lunes', ca: 'Dilluns' },
{ key: 'TUESDAY', es: 'Martes', ca: 'Dimarts' },
{ key: 'WEDNESDAY', es: 'Miércoles', ca: 'Dimecres' },
{ key: 'THURSDAY', es: 'Jueves', ca: 'Dijous' },
{ key: 'FRIDAY', es: 'Viernes', ca: 'Divendres' },
{ key: 'SATURDAY', es: 'Sábado', ca: 'Dissabte' },
{ key: 'SUNDAY', es: 'Domingo', ca: 'Diumenge' },
];
/**
* Pestaña Rutinas de tarde. Dos pasos: (1) definir rutinas en el catálogo de la familia
* una sola vez; (2) asignar una rutina del catálogo a varios días del niño de golpe.
* Reutiliza el patrón de las mañanas (catálogo de actividades + asignación por día).
*/
@Component({
selector: 'app-routines-tab',
imports: [FormsModule, EmojiPickerComponent, ColorPickerComponent],
template: `
<!-- 1) Catálogo de rutinas reutilizables de la familia -->
<div class="adm-card">
<p class="adm-label">Catálogo de rutinas</p>
<div class="grid2">
<div class="field">
<label class="field__label">Rutina (ES)</label>
<input class="field__input" [(ngModel)]="labelEs" placeholder="Ej. Hacer los deberes" />
</div>
<div class="field">
<label class="field__label">Rutina (CA)</label>
<input class="field__input" [(ngModel)]="labelCa" placeholder="Ex. Fer els deures" />
</div>
</div>
<div class="field">
<label class="field__label">Icono <span class="field__info" title="Toca un emoji para la rutina.">ⓘ</span></label>
<app-emoji-picker [(value)]="icon" [options]="routineIcons" />
</div>
<div class="field">
<label class="field__label">Color</label>
<app-color-picker [(value)]="color" />
</div>
<button class="adm-btn" [disabled]="!labelEs || !labelCa || !icon" (click)="addToCatalog()">
+ {{ i18n.t('add') }}
</button>
<div class="adm-list">
@for (t of catalog(); track t.id) {
<div class="adm-item">
<span>{{ t.icon }}</span>
<span class="adm-item__grow">{{ i18n.label(t.labelEs, t.labelCa) }}</span>
<button class="adm-del" (click)="removeFromCatalog(t)" aria-label="Borrar">✕</button>
</div>
} @empty {
<p class="adm-empty">{{ i18n.t('none') }}</p>
}
</div>
</div>
<!-- 2) Asignar una rutina del catálogo a varios días -->
<div class="adm-card">
<p class="adm-label">Asignar a días</p>
<div class="field">
<label class="field__label">Rutina</label>
<select class="field__input" [(ngModel)]="selectedTaskId">
<option [ngValue]="null" disabled>— Elige una rutina —</option>
@for (t of catalog(); track t.id) {
<option [ngValue]="t.id">{{ t.icon }} {{ i18n.label(t.labelEs, t.labelCa) }}</option>
}
</select>
</div>
<div class="adm-row">
@for (d of days; track d.key) {
<button
class="adm-chip"
[style.background]="isSelected(d.key) ? 'var(--accent-purple)' : ''"
[style.color]="isSelected(d.key) ? '#fff' : ''"
(click)="toggleSelectedDay(d.key)"
>
{{ i18n.label(d.es, d.ca) }}
</button>
}
</div>
<button
class="adm-btn"
[disabled]="selectedTaskId === null || selectedDays().length === 0"
(click)="assign()"
>
Asignar a {{ selectedDays().length }} día(s)
</button>
</div>
<!-- Vista de asignaciones por día -->
<div class="adm-card">
<div class="adm-row">
<span class="adm-label">{{ i18n.t('tabRoutines') }}:</span>
@for (d of days; track d.key) {
<button
class="adm-chip"
[style.background]="d.key === day() ? 'var(--accent-purple)' : ''"
[style.color]="d.key === day() ? '#fff' : ''"
(click)="day.set(d.key)"
>
{{ i18n.label(d.es, d.ca) }}
</button>
}
</div>
<div class="adm-list">
@for (r of routinesForDay(); track r.id; let i = $index; let last = $last) {
<div class="adm-item">
<span>{{ r.icon }}</span>
<span class="adm-item__grow">{{ i18n.label(r.labelEs, r.labelCa) }}</span>
<button class="adm-del" [disabled]="i === 0" (click)="move(i, -1)" aria-label="Subir">▲</button>
<button class="adm-del" [disabled]="last" (click)="move(i, 1)" aria-label="Bajar">▼</button>
<button class="adm-del" (click)="remove(r)">✕</button>
</div>
} @empty {
<p class="adm-empty">{{ i18n.t('none') }}</p>
}
</div>
</div>
`,
styles: [
`
.field { margin-bottom: var(--space-4); }
.field__label { display: flex; align-items: center; gap: 6px; font-weight: 700; color: var(--text-1); margin-bottom: 6px; }
.field__info { cursor: help; color: var(--text-4); font-size: 0.85rem; }
.field__input {
font-family: var(--font-body); font-size: 1rem; padding: 12px 14px;
border: 2px solid var(--border-2); border-radius: var(--radius-sm);
background: var(--surface); color: var(--text-strong); width: 100%; box-sizing: border-box;
}
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-4); }
@media (max-width: 520px) { .grid2 { grid-template-columns: 1fr; } }
`,
],
})
export class RoutinesTabComponent {
@Input({ required: true }) set childId(value: number) {
this._childId = value;
this.reload();
}
private _childId!: number;
private readonly api = inject(ParentApiService);
protected readonly i18n = inject(I18nService);
protected readonly days = DAYS;
protected readonly day = signal('MONDAY');
protected readonly catalog = signal<RoutineTaskView[]>([]);
protected readonly routines = signal<RoutineView[]>([]);
protected readonly routinesForDay = computed(() =>
this.routines().filter((r) => r.dayOfWeek === this.day()),
);
// Estado del formulario del catálogo.
protected readonly routineIcons = ['🎒', '🥪', '📝', '🎹', '🍽️', '🛁', '🦷', '📚', '🧹', '🐕', '🛏️', '🎨', '⚽', '🧺'];
protected icon = '';
protected labelEs = '';
protected labelCa = '';
protected color = '#A78BD0';
// Estado del formulario de asignación.
protected selectedTaskId: number | null = null;
protected readonly selectedDays = signal<string[]>([]);
private reload(): void {
this.api.listRoutineTasks().subscribe((l) => this.catalog.set(l));
this.api.listRoutines(this._childId).subscribe((l) => this.routines.set(l));
}
// --- Catálogo ---
addToCatalog(): void {
this.api
.createRoutineTask({
labelEs: this.labelEs,
labelCa: this.labelCa,
icon: this.icon,
color: this.color,
})
.subscribe(() => {
this.labelEs = this.labelCa = this.icon = '';
this.reload();
});
}
removeFromCatalog(t: RoutineTaskView): void {
this.api.deleteRoutineTask(t.id).subscribe(() => this.reload());
}
// --- Asignación multi-día ---
isSelected(dayKey: string): boolean {
return this.selectedDays().includes(dayKey);
}
toggleSelectedDay(dayKey: string): void {
const current = this.selectedDays();
this.selectedDays.set(
current.includes(dayKey) ? current.filter((d) => d !== dayKey) : [...current, dayKey],
);
}
assign(): void {
if (this.selectedTaskId === null || this.selectedDays().length === 0) {
return;
}
// El backend calcula el orden al final de CADA día destino.
this.api
.createRoutine({
childId: this._childId,
routineTaskId: this.selectedTaskId,
daysOfWeek: this.selectedDays(),
})
.subscribe(() => {
this.selectedTaskId = null;
this.selectedDays.set([]);
this.reload();
});
}
/** Mueve una rutina del día arriba (-1) o abajo (+1) y persiste el nuevo orden. */
move(index: number, delta: number): void {
const list = [...this.routinesForDay()];
const target = index + delta;
if (target < 0 || target >= list.length) {
return;
}
[list[index], list[target]] = [list[target], list[index]];
this.api.reorderRoutines(list.map((r) => r.id)).subscribe(() => this.reload());
}
remove(r: RoutineView): void {
this.api.deleteRoutine(r.id).subscribe(() => this.reload());
}
}