Files
e-ticket/tests/js/cart.test.js

411 lines
14 KiB
JavaScript
Raw Normal View History

Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { initCart } from '../../assets/modules/cart.js'
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
function createBilletterie(billets, stockUrl = '') {
let html = `<div id="billetterie"${stockUrl ? ` data-stock-url="${stockUrl}"` : ''}>`
for (const b of billets) {
html += `
<div data-cart-item data-billet-id="${b.id}" data-price="${b.price}" data-max="${b.max}">
<button data-cart-minus></button>
<input data-cart-qty type="number" min="0" max="${b.max || 99}" value="0" readonly>
<button data-cart-plus></button>
<span data-cart-line-total></span>
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
<p data-stock-label></p>
</div>
`
}
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
html += '<div id="cart-error" class="hidden"><p id="cart-error-text"></p></div>'
html += '<span id="cart-total"></span><span id="cart-count"></span><button id="cart-checkout" disabled data-order-url="/order"></button></div>'
document.body.innerHTML = html
}
describe('initCart', () => {
beforeEach(() => {
document.body.innerHTML = ''
})
it('does nothing without billetterie element', () => {
expect(() => initCart()).not.toThrow()
})
it('does nothing without total element', () => {
document.body.innerHTML = '<div id="billetterie"></div>'
expect(() => initCart()).not.toThrow()
})
it('initializes with zero totals', () => {
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
expect(document.getElementById('cart-count').textContent).toBe('0')
expect(document.getElementById('cart-checkout').disabled).toBe(true)
})
it('increments quantity on plus click', () => {
createBilletterie([{ id: 1, price: '15.00', max: 10 }])
initCart()
document.querySelector('[data-cart-plus]').click()
expect(document.querySelector('[data-cart-qty]').value).toBe('1')
expect(document.querySelector('[data-cart-line-total]').textContent).toBe('15,00 \u20AC')
expect(document.getElementById('cart-total').textContent).toBe('15,00 \u20AC')
expect(document.getElementById('cart-count').textContent).toBe('1')
expect(document.getElementById('cart-checkout').disabled).toBe(false)
})
it('decrements quantity on minus click', () => {
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.querySelector('[data-cart-plus]').click()
document.querySelector('[data-cart-minus]').click()
expect(document.querySelector('[data-cart-qty]').value).toBe('1')
expect(document.getElementById('cart-total').textContent).toBe('10,00 \u20AC')
})
it('does not decrement below zero', () => {
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-minus]').click()
expect(document.querySelector('[data-cart-qty]').value).toBe('0')
expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
})
it('respects max quantity', () => {
createBilletterie([{ id: 1, price: '10.00', max: 2 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.querySelector('[data-cart-plus]').click()
document.querySelector('[data-cart-plus]').click()
expect(document.querySelector('[data-cart-qty]').value).toBe('2')
expect(document.getElementById('cart-total').textContent).toBe('20,00 \u20AC')
})
it('allows unlimited when max is 0', () => {
createBilletterie([{ id: 1, price: '5.00', max: 0 }])
initCart()
for (let i = 0; i < 50; i++) {
document.querySelector('[data-cart-plus]').click()
}
expect(document.querySelector('[data-cart-qty]').value).toBe('50')
expect(document.getElementById('cart-total').textContent).toBe('250,00 \u20AC')
})
it('calculates total for multiple billets', () => {
createBilletterie([
{ id: 1, price: '10.00', max: 5 },
{ id: 2, price: '25.00', max: 3 },
])
initCart()
const plusBtns = document.querySelectorAll('[data-cart-plus]')
plusBtns[0].click()
plusBtns[0].click()
plusBtns[1].click()
// 2 * 10 + 1 * 25 = 45
expect(document.getElementById('cart-total').textContent).toBe('45,00 \u20AC')
expect(document.getElementById('cart-count').textContent).toBe('3')
})
it('disables checkout when cart is empty again', () => {
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
expect(document.getElementById('cart-checkout').disabled).toBe(false)
document.querySelector('[data-cart-minus]').click()
expect(document.getElementById('cart-checkout').disabled).toBe(true)
})
it('posts cart data on checkout click', () => {
const fetchMock = vi.fn().mockResolvedValue({
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
ok: true,
json: () => Promise.resolve({ redirect: '/commande/1/informations' }),
})
globalThis.fetch = fetchMock
createBilletterie([
{ id: 1, price: '10.00', max: 5 },
{ id: 2, price: '20.00', max: 3 },
])
initCart()
const plusBtns = document.querySelectorAll('[data-cart-plus]')
plusBtns[0].click()
plusBtns[0].click()
plusBtns[1].click()
document.getElementById('cart-checkout').click()
expect(fetchMock).toHaveBeenCalledWith('/order', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([
{ billetId: '1', qty: 2 },
{ billetId: '2', qty: 1 },
]),
})
})
it('redirects after successful checkout', async () => {
const fetchMock = vi.fn().mockResolvedValue({
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
ok: true,
json: () => Promise.resolve({ redirect: '/commande/1/paiement' }),
})
globalThis.fetch = fetchMock
globalThis.location = { href: '' }
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.getElementById('cart-checkout').click()
await new Promise(r => setTimeout(r, 10))
expect(globalThis.location.href).toBe('/commande/1/paiement')
})
it('does not redirect when response has no redirect', async () => {
const fetchMock = vi.fn().mockResolvedValue({
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
ok: true,
json: () => Promise.resolve({}),
})
globalThis.fetch = fetchMock
globalThis.location = { href: '/original' }
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.getElementById('cart-checkout').click()
await new Promise(r => setTimeout(r, 10))
expect(globalThis.location.href).toBe('/original')
})
it('re-enables button on fetch error', async () => {
const fetchMock = vi.fn().mockRejectedValue(new Error('Network error'))
globalThis.fetch = fetchMock
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.getElementById('cart-checkout').click()
await new Promise(r => setTimeout(r, 10))
const btn = document.getElementById('cart-checkout')
expect(btn.disabled).toBe(false)
expect(btn.textContent).toBe('Commander')
})
it('handles invalid price gracefully', () => {
document.body.innerHTML = `
<div id="billetterie">
<div data-cart-item data-billet-id="1" data-price="invalid" data-max="5">
<button data-cart-minus></button>
<input data-cart-qty type="number" min="0" max="5" value="0" readonly>
<button data-cart-plus></button>
<span data-cart-line-total></span>
</div>
<span id="cart-total"></span><span id="cart-count"></span>
<button id="cart-checkout" disabled data-order-url="/order"></button>
</div>
`
initCart()
document.querySelector('[data-cart-plus]').click()
expect(document.getElementById('cart-total').textContent).toBe('0,00 \u20AC')
expect(document.getElementById('cart-count').textContent).toBe('1')
})
it('works without checkout button', () => {
document.body.innerHTML = `
<div id="billetterie">
<div data-cart-item data-billet-id="1" data-price="10" data-max="5">
<button data-cart-minus></button>
<input data-cart-qty type="number" min="0" max="5" value="0" readonly>
<button data-cart-plus></button>
<span data-cart-line-total></span>
</div>
<span id="cart-total"></span><span id="cart-count"></span>
</div>
`
initCart()
document.querySelector('[data-cart-plus]').click()
expect(document.getElementById('cart-total').textContent).toBe('10,00 \u20AC')
expect(document.getElementById('cart-count').textContent).toBe('1')
})
it('does not post when cart is empty on checkout', () => {
const fetchMock = vi.fn()
globalThis.fetch = fetchMock
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.getElementById('cart-checkout').disabled = false
document.getElementById('cart-checkout').click()
expect(fetchMock).not.toHaveBeenCalled()
})
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
it('shows error message on HTTP error', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 400 })
globalThis.fetch = fetchMock
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
document.querySelector('[data-cart-plus]').click()
document.getElementById('cart-checkout').click()
await new Promise(r => setTimeout(r, 10))
const errorEl = document.getElementById('cart-error')
expect(errorEl.classList.contains('hidden')).toBe(false)
expect(document.getElementById('cart-error-text').textContent).toContain('erreur')
})
it('does not post without order url', () => {
const fetchMock = vi.fn()
globalThis.fetch = fetchMock
document.body.innerHTML = `
<div id="billetterie">
<div data-cart-item data-billet-id="1" data-price="10" data-max="5">
<button data-cart-minus></button>
<input data-cart-qty type="number" min="0" max="5" value="0" readonly>
<button data-cart-plus></button>
<span data-cart-line-total></span>
</div>
<span id="cart-total"></span><span id="cart-count"></span>
<button id="cart-checkout" disabled></button>
</div>
`
initCart()
document.querySelector('[data-cart-plus]').click()
document.getElementById('cart-checkout').click()
expect(fetchMock).not.toHaveBeenCalled()
})
})
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
describe('stock polling', () => {
beforeEach(() => {
document.body.innerHTML = ''
})
function mockStock(stock) {
return vi.fn().mockResolvedValue({
json: () => Promise.resolve(stock),
})
}
it('polls stock URL and updates labels for out of stock', async () => {
const fetchMock = mockStock({ 1: 0 })
globalThis.fetch = fetchMock
globalThis.setInterval = (fn) => { fn(); return 1 }
createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
initCart()
document.querySelector('[data-cart-plus]').click()
document.querySelector('[data-cart-plus]').click()
await new Promise(r => setTimeout(r, 20))
expect(fetchMock).toHaveBeenCalledWith('/stock')
expect(document.querySelector('[data-stock-label]').innerHTML).toContain('Rupture')
expect(document.querySelector('[data-cart-qty]').value).toBe('0')
})
it('polls stock URL and shows low stock warning', async () => {
globalThis.fetch = mockStock({ 1: 5 })
globalThis.setInterval = (fn) => { fn(); return 1 }
createBilletterie([{ id: 1, price: '10.00', max: 20 }], '/stock')
initCart()
await new Promise(r => setTimeout(r, 20))
expect(document.querySelector('[data-stock-label]').innerHTML).toContain('Plus que')
})
it('polls stock URL and shows normal stock', async () => {
globalThis.fetch = mockStock({ 1: 50 })
globalThis.setInterval = (fn) => { fn(); return 1 }
createBilletterie([{ id: 1, price: '10.00', max: 100 }], '/stock')
initCart()
await new Promise(r => setTimeout(r, 20))
expect(document.querySelector('[data-stock-label]').innerHTML).toContain('disponible')
})
it('clamps qty when stock decreases below current selection', async () => {
globalThis.fetch = mockStock({ 1: 2 })
globalThis.setInterval = (fn) => { fn(); return 1 }
createBilletterie([{ id: 1, price: '10.00', max: 10 }], '/stock')
initCart()
for (let i = 0; i < 5; i++) {
document.querySelector('[data-cart-plus]').click()
}
await new Promise(r => setTimeout(r, 20))
expect(document.querySelector('[data-cart-qty]').value).toBe('2')
})
it('does not poll without stock URL', () => {
const fetchMock = vi.fn()
globalThis.fetch = fetchMock
const origSetInterval = globalThis.setInterval
const intervalSpy = vi.fn()
globalThis.setInterval = intervalSpy
createBilletterie([{ id: 1, price: '10.00', max: 5 }])
initCart()
expect(intervalSpy).not.toHaveBeenCalled()
globalThis.setInterval = origSetInterval
})
it('handles stock poll fetch error gracefully', async () => {
globalThis.fetch = vi.fn().mockRejectedValue(new Error('Network'))
globalThis.setInterval = (fn) => { fn(); return 1 }
createBilletterie([{ id: 1, price: '10.00', max: 5 }], '/stock')
initCart()
await new Promise(r => setTimeout(r, 20))
// No crash, label unchanged
expect(document.querySelector('[data-stock-label]').innerHTML).toBe('')
})
})