# Ticket email queue and organiser delivery history

Implemented 2026-11-26 in the served/Git workspace `C:\xampp\htdocs\ZavvionEvents\zavvion-events`.

Bulk offline uploads commit ticket emails to the queue together with orders and tickets. Checkout completion and manual resends use the same queue policy. Web requests never send ticket emails directly. `TicketDeliveryEnqueuer` serialises resends under an order lock and reuses a matching pending email; account access is rechecked under that lock. A notification refresh failure after checkout commit cannot invalidate the completed payment.

`TicketDeliverySender` sends at most one eligible ticket email per invocation. The shared database gate enforces a default 10-second gap after each attempt completes, including across CLI workers and admin send requests. A batch limit controls the total work of a watch run; it does not bypass pacing. Authentication emails, finance exports, alerts, SMS, wallet and PDF records are outside this ticket-email worker.

The worker verifies that order, ticket and event agree, that the order is paid or partially refunded, and that the ticket is issued or checked in. Invalidated jobs become skipped. It reconstructs the existing stable opaque QR credential, registers its hash under an eligibility lock, includes that QR in a self-contained PDF attachment and the email body, and refuses to reactivate a revoked hash. Raw QR credentials are not stored in the delivery log or exposed in organiser reports.

Explicit provider 429 and 5xx responses retry after 60, 120, 240, then 480 seconds, up to five attempts by default. Permanent errors stop. Network exceptions, unknown responses and abandoned claims stop for review because the provider may already have accepted the message. Each payload includes a stable `idempotency_key`; end-to-end duplicate prevention depends on provider support. Review the provider before manually requesting another resend after an unknown outcome.

## PDF attachments and guest ticket links

Newly sent ticket emails attach a single-page admission PDF containing event/date/venue, attendee, section/seat, status, ticket ID and a sharp vector QR. **Open ticket** and **Download PDF** use signed links that work without registration or login, including orders created by bulk upload with no user account. Existing emails keep their original URLs; new or subsequently resent messages use the guest links.

`GuestTicketAccess` binds each link to one ticket and its existing stable QR hash using a domain-separated HMAC. It requires a non-placeholder QR signing secret of at least 32 characters, an active persisted QR credential, an eligible ticket/order, and consistent ticket/order/event IDs. Guest reads never create or restore credentials. Cancellation, refund or QR revocation disables both the view and download. Account APIs retain their normal authentication. The guest projection omits order IDs, customer contact information, account data and payment details.

Guest view/download responses are private, non-cacheable, no-referrer and noindex. The standalone responsive page has no account navigation, third-party assets or authentication scripts. Anyone holding the emailed link can read that individual ticket, so recipients should keep it private. The ticket's existing QR signing secret must remain stable; do not rotate it merely to enable this feature without the existing QR rotation plan.

The confirmed relay contract supports one singular `attachment`, so it now carries the PDF. QR remains visible in the email through the existing public QR image URL. No unverified plural attachment field is sent. Production `APP_URL` must be a public HTTPS URL; development HTTP URLs must use loopback hosts. Invalid guest-link configuration leaves emails queued without attempts, credential registration or transport. PDF generation uses native PHP and the existing QR package, with no added production dependencies, remote file fetching or runtime browser requirement.

Current PDF font limitation: visible text uses Helvetica/WinAnsi, supporting Latin accents and available transliteration. Sinhala, Tamil, CJK and other unsupported scripts may appear as question marks; complete original event/attendee values remain in PDF metadata and display correctly in the Unicode guest HTML page. Full complex-script PDF typography requires an approved embedded-font renderer/font asset change. Long PDF fields wrap within fixed bounds and may end in an ellipsis; complete values remain on the online ticket.

Validation for this addition: 135 focused tests / 698 assertions passed. The full suite ran 1,076 tests / 5,182 assertions with no errors, the same five documented unrelated failures and two skips. Guest-service tests cover accountless access, wrong ticket, HMAC tampering, key rotation, missing/revoked QR hashes, unpaid/refunded/cancelled/void tickets and cross-event corruption. A synthetic accountless loopback HTTP fixture executed the real public handler: view200, PDF200 with valid MIME/PDF bytes, tampered404, no-store/no-referrer, no session cookie or account link. Apache invalid-link view/PDF requests also returned404 with effective no-referrer. Standard and long-detail PDFs were rendered with Poppler and visually inspected; the rendered QR decoded to the original token. Actual provider inbox/attachment validation and authenticated mobile browser review remain deployment checks. No actual ticket credentials, customer emails or database records were changed during verification. No additional schema migration is required beyond the queue migration above.

## Organiser workspace

Open **Ticket deliveries** at `organiser.html#deliveries`. Organiser owners, admins and permitted event managers use the existing `orders.manage` access boundary. The server resolves the organiser from the authenticated workspace; query parameters cannot select another organiser.

The page shows queued, sent, detected-open and failed totals, event/status filters, recipient, ticket, attempts, next retry, safe error details and pagination. Refresh retrieves current data. Workspace switches immediately clear old data and discard stale responses.

**Sent** means the HTTP provider accepted the message. It does not confirm inbox placement or final delivery; this provider contract has no signed delivered/bounce events. Older sent records may have no timestamp and may include historical local adapter simulations. **Open detected** means the tracking image loaded. Image blocking, email scanners, caching and privacy proxies can hide or create opens; this is not proof a person read the email.

## Installation and operation

