# Shared online checkout

## Entry point and responsibilities

`Payment::przelewy24_initiate_payment()` handles group lessons (`z`), individual
lessons (`i`), passes (`k`), pass bundles (`b`), course enrollment (`p`),
section-period payments (`c`), account balance (`s`), rentals (`r`), skate covers
(`g`) and gift vouchers (`v`). Its existing arguments remain compatible;
`accessToken` and `expectedAmount` are optional checkout inputs. Controllers
validate POST/CSRF, select the authorized purchase and handle the returned URL
or error. All types use the same initiation, code claim, receipt snapshot and
P24 registration flow. There is no separate voucher or class-order initiator.

The P24 sessionId is always a string in registration and verification payloads
and their signatures, even when a refreshed PDO payment row provides an integer
ID. Amounts are integer cents. Registration tests validate these JSON types and
the signature against the provider contract.

`prepareCheckout()` resolves a small internal context containing the target
model, nominal amount, discount scope, participant/buyer, P24 description and
reference, return URL and optional balance items. Product-specific rules stay
here or in the target model. Model reads and writes use the payment's injected
PDO connection. Migration 20261013160000_add_payment_refund_tracking.sql adds
refund tracking and independent balance snapshots. No configuration or external
file changes are needed.

Guests may access only a voucher order whose token hash matches. Account
checkouts verify the purchasing account and ownership/parent relationship.
Rentals and skate covers require an approved order and their existing domain
permissions. Already assigned ordinary purchases cannot start another payment.
Voucher/order locks refresh their current state. Paid-payment checks use current
locking reads so concurrent confirmation cannot be hidden by an older snapshot.

## Preparation and reservation

The confirmation page displays a read-only RollPoints estimate below the final
discounted amount when the program is enabled and the payment would earn at
least one point. `RollPointsPayment::checkoutPreview()` reuses receipt eligibility
and the earning rate at preview time. Members see the expected points; nonmembers
see an invitation to join before paying, opening the program in a separate tab
to preserve checkout. Both variants include a small receipt-time qualification,
without campaign names, dates or other promotion details. Invalid discount
previews, zero-point purchases, voucher redemptions, balance payments and
ineligible passes/late single lessons show no estimate. The payer determines
membership, including purchases for children; voucher purchases use the normal
owner/unique guest-email resolution rather than the current browser login.
This preview creates no payment, code reservation, persisted snapshot or point grant and
does not reserve a rate. Confirmation retains the existing receipt-time rules.
No migration, configuration or external file operation is required.

Checkout starts one database transaction. The target is refreshed and required
locks acquired before price calculation. Voucher and class-order preparation
closes their earlier unpaid online attempts; a rejected replacement rolls this
back. Other types retain their existing attempt-replacement behavior.

`savePaymentWithPromoCodeUsage()` is the common persistence mechanism, including
its existing transaction/savepoint support. With checkout context it locks and
refreshes an ordinary code before repeating validity, usage, participant/account
and target checks and recalculating the payable total. Group/individual codes,
pass restrictions and voucher purchase targets keep their established meanings.
Legacy fixed-value precedence and percent arithmetic remain unchanged.

Invalid, unavailable or non-applicable selected codes block both preview and
confirmation instead of silently charging the nominal amount. The shared error
field tells the customer to correct the selection or remove the discount.
KDR still applies only to direct group and individual lesson payments, with
the configured verification behavior. Course, section, balance, rental and
skate-cover checkout does not gain new discount support.

The supplied `expected_amount` is compared with the recalculated amount in
cents. A changed total rejects the transaction without a new payment, consumed
code or closed previous attempt. Legacy calls without a preview amount remain
valid, except a discounted voucher purchase requires that amount. The same
already-present hidden field is read for all account checkout types.

Buyer NIP and test-email configuration are validated before committing the
payment or single-use claim. The payment, code reservation and receipt source
snapshot commit together. Receipts retain the purchasing account (including
parent billing details), the actual discounted amount and fixed order quantity.
The receipt snapshot is idempotent when the registration method is called.

## Zero amounts and registration

Existing zero-value group/individual lesson, pass/bundle, course, balance and
voucher flows use a paid technical payment without P24. Their existing domain
assignment/activation rules remain: individual expected amount is zero, passes
activate, and a voucher issues its full hours and PDF/email after commit.
Zero course checkout retains its existing payment assignment behavior.
This does not introduce free section donations, rentals or skate-cover sales.
Technical/zero-value payments earn no RollPoints and generate no receipt.

For positive monetary payments, P24 HTTP registration runs after commit.
`przelewy24_trnRequest()` retains its signature, test-recipient resolution,
donation transfer title, return URLs and direct-call support. It never saves
the complete stale payment object again. Its common metadata update locks and
refreshes the current active, unpaid online row, verifies the amount and code,
and writes only buyer NIP, payer identity or the returned registration token.
The token is persisted once; product branches do not repeat its save.

If a concurrent action closes or confirms the attempt, a late registration
response cannot reactivate it, overwrite payment state or return an actionable
payment URL. A failed registration deactivates only an unpaid attempt for every
checkout type. The participant allowance and any single-use marker remain
consumed, even after
failure, deactivation, replacement or recall. Paid rows are preserved
even if registration reports an error after confirmation.

## Confirmation and historical data

