Compare commits

..
4 Commits
3 changed files with 293 additions and 21 deletions

No files matched your search

+18 -1
View File
@@ -2,7 +2,7 @@
> **Author:** Anne Droid <anne-droid@roadtotech.me> > **Author:** Anne Droid <anne-droid@roadtotech.me>
> **Role:** Senior Frontend Engineer & UX Specialist > **Role:** Senior Frontend Engineer & UX Specialist
> **Worktree:** `/home/kiskaadee/Projects/active/armonia/armonia-dashboard-anne-roster` > **Worktree:** `/home/kiskaadee/Projects/active/armonia/.worktrees/armonia-dashboard-anne-roster`
> **Branch:** `feat/anne/workshop-roster` > **Branch:** `feat/anne/workshop-roster`
> **Date:** 2026-10-26 > **Date:** 2026-10-26
> **Target Specification:** `docs/pilot/SPEC-WORKSHOP-ROSTER.md` > **Target Specification:** `docs/pilot/SPEC-WORKSHOP-ROSTER.md`
@@ -125,3 +125,20 @@ The implementation strictly respects the Scope Containment Invariant:
- **Notice 1 (String Matching on HTTP 409 detail)**: - **Notice 1 (String Matching on HTTP 409 detail)**:
As anticipated in Section 2.1 of `SPEC-WORKSHOP-ROSTER.md`, disambiguating between duplicate check-in (`"This attendee has already checked in."`) and session capacity (`"El taller ha alcanzado su cupo máximo..."`) relies on substring matching on `response.detail`. This is preserved as an accepted pilot accommodation to maintain backend immutability on `armonia-api`. An M5 ticket will introduce machine-readable error codes (`error_code`). As anticipated in Section 2.1 of `SPEC-WORKSHOP-ROSTER.md`, disambiguating between duplicate check-in (`"This attendee has already checked in."`) and session capacity (`"El taller ha alcanzado su cupo máximo..."`) relies on substring matching on `response.detail`. This is preserved as an accepted pilot accommodation to maintain backend immutability on `armonia-api`. An M5 ticket will introduce machine-readable error codes (`error_code`).
---
## 6. Addendum: Post-Review Revision & Multi-Attendee 409 Server Reconciliation
Following Project Owner review and QA verification of PR #9, targeted enhancements were implemented:
1. **Finding A: HTML Sanitization (`escapeHtml`)**:
- Introduced and exported `escapeHtml(str: string): string` in `src/components/WorkshopRoster.ts` (matching the pattern in `ClientDirectory.ts` and `IntakeModal.ts`).
- Sanitized all dynamic string interpolations (`attendee.client_name`, `attendee.client_phone`, `attendee.booking_code`, `session.service_name`, date strings, etc.) across visible text nodes and attribute values (`aria-label`, `title`, `href`, `data-booking-id`).
2. **Finding B & Case 2B: Authoritative Server Reconciliation on 409 Conflict**:
- Implemented `reconcileSessionsWithServer()` in `src/components/WorkshopRoster.ts`.
- When an `ALREADY_CHECKED_IN` 409 conflict occurs, the client now performs an authoritative refresh from `fetchRosters({ date_from, date_to })`, reconciling all sessions and attendees against server state and re-rendering the view.
- This ensures that if multiple attendees were checked in out-of-band across devices (Case 2B), the capacity counter immediately reflects the exact server count (e.g. `2 presentes`) and all checked-in attendees render with `ASISTIÓ`. If the refresh fetch fails, it gracefully falls back to local row reconciliation via `reconcileAlreadyCheckedInState()`.
3. **Verification**:
- Added unit test suites in `tests/roster.test.ts` validating HTML escaping (XSS vectors, attributes, plain strings), local state reconciliation, and authoritative multi-attendee out-of-band reconciliation (Case 2B).
- Test suite passes 100%: 34/34 tests passing (17 utils + 17 roster).
+107 -20
View File
@@ -97,6 +97,73 @@ export type ConflictType =
| "CAPACITY_EXCEEDED" | "CAPACITY_EXCEEDED"
| "UNKNOWN"; | "UNKNOWN";
/**
* Escape HTML characters to prevent XSS in template string interpolations
*/
export function escapeHtml(str: string): string {
return str
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
/**
* Reconcile session state upon out-of-band 409 ALREADY_CHECKED_IN conflict.
* Ensures attendance status is COMPLETED / ASISTIÓ, and if the attendee was
* previously unrecorded locally, increments attended_count.
* Returns true if attended_count was incremented.
*/
export function reconcileAlreadyCheckedInState(
session: RosterSession,
attendee: RosterAttendee,
): boolean {
const wasAttended =
attendee.attended || attendee.booking_status === "COMPLETED";
attendee.attended = true;
attendee.booking_status = "COMPLETED";
if (!wasAttended) {
session.attended_count += 1;
return true;
}
return false;
}
/**
* Reconcile local session state with authoritative server sessions.
* Matches sessions by service_id and scheduled_at to update counts and attendee records.
*/
export function reconcileSessionsWithServer(
currentSessions: RosterSession[],
freshSessions: RosterSession[],
): RosterSession[] {
if (!freshSessions || freshSessions.length === 0) {
return currentSessions;
}
return freshSessions.map((fresh) => {
const existing = currentSessions.find(
(curr) =>
curr.service_id === fresh.service_id &&
curr.scheduled_at === fresh.scheduled_at,
);
if (!existing) return fresh;
return {
...existing,
...fresh,
attendees: fresh.attendees.map((freshAtt) => {
const existingAtt = existing.attendees.find(
(a) => a.booking_id === freshAtt.booking_id,
);
return {
...existingAtt,
...freshAtt,
};
}),
};
});
}
/** /**
* Disambiguate HTTP 409 Conflict based on response detail * Disambiguate HTTP 409 Conflict based on response detail
*/ */
@@ -151,7 +218,7 @@ export function renderWorkshopRoster(
type="date" type="date"
id="roster-date-input" id="roster-date-input"
class="form-input-date" class="form-input-date"
value="${selectedDate}" value="${escapeHtml(selectedDate)}"
aria-label="Seleccionar fecha de talleres" aria-label="Seleccionar fecha de talleres"
/> />
</div> </div>
@@ -247,7 +314,7 @@ export function renderWorkshopRoster(
<div class="empty-icon" aria-hidden="true">🪷</div> <div class="empty-icon" aria-hidden="true">🪷</div>
<h3 class="empty-title">Sin talleres programados</h3> <h3 class="empty-title">Sin talleres programados</h3>
<p class="empty-message">No hay talleres grupales programados para esta fecha.</p> <p class="empty-message">No hay talleres grupales programados para esta fecha.</p>
<p class="text-xs text-muted mt-2">Fecha seleccionada: ${dateStr}. Navega a otra fecha para consultar talleres.</p> <p class="text-xs text-muted mt-2">Fecha seleccionada: ${escapeHtml(dateStr)}. Navega a otra fecha para consultar talleres.</p>
</div> </div>
`; `;
} }
@@ -296,8 +363,8 @@ export function renderWorkshopRoster(
card.innerHTML = ` card.innerHTML = `
<div class="session-card-header"> <div class="session-card-header">
<div class="session-title-block"> <div class="session-title-block">
<span class="session-time-pill" title="Horario del taller">⏰ ${timeStr} hrs</span> <span class="session-time-pill" title="Horario del taller">⏰ ${escapeHtml(timeStr)} hrs</span>
<h3 class="session-title">${session.service_name}</h3> <h3 class="session-title">${escapeHtml(session.service_name)}</h3>
</div> </div>
<div class="session-header-actions"> <div class="session-header-actions">
<span class="session-capacity-counter font-mono font-medium" id="capacity-counter-${sessionIdx}"> <span class="session-capacity-counter font-mono font-medium" id="capacity-counter-${sessionIdx}">
@@ -343,6 +410,7 @@ export function renderWorkshopRoster(
attendee.attended || attendee.booking_status === "COMPLETED"; attendee.attended || attendee.booking_status === "COMPLETED";
const waUrl = buildWhatsAppUrl(attendee.client_phone); const waUrl = buildWhatsAppUrl(attendee.client_phone);
const formattedPhone = formatMexicanPhone(attendee.client_phone); const formattedPhone = formatMexicanPhone(attendee.client_phone);
const cleanPhoneDigits = getCleanDigitsPhone(attendee.client_phone);
const attendanceBadge = renderAttendanceStatusBadge( const attendanceBadge = renderAttendanceStatusBadge(
isAttended, isAttended,
@@ -365,7 +433,7 @@ export function renderWorkshopRoster(
type="checkbox" type="checkbox"
id="cash-check-${sessionIdx}-${attIdx}" id="cash-check-${sessionIdx}-${attIdx}"
class="cash-checkbox" class="cash-checkbox"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
/> />
<span class="text-xs">Cobro en efectivo recibido</span> <span class="text-xs">Cobro en efectivo recibido</span>
</label> </label>
@@ -374,7 +442,7 @@ export function renderWorkshopRoster(
class="btn btn-primary btn-sm btn-checkin" class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}" data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}" data-att-idx="${attIdx}"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
> >
Registrar Asistencia Registrar Asistencia
</button> </button>
@@ -389,7 +457,7 @@ export function renderWorkshopRoster(
class="btn btn-primary btn-sm btn-checkin" class="btn btn-primary btn-sm btn-checkin"
data-session-idx="${sessionIdx}" data-session-idx="${sessionIdx}"
data-att-idx="${attIdx}" data-att-idx="${attIdx}"
data-booking-id="${attendee.booking_id}" data-booking-id="${escapeHtml(attendee.booking_id)}"
> >
Registrar Asistencia Registrar Asistencia
</button> </button>
@@ -398,24 +466,24 @@ export function renderWorkshopRoster(
} }
return ` return `
<div class="roster-attendee-row ${isAttended ? "row-attended" : ""}" data-booking-id="${attendee.booking_id}"> <div class="roster-attendee-row ${isAttended ? "row-attended" : ""}" data-booking-id="${escapeHtml(attendee.booking_id)}">
<div class="attendee-col-client"> <div class="attendee-col-client">
<span class="attendee-name font-medium">${attendee.client_name}</span> <span class="attendee-name font-medium">${escapeHtml(attendee.client_name)}</span>
<span class="attendee-code font-mono">${attendee.booking_code}</span> <span class="attendee-code font-mono">${escapeHtml(attendee.booking_code)}</span>
</div> </div>
<div class="attendee-col-phone"> <div class="attendee-col-phone">
<span class="attendee-phone-text">${formattedPhone}</span> <span class="attendee-phone-text">${escapeHtml(formattedPhone)}</span>
<a <a
href="${waUrl}" href="${escapeHtml(waUrl)}"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="btn-wa-link" class="btn-wa-link"
title="Abrir chat en WhatsApp" title="Abrir chat en WhatsApp"
aria-label="Contactar a ${attendee.client_name} por WhatsApp" aria-label="Contactar a ${escapeHtml(attendee.client_name)} por WhatsApp"
> >
<span class="wa-icon" aria-hidden="true">💬</span> <span class="wa-icon" aria-hidden="true">💬</span>
<span class="wa-label font-mono text-xs">wa.me/${getCleanDigitsPhone(attendee.client_phone)}</span> <span class="wa-label font-mono text-xs">wa.me/${escapeHtml(cleanPhoneDigits)}</span>
</a> </a>
</div> </div>
@@ -527,11 +595,30 @@ export function renderWorkshopRoster(
const conflictType = disambiguate409Error(detail); const conflictType = disambiguate409Error(detail);
if (conflictType === "ALREADY_CHECKED_IN") { if (conflictType === "ALREADY_CHECKED_IN") {
// 409 Case A: Reconcile row to ASISTIÓ, disable button, informative toast // 409 Case A: Authoritative server state reconciliation
attendee.attended = true; try {
attendee.booking_status = "COMPLETED"; const freshSessions = await fetchRosters({
updateRowAttendanceState(rowEl, attendee); date_from: selectedDate,
date_to: selectedDate,
});
cachedSessions = reconcileSessionsWithServer(
cachedSessions,
freshSessions,
);
if (contentEl) {
renderSessions(contentEl, cachedSessions);
}
} catch {
// Fallback to local row reconciliation if refresh fetch fails
const incremented = reconcileAlreadyCheckedInState(session, attendee);
if (incremented) {
updateCapacityDisplay(session, sessionIdx);
}
updateRowAttendanceState(rowEl, attendee);
}
showToast("El asistente ya contaba con asistencia registrada", "info"); showToast("El asistente ya contaba con asistencia registrada", "info");
onStateChange?.();
} else { } else {
// Ordinary failure / timeout // Ordinary failure / timeout
button.disabled = false; button.disabled = false;
@@ -613,11 +700,11 @@ export function renderWorkshopRoster(
<div class="summary-box"> <div class="summary-box">
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Taller:</span> <span class="summary-label">Taller:</span>
<span class="summary-value font-medium">${session.service_name}</span> <span class="summary-value font-medium">${escapeHtml(session.service_name)}</span>
</div> </div>
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Horario:</span> <span class="summary-label">Horario:</span>
<span class="summary-value font-mono font-bold">${timeStr} hrs</span> <span class="summary-value font-mono font-bold">${escapeHtml(timeStr)} hrs</span>
</div> </div>
<div class="summary-row"> <div class="summary-row">
<span class="summary-label">Capacidad Actual:</span> <span class="summary-label">Capacidad Actual:</span>
+168
View File
@@ -2,10 +2,14 @@ import { describe, expect, it } from "vitest";
import { import {
buildWhatsAppUrl, buildWhatsAppUrl,
disambiguate409Error, disambiguate409Error,
escapeHtml,
formatRosterCapacity, formatRosterCapacity,
reconcileAlreadyCheckedInState,
reconcileSessionsWithServer,
renderAttendanceStatusBadge, renderAttendanceStatusBadge,
renderPaymentStatusPill, renderPaymentStatusPill,
} from "../src/components/WorkshopRoster"; } from "../src/components/WorkshopRoster";
import type { RosterAttendee, RosterSession } from "../src/types";
describe("Workshop Roster Utilities", () => { describe("Workshop Roster Utilities", () => {
describe("Capacity Formatting", () => { describe("Capacity Formatting", () => {
@@ -97,4 +101,168 @@ describe("Workshop Roster Utilities", () => {
expect(disambiguate409Error(undefined)).toBe("UNKNOWN"); expect(disambiguate409Error(undefined)).toBe("UNKNOWN");
}); });
}); });
describe("HTML Sanitization (escapeHtml)", () => {
it("escapes dangerous HTML characters to prevent XSS", () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
"&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;",
);
expect(escapeHtml("Tom & Jerry's")).toBe("Tom &amp; Jerry&#039;s");
expect(escapeHtml('<img src="x" onerror="alert(1)">')).toBe(
"&lt;img src=&quot;x&quot; onerror=&quot;alert(1)&quot;&gt;",
);
});
it("leaves strings without special characters untouched", () => {
expect(escapeHtml("Elena Gómez")).toBe("Elena Gómez");
expect(escapeHtml("ADS-1001")).toBe("ADS-1001");
expect(escapeHtml("+52 55 1111 2222")).toBe("+52 55 1111 2222");
});
});
describe("409 Out-of-Band Counter Reconciliation", () => {
function createMockSession(occupied = 2, attended = 0): RosterSession {
return {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: occupied,
attended_count: attended,
attendees: [],
};
}
function createMockAttendee(attended = false): RosterAttendee {
return {
booking_id: "bk-123",
booking_code: "ADS-1001",
client_id: "cl-123",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: attended ? "COMPLETED" : "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended,
};
}
it("increments attended_count and reconciles attendee when locally unrecorded", () => {
const session = createMockSession(2, 0);
const attendee = createMockAttendee(false);
const incremented = reconcileAlreadyCheckedInState(session, attendee);
expect(incremented).toBe(true);
expect(session.attended_count).toBe(1);
expect(attendee.attended).toBe(true);
expect(attendee.booking_status).toBe("COMPLETED");
});
it("does not increment attended_count if attendee was already marked attended locally", () => {
const session = createMockSession(2, 1);
const attendee = createMockAttendee(true);
const incremented = reconcileAlreadyCheckedInState(session, attendee);
expect(incremented).toBe(false);
expect(session.attended_count).toBe(1); // Unchanged
expect(attendee.attended).toBe(true);
});
it("reconciles multiple out-of-band check-ins authoritatively from server response (Case 2B)", () => {
const staleLocalSession: RosterSession = {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: 2,
attended_count: 0,
attendees: [
{
booking_id: "bk-1001",
booking_code: "ADS-1001",
client_id: "cl-1",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: false,
},
{
booking_id: "bk-1002",
booking_code: "ADS-1002",
client_id: "cl-2",
client_name: "Carlos Méndez",
client_phone: "525533334444",
booking_status: "RESERVED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "AWAITING_ACKNOWLEDGMENT",
amount_mxn: 350,
attended: false,
},
],
};
const authoritativeServerSession: RosterSession = {
service_id: "srv-123",
service_name: "Círculo de Cacao",
scheduled_at: "2026-10-26T18:00:00Z",
max_capacity: 15,
occupied_count: 2,
attended_count: 2,
attendees: [
{
booking_id: "bk-1001",
booking_code: "ADS-1001",
client_id: "cl-1",
client_name: "Elena Gómez",
client_phone: "525511112222",
booking_status: "COMPLETED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: true,
},
{
booking_id: "bk-1002",
booking_code: "ADS-1002",
client_id: "cl-2",
client_name: "Carlos Méndez",
client_phone: "525533334444",
booking_status: "COMPLETED",
payment_arrangement: "PREPAID_DEFAULT",
payment_status: "ACKNOWLEDGED",
amount_mxn: 350,
attended: true,
},
],
};
const reconciled = reconcileSessionsWithServer(
[staleLocalSession],
[authoritativeServerSession],
);
expect(reconciled).toHaveLength(1);
expect(reconciled[0].occupied_count).toBe(2);
expect(reconciled[0].attended_count).toBe(2);
const elena = reconciled[0].attendees.find(
(a) => a.booking_code === "ADS-1001",
);
const carlos = reconciled[0].attendees.find(
(a) => a.booking_code === "ADS-1002",
);
expect(elena?.attended).toBe(true);
expect(elena?.booking_status).toBe("COMPLETED");
expect(carlos?.attended).toBe(true);
expect(carlos?.booking_status).toBe("COMPLETED");
});
});
}); });