1. Apply `migrations/M261126120000AddPacedTicketDelivery.php` through the normal migration runner, or execute the complete forward-only `migrations/sql/M261126120000AddPacedTicketDelivery.sql` against the intended database. Require `PACED_TICKET_DELIVERY_SCHEMA_READY`. The migration adds seven log columns, the due index and a singleton pacing table. It preserves existing recipients and statuses. MySQL DDL auto-commits; take the normal deployment backup and apply during a quiet window. Runtime schema repair does not replace this migration.
2. Set the existing HTTP provider endpoint and bearer token securely in the deployment environment. Keep the existing QR signing secret stable. `log` and `local` deliberately retain emails as queued and report zero sent. Never place real credentials in Git.
3. Set `TICKET_DELIVERY_INTERVAL_SECONDS=10` and `TICKET_DELIVERY_MAX_ATTEMPTS=5`, or use the provider's approved lower sending rate. The interval is clamped to 1–3600 seconds and attempts to 1–10.
4. Review the existing backlog before enabling the provider or schedule; eligible old queued ticket emails will also be processed.
5. Schedule the bounded command below every minute using cron or Windows Task Scheduler. Use the project directory as the working directory and an appropriate local PHP binary. The database gate also protects overlapping invocations. No scheduler or production environment changes were installed by this implementation.

```text
php bin/send-ticket-deliveries --watch --seconds=50 --limit=50
```

On this XAMPP workspace, PHP is `C:\xampp\php\php.exe` (8.5.13); the preferred `C:\xampp9\php\php.exe` is absent. For a single paced tick:

```text
C:\xampp\php\php.exe bin\send-ticket-deliveries --limit=1
```

Optional open reporting is disabled by default. To enable it, set `EMAIL_OPEN_TRACKING_ENABLED=true`, an independent random `EMAIL_OPEN_TRACKING_SECRET` of at least 32 characters, and a public HTTPS `APP_URL`. Keep that secret stable while historical messages need tracking. Include the collection in the site's privacy notice before enabling it. Tracking records only the first image-load timestamp, without IP or user-agent data; safe timestamps and attempts are included in customer privacy exports. The endpoint returns a fixed, non-cacheable GIF for valid and invalid requests. Apache permits cross-origin loading only for this image route.

Pacing does not fix unauthenticated senders or poor reputation. Verify SPF, DKIM, DMARC and From-domain alignment with the actual mail provider, and monitor provider throttling/bounces. See [Google's sender guidelines](https://support.google.com/mail/answer/81126) and [Apple's explanation of Mail Privacy Protection](https://support.apple.com/guide/icloud/use-mail-privacy-protection-mm90f7d05c96/icloud).

## Ticket layout (2026-12-03)

- Email, signed guest web views, and authenticated account print views share the same ticket card: full event artwork on the left, opaque white admission details and QR on the right, without a decorative outer frame or added artwork text. Details never overlay the uploaded artwork. Mobile panels stack; narrow phones give the QR its own full-width row.
- The event's existing `ticket_background` upload remains the artwork source. Guest enrichment selects only current-event, active, clean, nondeleted media. Stored relative upload paths resolve consistently through `APP_URL`, including subdirectory XAMPP installations. The supplied reference is a layout reference, not a replacement event upload or admission credential.
- PDF attachments and guest downloads embed the same local uploaded artwork without network requests. Queue delivery now carries the event-scoped ticket type; account ticket-type aliases render consistently. The bounded native loader accepts RGB/grayscale JPEG and noninterlaced 8-bit PNG (including palette/transparency), with a 5 MB / 8 million pixel limit. WebP requires PHP GD. Missing, remote-only, unsupported or oversized artwork leaves the artwork area plain white. The existing Latin/WinAnsi PDF font limitation remains; web/email preserve Unicode.
- PDF QR remains vector with its white quiet zone. Email QR remains the existing public PNG (or CID fallback); the singular email attachment remains the PDF. Guest access, scanner credentials, signing, eligibility and delivery pacing are unchanged.
- Validation: 70 focused tests / 425 assertions pass under PHP 8.2.12; changed PHP syntax passes. Full suite: 1,129 tests / 5,639 assertions, the same five known unrelated failures, two skips, no errors. Chrome checks at 320/390/768/1480 px found no horizontal overflow. Desktop/mobile web and email HTML previews, normal/long-detail/artwork PDFs were rendered and visually inspected, and all rendered QR codes decoded. Synthetic guest HTTP view/PDF returned 200 and tampered access returned 404, retaining no-store/no-referrer. No real emails, production data, secrets, dependencies or deployment settings changed. Actual Gmail/Outlook inbox rendering remains a deployment check.

## Validation and current local state

- The additive SQL was applied twice to the loopback development database; both executions returned READY. All 199 existing delivery rows were retained. The actual mixed-collation organiser report and admin summary execute successfully.
- Current local provider remains `log`; a real CLI tick reported zero processed/sent. There are 16 existing queued ticket emails. No customer emails were sent, no real credentials changed, and no sending schedule was installed.
- Focused delivery, QR, bulk import, privacy and route tests: 119 tests, 567 assertions passed. Changed PHP files and both organiser JavaScript files pass syntax checks.
- `tests/fixtures/ticket-delivery-mysql-smoke.php` passed using connection-scoped temporary tables and a fake transport: pending enqueue reuse, mixed-collation queries, pacing, reentrant lease rejection, QR hash registration and reporting. It performs zero HTTP requests and changes no real queue rows. Independent multi-process contention and actual provider responses remain deployment checks.
- Apache serves the updated organiser page; anonymous history requests return 401; the tracking endpoint returns the same 42-byte GIF with `no-store` and `Cross-Origin-Resource-Policy: cross-origin`.
- Automated view behavior checks cover escaping, filter races, context switches, loading/error/empty states and disabled tracking. Browser automation reported its access host unavailable, so authenticated visual/mobile QA remains manual.
- The full regression suite retains the five documented unrelated failures in box-office defaults, customer sign-in copy (two), reserved-seat section tabs and the legacy stable-QR source-format assertion. See `.project-status/ticket-delivery-validation.json` for the latest full-run counts.