P24 registration, callback comparisons and verification signatures use integer
cents through PaymentReceipt::cents(). The incoming signature is checked against
the original notification fields; a one-cent mismatch or invalid signature is
rejected before provider verification.

Confirmation locks the target before refreshing the payment with a current
locking read. After validating the signed P24 notification, local payment state,
assignment, activation and durable events are committed **before** calling
`transaction/verify`. A failed write, deadlock, lock timeout or failed commit
rolls back local settlement and returns HTTP 503 with `Retry-After: 30`, without
accepting the transaction at P24. There is no application retry loop or worker.
PDO exceptions are enabled for this callback only and its previous error mode
is restored afterwards.

An already paid callback must still finish provider acceptance. It reads
`transaction/by/sessionId/{sessionId}` and requires matching session, order ID,
integer-cent amount and currency. Status 2 completes acceptance; status 1 permits
`verify`; unavailable, mismatched, unpaid or returned transactions request
redelivery without changing existing settlement. A failed verification also
checks provider status, covering a lost success response or concurrent acceptance.
A provider failure never rolls back committed money. Replays do not repeat
assignment, activation, loyalty events or purchase notifications, and never
reactivate recalled payments.

Online receipt capture and confirmation participate in local settlement, but
issuance is queued explicitly only after provider acceptance is confirmed,
including on a replay after a process interruption. A Fakturownia failure does
not change P24 acceptance. No callback URL, schema or deployment setting changes.
See `fakturownia-receipts.md` for opportunistic buyer-lock recovery.

### Unlinked refunds

The first accepted assignment wins. Verified extra money remains on the original
P24 payment.id, with is_paid = 1, is_active = 1 and is_refund_required = 1.
Purchase relations and selected receipt items are cleared. Participant, payer,
amount, channel, literal promo code and balance snapshot are retained. The
comment records the reason, original target and preceding payment ID.
Subsequent edits preserve the refund marker and original financial identity.

Superseded voucher attempts follow this rule even when the newer attempt is
unpaid. They never issue hours, a PDF or an email. Duplicate rental/skate-cover payments do
not change the winning order. A first rental/skate-cover payment received after
cancellation or a price change retains linked settlement_required handling.

Reports label these entries **Wpłata niepowiązana – do zwrotu**. They cannot pay
other classes/passes, earn RollPoints/referral benefits or receive an automatic
or manually prepared receipt. Unissued receipt snapshots become excluded and
are omitted from receipt preparation counts. Staff recall the extra payment
through the existing editor and refund money externally. There is no automatic
provider refund, and recall does not modify the winning purchase.

### Balance snapshots

New balance checkout stores balance_items_json independently of receipt
integration. Each entry contains type (group/solo), id_target and amount_cents.
Confirmation locks the account and all original items in deterministic order.
It checks the total and every item before assigning any. Missing, inactive or
already assigned items turn the whole payment into an unlinked refund. There
is no partial assignment or allocation against newer debt.

Historical attempts without a snapshot deliberately retain current-balance
matching: a matching current total permits atomic assignment of currently
unpaid items; a mismatch records an unlinked refund. This agreed fallback can
pay newer debt with the same total.

### Migration and rollout

20261013160000_add_payment_refund_tracking.sql adds payment.is_refund_required
(default 0) and nullable payment.balance_items_json. It is additive and replayable
after a partial application. Historical payments are not reclassified or
reassigned. Once-per-user codes count their entire existing usage history.

Apply the migration before new code through the backed-up deployment runner.
Verify test-next first, then promote production separately. No new configuration,
external files or dependencies are needed. An old application version does not
recognize refund-only money: after such entries exist, rollback must retain the
refund exclusions or stop callback/loose-payment processing until they are
resolved. Do not destructively roll back the schema.

## Verification

Run `tests/rollpoints_checkout_preview_test.php` on a prepared isolated
`RP_TEST_DATABASE`, then repeat with `--disabled`. It checks eligible purchase
types, payer/child and guest identity, nonmembership/withdrawal, discounted cents,
promotional rates, excluded payments, unchanged records and code usage, both
message variants, the small receipt-time note and absence of campaign details.

Run `tests/shared_payment_checkout_test.php` on a database prepared by
`scripts/prepare-rollpoints-tests.php` using `RP_TEST_DATABASE=codex_rollpoints_<name>`.
It exercises every target through real persistence, receipt capture and P24
payload construction, with the HTTP transport replaced by a fake and a temporary
log/PDF root. It covers parent billing, guest tokens, invalid/stale codes,
failed claims, zero-value settlement, invalid NIP and responses arriving after
deactivation or payment confirmation. No provider or queue worker is invoked.

Run tests/payment_confirmation_refund_test.php with receipts enabled and with
PAYMENT_RECEIPTS_ENABLED=0. It covers signed cents, all purchase targets,
sequential/concurrent callbacks, replay/recall, manual winners, refund reporting,
no loyalty/allocation/receipt, frozen/legacy balance and assignment rollback.
HTTP registration and verification are fake; no provider or worker runs.

Also run voucher purchase, ordinary-code checkout/concurrency, account
restriction, P24 registration, KDR, class-order payment, RollPoints, receipt
and request-error regressions. Before promotion, verify a real test-environment
P24 payment and its resulting assignment, receipt and loyalty entry.
