# Payment, Charging, and Rollover

## Latest update: Lauren's ADCM-171 clarifications (2026-10-15)

Sources: Lauren's ADCM-171 replies supplied in the conversation, the supplied
ADCM-171 R3/R4/R5/R6/R10 and AC3/AC11/AC18 snapshot, and Payment Flow
Sections 4 and 5. These decisions supersede earlier open questions below.
No live Jira/Confluence updates were made.

### Clarification-to-code-to-test checklist

| Source / confirmed rule                                                       | Current implementation and change                                                                                                                                                                                                                                                                                            | Verification                                                                                                                                                                                                                                                                                                        |
| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R3: Text uses the same 24-hour window                                         | Retained the shared `ROLLOVER_WINDOW_MS`; no extra Text attribution delay was added.                                                                                                                                                                                                                                         | Display/Text database tests verify no rollover one millisecond before the boundary. Existing tests cover rollover exactly at 24 hours.                                                                                                                                                                              |
| R3/R10: fixed reporting cutoff, even if the job runs late                     | [Rollover service](../src/modules/payments/payment-rollover.service.ts) already supplies `spendCutoff = endedAt + 24 hours`, independently of job time. Clarified the reader contract; no scheduling or arithmetic change was needed.                                                                                        | New Display/Text cases run rollover 45 minutes late. Test-only reporting records include $750 before cutoff, $50 at cutoff and $25 twenty minutes after cutoff. Only $800 is used, yielding a $200 credit on a $1,000 budget. A subsequent run does not read or credit again.                                       |
| R5/R6/AC3: preserve raw overspend; round only balance credit                  | Existing BIGINT-micros calculations and ledger storage already comply. No additional migration or rounding rule was needed.                                                                                                                                                                                                  | Exact unit cases plus Display/Text database cases verify $100 budget / $100.005 spend gives 5,000 micros overspend, zero credit, zero remaining budget and unchanged balance. $99.995 spend gives a 10,000-micro ($0.01) credit and no overspend. Both verify ledger reconciliation and no extra card-charge entry. |
| R3/AC18: Display uses billing-grade reporting, not pacing                     | Retained the authoritative-spend reader boundary and documented the required source explicitly. No reporting table, endpoint or fallback total was invented.                                                                                                                                                                 | Existing database test supplies $800 billing spend while the stored realtime remaining budget disagrees; rollover uses the supplied billing total. This is adapter-level evidence, not live reporting-pipeline verification.                                                                                        |
| R3/AC18: Text uses AdMedia reporting, mapping `line_item.admedia_campaign_id` | The required mapping and source are now recorded. Decimal/integer dollar values must be converted to exact micros at the reporting boundary. The current API schema has no such campaign-mapping field and no AdMedia reporting client; the concrete reporting integration remains pending the forthcoming reporting ticket. | Tests exercise an injected Text spend reader. No live AdMedia response format, mapping creation or reporting read was tested. No speculative schema/API was added.                                                                                                                                                  |
| R4/AC11: Display archive stop is owned by the DSP team                        | Local archive still only sets ARCHIVED + one-time `ended_at`. Payment code does **not** call the DSP/bidder to stop buying. Comment on `lineItemService.softDelete` records DSP ownership (~5 minutes) and that inventing a bidder pause is out of scope.                                                                    | Archive tests cover local state only. Display stop remains DSP acceptance, not API payment acceptance.                                                                                                                                                                                                              |
| R4/AC11: this team must immediately pause Text on AdMedia when archived       | **Implemented via AdMedia entity sync:** archive/pause calls `reconcileAdmediaLineItem` so Search Text remote campaigns go inactive when `ADMIN_SYNC_ENABLED` is on.                                                                                                                                                         | DEV-verify with Admin sync + AdMedia credentials. Local archive alone is not proof if sync is disabled.                                                                                                                                                                                                             |

### Reporting adapter obligations and pending archive work

- The fixed cutoff applies to records received by `ended_at + 24 hours`, not to
  all spend visible when a delayed job happens to execute. Reporting adapters
  must support an as-of-cutoff total through recorded timestamps or a preserved
  snapshot. A current cumulative total read 45 minutes late is not sufficient
  unless it excludes later records. This remains unverified against the real
  Display/AdMedia integrations.
- Display per-win reporting amounts already expressed in micros remain integers.
  Dollar-denominated AdMedia decimals/integers must convert at the boundary using
  exact conversion. Do not use floating-point summation or the pacing counter.
- Text reporting details are deferred to the forthcoming reporting ticket.
  Lauren specified `line_item.admedia_campaign_id`, but creation/population,
  migration details and actual source format still need the real integration
  contract. Do not substitute the advertiser's `admedia_adv_id` for a campaign ID.
- Text archive → AdMedia pause is handled by entity sync (`reconcileAdmediaLineItem`)
  when Admin sync is enabled. Display archive → delivery stop remains DSP-owned;
  do not add a bidder pause from this payment workflow.
- This clarification does not change card retries, funding, campaign time zones,
  existing archive HTTP behavior or ADCM-188 policy.

### Execution evidence for this clarification

API typecheck passed. The VS Code test tool did not discover tests in the
separate API workspace, so the existing npm/Vitest runner was used:

```powershell
npm run typecheck
npm run test -- tests\payment-rollover.unit.test.ts tests\payment-rollover.e2e.test.ts tests\money.unit.test.ts tests\payment-lifecycle.unit.test.ts --silent=true
```

Result: **135 tests passed / 4 files**, duration **18.20 seconds**, including
eight new regression cases for the approved examples and fixed cutoff.
Evidence: session artifact `lauren-171-clarifications-tests.txt`.
The previous full run of 550 tests is historical; the full suite was not rerun
for this comments/tests/documentation-only clarification.
Financial/reporting boundaries remain mocked; no live external acceptance,
production migration, deployment, commit or push occurred.

## Earlier update: Lauren's ADCM-170 payment clarifications (2026-10-15)

This section supersedes conflicting implementation-status and open-question
statements below. Sources are Lauren's replies supplied in this conversation,
the supplied ADCM-170/171 snapshots and Payment Flow document, plus the user's
explicit approval of the cross-cutting micros migration and preservation of
existing campaign flight boundaries. No live Jira or Confluence content was
updated. Earlier test counts remain historical, not evidence for this revision.

### Decision-to-implementation traceability

| Source / approved decision                                                       | Implemented behavior                                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Verification                                                                                                                                                                                                                          |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCM-170 R5/R7: Lauren delegates retry/recovery timing to engineering and Clover | [Timing policy](../src/modules/payments/payment-timing.ts): up to three transient retries after 1, 2 and 4 seconds, respecting a longer provider `retryAfterMs`. [Configured lifecycle jobs](../src/plugins/payment-lifecycle.ts) run recovery on env `PAYMENT_RECOVERY_CRON_SCHEDULE` (live value from `.env`; schema default only if unset) for attempts pending at least `PAYMENT_PENDING_AGE_MS` — lookup only, same attempt key, no second charge. Unknown outcomes stay pending.             | `payment-timing.unit.test.ts`, `payment-lifecycle.unit.test.ts` and retry/recovery cases in `payment-rollover.e2e.test.ts`.                                                                                                           |
| ADCM-170 R7: successful charge confirmed around flight expiry                    | Record confirmed funding, mark the expired item Completed and prevent delivery. Unspent funding follows the existing 24-hour rollover process. No automatic expiry void/refund.                                                                                                                                                                                                                                                                                                                    | Late-confirmation-through-rollover test, existing expiry and completion tests in `payment-rollover.e2e.test.ts`.                                                                                                                      |
| ADCM-170 R5/R8: Pause/Archive during payment                                     | [Workflow](../src/modules/payments/payment-activation.workflow.ts) checks stopped status before submitting/retrying and asks the optional processor cancellation adapter to cancel a known charge. A confirmed cancellation restores reserved balance once and does not send a decline email. An unknown cancellation stays pending. If cancellation is unsupported, successful funding preserves Paused/non-serving or Archived/ended status; archived unspent funding can roll over.             | Pause and Archive cancellation, unsupported/unknown cancellation, stopped retry, reactivation and ledger reconciliation cases in `payment-rollover.e2e.test.ts`.                                                                      |
| Same decision: status/payment race safety                                        | [Finalization](../src/modules/payments/payment-activation.service.ts) checks current status under the advertiser lock and returns `CANCELLATION_REQUIRED` without settling when cancellation must be attempted. The external cancellation call runs after that transaction, never while holding the financial lock. Pause uses the same advertiser lock.                                                                                                                                           | Workflow cancellation tests and full regression; cancelled attempts remain terminal and balance restoration is idempotent.                                                                                                            |
| ADCM-170 R3 / Payment Section 6: Text funding signal                             | `charged_at` remains the funding flag for balance-only, card-only and mixed funding. No separate Admedia notification API or campaign mapping was invented. Further Text integration belongs to ADCM-200.                                                                                                                                                                                                                                                                                          | Existing balance-only and mixed funding tests inspect funding state and processor call counts. Live Admedia consumption is not tested.                                                                                                |
| ADCM-170 R8: Pacific-only MVP campaigns                                          | [Campaign service](../src/modules/campaigns/campaign.service.ts) permits only `America/Los_Angeles` for new campaigns and rejects changes to an existing campaign's time zone. Existing non-Pacific campaigns retain their original flight boundaries, as explicitly approved by the user pending a separate data migration. Existing UI controls already use Pacific/read-only behavior.                                                                                                          | Campaign API tests cover Pacific creation, rejected non-Pacific creation, rejected changes and preserved legacy zones. Calendar/DST tests retain their multi-zone coverage.                                                           |
| ADCM-170 R7/AC6: decline email                                                   | Existing `DspAdvertiser.billingEmail` recipient is confirmed. Missing address/delivery errors remain explicit; no automatic redelivery queue or retry policy was added.                                                                                                                                                                                                                                                                                                                            | Existing notification unit and workflow tests. No live email delivery claim.                                                                                                                                                          |
| ADCM-170 R4: all monetary storage uses signed BIGINT USD micros                  | [Money helpers](../src/lib/money.ts), [schema](../prisma/schema.prisma) and integer funding/rollover arithmetic use 1 USD = 1,000,000 micros. Physical columns use `_micros`; existing Prisma property names remain to avoid needless consumer changes. Includes advertiser balance, line-item budget/bid/remaining/applied/charged/conversion value, ledger amount/overspend, payments/attempts/refunds and shared Text conversion pixels. `revShare` remains decimal because it is a percentage. | Exact micro/int64 boundary tests; populated-data migration tests; funding/rollover tests including one-micro overspend; payment and Text conversion API regression; line-item HTTP dollar-to-micros roundtrip and submicro rejection. |
| User approval: preserve existing dollar API/UI contracts                         | Dollar inputs convert at storage boundaries; stored micros serialize back to dollar numbers. Provider cents and external pixel dollar values remain boundary representations. Non-USD monetary writes and submicro/out-of-range values fail explicitly. Dollar serialization also fails explicitly if the existing numeric JSON contract cannot represent a stored value exactly. No silent FX conversion or precision loss.                                                                       | `money.unit.test.ts`, `line-items.e2e.test.ts`, `payments.e2e.test.ts`, `text-ads-conversion-pixels.e2e.test.ts`; API/UI typechecks.                                                                                                  |
| ADCM-171 R5/AC3 / Payment Section 4: overspend                                   | Lauren confirmed that the platform absorbs overspend; no additional card charge. This existing rule is retained. Raw overspend now persists exactly in micros, including subcent spend.                                                                                                                                                                                                                                                                                                            | Rollover unit/e2e tests, including exact one-micro overspend with no card recharge.                                                                                                                                                   |

### Migration and deployment requirements

- [USD-micros migration](../prisma/migrations/20261015090000_usd_micros/migration.sql)
  scales existing decimal-dollar values exactly and renames/converts the physical
  columns to signed BIGINT. Its preflight fails before monetary DDL for non-USD
  records or values outside the supported range; it does not guess conversion
  rates. NULLs, negative values and zero defaults are preserved.
- [Cancellation migration](../prisma/migrations/20261015090100_payment_cancellation/migration.sql)
  adds the `CANCELLED` ledger status. Earlier payment/rollover migrations remain
  required.
- MySQL DDL is not transactional. Back up the database, stop monetary writers and
  coordinate the API, bidder, pacing, spend-accounting and reporting cutover
  before applying these migrations outside the dedicated test database.
  `FinalSpendReader` now returns `bigint` USD micros, not decimal dollars.
  All other readers/writers of the renamed columns must adopt the same contract.
- Shared card-payment/ADCM-188 storage changed only for monetary compatibility;
  card-validation business rules were not expanded as part of these decisions.
- No bulk time-zone normalization was added. Legacy flight boundaries must not
  be changed without the separately approved migration.
- Migrations were exercised only against the approved dedicated test database.
  Migration SQL was also tested on connection-local temporary tables populated
  with representative existing values, overflow and non-USD cases.
  No development/production migration, deployment, commit, push or live card
  transaction was performed.

### Executed verification for this revision

Final verification ran against the approved dedicated test database after the
cancellation/status race changes and the late-confirmation rollover test:

```powershell
npm run typecheck
npm run test -- --silent=true
```

- API typecheck passed.
- **550 tests passed / 43 files**, duration **282.31 seconds**. The final run
  includes monetary migration, existing API regressions, funding/retry/recovery,
  cancellation, expiry, Pacific restrictions and rollover.
- The first full run found two strict cancellation-callback argument mismatches.
  The workflow was corrected to pass only the documented cancellation contract,
  and the complete suite was rerun successfully. No failing assertions were
  removed or weakened.
- UI typecheck and changed-file ESLint passed earlier in this revision; no new UI
  changes were needed for Lauren's clarifications.
- Existing API ESLint could not run: `eslint.config.js` imports the unavailable
  `@eslint/js` package. This tooling issue was not hidden or addressed with an
  unrelated dependency change. Typecheck and test success are not an API lint
  success claim.
- Formatting and patch whitespace checks passed. Full-run evidence is retained
  in the session artifact `lauren-full-tests-final.txt`; earlier failing runs
  remain historical evidence.

Financial processor, spend-reader and email boundaries are mocked in workflow
tests. These results do not prove live Clover, DSP, Admedia or email acceptance.

### Remaining live-integration boundaries

- The default server still does not provide real activation charge/recovery,
  cancellation or authoritative final-spend adapters. The schedules above run
  only when financial dependencies are explicitly configured; a missing
  integration is not replaced with a fake success or zero spend.
- Clover documents that reusing an idempotency key prevents duplicate charges
  ([Ecommerce payments](https://docs.clover.com/dev/docs/ecommerce-accepting-payments)).
  This does not establish retention duration, replay of the original result
  (including declines) or every in-progress response. The existing saved-card
  provider creates an order on each submission; blindly replaying that helper
  is not proof of an identical original request. Safe original-request recovery
  and the supported cancellation operation still require verified integration.
  No speculative replay, void or automatic refund was wired.
- Confirmed cancellation is implemented behind an adapter contract, not claimed
  as a verified live Clover capability. Missing support is logged and uses the
  approved cannot-cancel outcome; unknown results remain unresolved.
- DSP/Admedia delivery and authoritative final spend, ADCM-200 integration,
  live email and the written
  manual-only replacement-card retry amendment remain separate outstanding
  items. Timing, billing-email recipient, overspend, monetary precision and the
  supplied in-flight expiry/Pause/Archive questions are no longer open product
  questions for this implementation.
- This is not a claim that all three tickets or live end-to-end acceptance are
  complete.

## Historical update: activation events and manual Retry Payment (2026-10-14)

This was the status on 2026-10-14; the 2026-10-15 update above supersedes it where
different. Sources were cross-checked against the supplied
ADCM-170 R1/R5/R6/R7/R8 and Confluence **Payment, Charging, and Rollover**,
**Section 2: Activation Charge**. No live Jira/Confluence changes were made.

| Source                                                               | Workflow and code                                                                                                                                                                                                                                                                                                                                                                                                  | Executed verification                                                                                                                                                                                                                                                     |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCM-170 R1: Activate, creative approval, campaign activation events | Existing routes pass the configured payment dependencies to their services. After the status transaction commits, the [line-item service](../src/modules/line-items/line-item.service.ts) or [scoped event service](../src/modules/payments/payment-activation-events.service.ts) invokes the existing reserve/charge/finalize workflow. Eligibility and previous funding are rechecked under the advertiser lock. | Database/API tests exercise the Activate HTTP route, campaign activation of two items with shared balance, and creative approval making an item eligible. No external charge occurs within the status transaction. Existing default startup has no real payment adapters. |
| ADCM-170 R7: `POST /line-items/{id}/retry-payment`                   | The [route](../src/modules/line-items/line-item.routes.ts) requires session authentication and existing ownership checks. The service permits a previously declined, unpaid item and reuses the documented eligibility/expiry and new-attempt logic. No amount, card details or provider reference is supplied by the UI.                                                                                          | HTTP tests cover successful, declined and unresolved retries; unauthenticated/unowned access; non-failed, pending and already-paid items; concurrency; expired flights; inactive campaigns; unapproved creatives; and missing integration dependencies.                   |
| ADCM-170 R6/R7: avoid duplicate or expired charges                   | Concurrent requests share the advertiser-locked reservation. An expired failed item becomes Completed without a new processor call. An unresolved attempt remains pending; it is not presented as a successful payment.                                                                                                                                                                                            | Concurrent HTTP requests produce exactly one new charge attempt and reconcile the balance ledger. Expiry and eligibility tests prove no extra card call or ledger charge row.                                                                                             |
| ADCM-170 R7: Retry Payment button                                    | The UI line-item detail page shows Retry Payment only for a payment-failed, unpaid item without a pending charge. It disables actions during the request and displays the returned paid, failed, pending or not-charged result. Query mutations do not automatically retry this financial POST; related caches refresh even after an error.                                                                        | UI strict typecheck, changed-file ESLint and formatting passed. No browser interaction or live-card acceptance has been executed.                                                                                                                                         |
| Explicit error handling                                              | Missing configured financial dependencies returns HTTP 503 `PAYMENT_UNAVAILABLE` before another reservation. Pending confirmation returns HTTP 202. A processed definitive decline returns the existing success envelope with the explicit failure message and unpaid detail, not a payment-success claim.                                                                                                         | HTTP assertions inspect status, message, `chargedAt`, `chargePending`, attempt number, processor call count and balance/ledger reconciliation.                                                                                                                            |

### Focused execution evidence

Run from the API root using the approved dedicated test database:

```powershell
npm run typecheck
npm run test -- tests\payment-rollover.e2e.test.ts --silent=true
```

Result: **67 tests passed / 1 file** after the final concurrency, expiry and
eligibility additions. An earlier run of the funding/rollover suite plus lifecycle
timer tests passed **69 tests / 2 files** before those four additions.
Processor, final-spend and email boundaries are mocked in these tests.
API and UI typechecks passed; changed UI files passed ESLint; formatting and patch
whitespace checks passed. The UI production build also passed; Vite reported its
existing large-chunk warning, which was not addressed with unrelated refactoring.

Final API regression, executed after all retry/event changes:

```powershell
npm run test -- --silent=true
```

Result: **513 tests passed / 40 files**, duration **602.52 seconds**, on the
approved dedicated test database. This includes existing campaign, creative,
line-item, targeting, verification and payment regression suites as well as
the new funding, lifecycle and notification coverage. Evidence is retained in
the session artifact `payment-retry-full-tests.txt`. These results supersede
earlier full-suite counts for the current worktree, but do not establish live
Clover, reporting, delivery or email acceptance.

### What still prevents live happy-flow acceptance

- Production startup does not yet supply safe real Clover original-attempt
  charging/recovery and authoritative final-spend adapters. No fake adapter or
  arbitrary-amount saved-card endpoint shortcut was introduced.
- Processor recovery scheduling remains unwired pending the supported lookup
  contract and clarification of "older than a few minutes"/backoff timing.
- Actual DSP/Admedia paid-delivery, spend reporting, start/stop and live decline
  email acceptance remain unverified.
- The user reported PM/TL approval of manual-only retry, but the supplied R7/AC13
  and Payment document still say saving a new validated card retries all unexpired
  failed items. Written approval/source amendment remains outstanding. The manual
  button itself is explicitly documented; no ADCM-188 card-update notification
  behavior was added.
- Previously recorded product questions (including Text attribution window,
  spend cutoff/precision and in-flight end/archive outcomes) remain open. This
  change does not decide them or claim all three tickets complete.

No schema changes, live financial calls, deployment, commit or push were performed
in this update. The existing ADCM-171 migration still needs the normal approved
deployment process; tests applying it to the dedicated test database are not a
production migration.

## Earlier update: independent ticket work after the handoff review (2026-10-14)

This section records the previous implementation status. Only the supplied
ADCM-167/170/171 requirements were used; no ADCM-188 verification changes,
new database fields, fake financial adapters or additional business policies
were introduced in this update.

| Ticket source                                            | Implementation                                                                                                                                                                                                                                                                                                             | Verification and remaining boundary                                                                                                                                                                                                                                                                                                                                               |
| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCM-170 R1: sweep at least every five minutes           | [Lifecycle plugin](../src/plugins/payment-lifecycle.ts) runs the activation batch every five minutes when explicit financial adapters are supplied to [buildApp](../src/app.ts).                                                                                                                                           | Timer tests cover exact frequency, no overlapping runs, error logging, shutdown and test-environment disablement. Database tests cover a future flight becoming eligible at its local start date without another event, and charge-once behavior. Current server startup does not supply real adapters, so live charging is not enabled. Activation event callers remain pending. |
| ADCM-171 R10: hourly rollover job                        | The same plugin registers the hourly rollover batch, which prepares external reporting outside the advertiser transaction.                                                                                                                                                                                                 | Timer tests cover the hourly boundary and failure handling. Required reporting adapters have no default; no zero-spend fallback or new environment flag was added. The real reporting connection remains blocked.                                                                                                                                                                 |
| ADCM-170 R7: failed unpaid flight expires without charge | The activation candidate query also includes Pending payment-failed items. The reserve operation completes expired flights without attempting payment, while unexpired declines stay Pending without automatic retries.                                                                                                    | Database test verifies Pending before expiry, Completed at campaign-local flight end, no charged timestamp and no additional processor call. These unpaid items never become rollover candidates.                                                                                                                                                                                 |
| ADCM-170 R7: no charging after flight end                | The immutable reservation now carries its campaign-local flight-end instant. Each processor call rechecks the clock after any retry backoff.                                                                                                                                                                               | Database test expires the flight during transient backoff: there is no second charge. The pending original attempt is resolved by lookup; a definitive no-record result finalizes decline/Completed rather than guessing the outcome.                                                                                                                                             |
| ADCM-170 R7/AC6: advertiser decline email                | [Notification service](../src/modules/payments/payment-notification.service.ts) uses the existing email infrastructure and [template](../src/lib/email/templates/payment-declined-email-template.ts). The activation/recovery workflow invokes it after a newly finalized decline unless an explicit notifier is supplied. | The user clarified using `DspAdvertiser.billingEmail`. Ownership is checked before selecting it; missing billing email or delivery failure raises an explicit error, without guessing another recipient. Database and sender tests verify the billing address and no duplicate notification on terminal recovery. No email was sent live.                                         |

Executed validation for this update: API typecheck passed; the targeted
lifecycle, notification, funding/rollover, completion and default startup run
passed **72 tests / 5 files**. One initial scheduler assertion recursively compared
the Prisma client and failed; it was corrected to check reference identity
and the rerun passed. The earlier **482 tests / 38 files** full-suite result
predates these additions; it is not a new full-suite run.

The optional lifecycle registration is an explicit composition point for real
adapters, not a feature flag or a claim that a live integration exists.
Schedules do not run in tests. Both timers are cancelled before shutdown waits
for in-flight work. Existing default startup remains unchanged.

Still incomplete from my side: activation event wiring, processor/reporting
adapter integration, recovery scheduling once its contract/timing is resolved,
the manual Retry Payment endpoint/button, and live email-delivery acceptance.
The decline-email recipient/callback wiring is now implemented using the user's
billing-email clarification. These are not all external blockers. Missing external
contracts and unresolved source decisions must remain separate from implementable
work. No unavailable/success-shaped retry endpoint or speculative UI was added.

## Current activation implementation and ADCM-188 handoff (2026-10-14)

This section supersedes historical implementation-status statements below.
It does not claim complete ADCM-167/170/171 acceptance or live integrations.

### Confirmed verification/card handoff

The user supplied the ADCM-188 developer's answers:

- Final advertiser verification is `DspAdvertiser.verified`.
- The validated saved-card reference is
  `dsp_payment_method.provider_payment_method_id`. Existing payment code stores
  the Clover customer reference here and retrieves the latest Active method.
- ADCM-188 owns card validation/save. Activation must not validate the card again
  or request raw card/CVV data. The frontend does not need the provider reference.
- `GET /payments/saved-method` returns masked details. Existing
  `POST /payments/saved-method/charge` charges a supplied amount; it is not a
  replacement for line-item balance/ledger/reserve/finalize orchestration.
- Their current card-update implementation does not notify payment processing:
  the advertiser must explicitly retry after updating/validating a card.

The last answer conflicts with supplied ADCM-170 R7:
"The new card retries every payment-failed line item whose flight hasn't ended."
The user subsequently reported PM/TL approval for manual-only retries and said
the approval will be supplied. The written approval/ticket amendment reference
is still pending. Do not describe the original new-card automatic-retry
acceptance criterion as completed. The tested backend fanout helper has no
production caller; no card-save notification has been added to ADCM-188.

### Implemented from my side

| Source                                           | Persistent code                                                                                                                                                                       | Evidence and boundary                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCM-170 R1; Confluence activation dates         | [serving predicates](../src/lib/serving-status.ts), [calendar helpers](../src/modules/payments/payment-flight.ts), line-item/campaign/creative query mappers and creative SQL filters | Inclusive campaign-local dates, mandatory line-item end, paid delivery gate; SQL filtering occurs before creative pagination/counting. Paid campaigns no longer complete before their local final day; legacy uncharged campaign completion is preserved. External bidder consumption remains unverified.                                                                                    |
| ADCM-170 R2-R6; Confluence balance-first funding | [activation transactions](../src/modules/payments/payment-activation.service.ts), [collection](../src/modules/payments/payment-activation.collection.ts)                              | Advertiser lock; ready rollovers first in the same reserve transaction; signed balance debit and pending card ledger; processor call outside transaction; atomic success or decline restoration; balance-only funding makes no processor call. Existing saved-reference lookup reused, no new schema.                                                                                        |
| ADCM-170 R5-R7                                   | [injected processor workflow](../src/modules/payments/payment-activation.workflow.ts)                                                                                                 | Up to three transient retries with the original attempt/key and injected backoff; unknown results stay Pending; recovery performs lookup rather than another charge; definitive no-record restores balance as a decline. Conflicting terminal outcomes raise an error. Real Clover order reuse/key lookup remains a dependency.                                                              |
| ADCM-170 R7                                      | [lifecycle batch functions](../src/modules/payments/payment-lifecycle-jobs.service.ts), API read/status surfaces                                                                      | Exact Pending message "Payment failed, update your card"; creative review cannot silently clear the decline or trigger payment. Explicit retry/fanout core excludes expired flights, creates a new attempt only after decline and rechecks campaign/creative eligibility. The manual retry HTTP endpoint/button and actual email delivery remain integration work, not completed acceptance. |
| ADCM-171 R9; AC6-AC8, AC17                       | Activation reserve invokes [ready rollover core](../src/modules/payments/payment-rollover.service.ts) before balance calculation                                                      | Database tests cover ready credits before card amount, multiple ready items, the still-open window, mixed balance-ledger reconciliation, rollback and concurrent reservations. AC7 exact example: $250 ready credit against $400 budget leaves $150 card charge. Reporting values are injected, not live.                                                                                    |
| ADCM-171 R10                                     | Lifecycle batch function prepares external reporting before each advertiser transaction, then processes all ready advertisers                                                         | Database batch test covers multiple items and repeat no-op. The hourly production timer remains disconnected until authoritative reporting is supplied.                                                                                                                                                                                                                                      |

Implemented workflow:

```mermaid
flowchart TD
  A[Activation event or sweep caller: production integration pending] --> B[Lock advertiser and recheck item, campaign, dates and attempt]
  B --> C[Apply ready oldest-first rollovers using authoritative spend]
  C --> D[Reserve balance and write balance/card ledger]
  D --> E{Card amount zero?}
  E -->|Yes| F[Set funded timestamp and full remaining budget atomically]
  E -->|No| G[Commit reservation and release lock]
  G --> H[Processor outside transaction with stable attempt key]
  H -->|Transient| I[Up to three retries, same key, injected backoff]
  I --> H
  H -->|Success| J[Lock and atomically finalize paid funding]
  H -->|Decline| K[Lock, mark failed, restore balance, Pending or expired Completed]
  H -->|Unresolved| L[Keep pending until original-key processor lookup]
  L -->|Recorded success| J
  L -->|Definitive no-record or decline| K
  K --> M[Decline notification callback: actual email integration pending]
  K --> N[Explicit advertiser retry: endpoint and UI integration pending]
```

The lookup branch uses the matching success/decline finalization, not a guessed
success or another charge. Archive/Pause changes during processor calls are
not reactivated by successful finalization; expired flights become Completed.

### Executed tests and remaining work

- First timezone/API regression run: **114 tests / 4 files passed**, including
  creatives and line-item API tests.
- Expanded funding/rollover/calendar/completion run: **73 tests / 3 files
  passed** before the final tooltip/decline-preservation additions.
- Final full API regression: `npm run test -- --silent=true` passed
  **482 tests / 38 files**, including the final tooltip/decline-preservation
  additions, on the approved dedicated test database. Earlier 436-test results
  below are historical.
- Final API and UI typechecks passed. Changed-file formatting and patch
  whitespace checks passed. No browser/live
  processor/reporting/DSP/Admedia acceptance is claimed.

From your side, the verified-column and saved-reference location questions are
answered. Still needed: supported same-attempt Clover order reuse and original
key lookup; authoritative Display/Text final-spend contracts; Admedia
pause/start integration; external paid-delivery and Display withdrawal
acceptance; billing precision/Text attribution decisions; and the manual-only
retry approval/reference. The card-update event dependency is removed only
when the source requirement is formally amended to the approved manual-only
behavior.

From my side, after the necessary contracts are available, production adapters,
activation event/sweep registration, recovery scheduling, hourly rollover
registration, decline email delivery and the documented manual retry API/UI
still need wiring and end-to-end acceptance. No fake reporting values, live
card calls, new database changes or undocumented automatic jobs were added.
ADCM-188 verification/card-validation implementation remains the other
developer's ownership. The older Word readiness report is not a current
completion certificate.

## PM-approved card pre-authorization clarification (2026-10-14)

The user supplied the PM decision: enable AVS (ZIP) and CVV rules in the Clover
dashboard; validate with an authorization-only transaction; immediately void
when validation passes and funds need not be held, or when a check fails.
Sources supplied by PM and retrieved during this change:

- https://docs.clover.com/dev/docs/create-pre-authorization
- https://docs.clover.com/dev/docs/ecommerce-refunding-payments

Clover documents `capture=false` for pre-authorization, a temporary hold, and
the distinction between voiding an unsettled transaction and refunding a settled
one. Therefore "no captured payment/deduction" must not be represented as a
guarantee that no temporary pending hold appears or that issuer release is instant.
The pre-auth documentation's 100-cent example is not a mandated verification
amount. This change retains the existing 100-cent amount without inventing a new
amount policy.

Implementation: card validation continues to request `capture=false`, but now
calls the existing provider `voidCharge` immediately rather than `refundPayment`.
The void uses a stable `:void` suffix on the validation-attempt key and the
existing client IP. A declined validation that includes a processor reference
also attempts void and does not save the card. A declined response without a
reference cannot be voided by the current provider contract; no guessed reference
or endpoint was added.

Existing validation success-on-cleanup-failure status policy was not changed
without an explicit business decision. Instead, a failed/unconfirmed void is
recorded in the existing event metadata and the pending-hold warning is now
returned in both `statusMessage` and the card-validation response message.
It is **not** proof of a successfully released authorization. Whether validation
must stay unconfirmed until cleanup succeeds remains an open acceptance question.
Existing reconciliation must not be treated as proof that it retries a failed
validation void.

From the Clover/dashboard owner: enable AVS ZIP and CVV rules and provide sandbox
evidence of matching ZIP/CVV, mismatch/decline behavior, immediate void and
issuer hold release. Clover hosted fields already expose CVV/postal-code inputs;
actual dashboard configuration and processor enforcement have not been verified.
Do not store or add raw CVV to the API. If a failed check leaves a pre-auth whose
reference is omitted from the failure response, the supported recovery/void
lookup must be supplied. This clarification does not resolve activation payment
idempotency recovery or the other ADCM-170/171 integration dependencies.

Executed: API typecheck passed; **45 tests passed** across payment API and Clover
provider suites. New tests assert auth-only request, void instead of refund,
void before card save, referenced decline cleanup/no save and explicit warning
on failed cleanup. Processor calls are mocked, not a live AVS/CVV or void test.
No schema/migration change and no real authorization/charge were performed.
The earlier forwarding Word report predates this PM clarification; its older
refund-cleanup wording is historical, not the current implementation.

## Saved-card charge endpoint review (2026-10-14)

The supplied `POST /payments/saved-method/charge` curl matches an existing
authenticated endpoint. Its body accepts `amount`, `currency` and `description`,
with the required `Idempotency-Key` header and an existing saved payment method.
It is an existing standalone saved-card payment, **not** ADCM-170 line-item
activation funding: it has no line-item identifier, does not apply available
balance/ready rollovers, does not create the line-item funding ledger entries
and does not finalize a line item's `charged_at` or remaining budget.

Corrected its response message to reuse the existing status-aware payment
message helper. Declines and replayed unresolved results no longer receive the
unconditional "Payment created successfully" message. Existing HTTP 201 and
response envelope conventions are preserved; consumers must check `data.status`.
Fresh unresolved payments retain the existing error behavior.

Executed validation: **43 tests passed across the payment API and Clover
provider suites**, including the supplied request shape, sequential replay
without another payment attempt, declined-result messages and unresolved-result
messages. The card-save fixture explicitly uses the existing save token.
Provider calls are mocked; no real charge was made. API typecheck and patch
whitespace checks passed. No database schema or migration change was needed.
This targeted result supplements, rather than re-runs, the earlier 436-test
full-regression baseline.

The curl does not establish same-attempt order reuse or lookup by the original
idempotency key after a lost processor response. Current Clover recovery needs
a known payment ID; automatic ADCM-170 retry/recovery and activation remain
unwired. Do not invoke the public saved-card endpoint internally as a shortcut
for reserve/charge/finalize or submit an arbitrary card charge as line-item
funding.

For an approved test environment only, the equivalent Windows PowerShell
request is below. Supply the actual environment URL and session cookie securely
outside source control. This POST can charge a real card if pointed at a live
provider; it was **not executed** as a real curl during this review.

```powershell
$apiBaseUrl = $env:VITE_API_BASE_URL.TrimEnd('/')
$sessionCookie = $env:DSP_SESSION_COOKIE
$idempotencyKey = '8d2c6d5e-2f5d-4a3a-9d7f-3baf8b7b9c41'
$body = '{"amount":25.00,"currency":"USD","description":"Saved card payment"}'

curl.exe --request GET "$apiBaseUrl/payments/saved-method" `
  --cookie "connect.sid=$sessionCookie"

$body | curl.exe --request POST "$apiBaseUrl/payments/saved-method/charge" `
  --header "Content-Type: application/json" `
  --header "Idempotency-Key: $idempotencyKey" `
  --cookie "connect.sid=$sessionCookie" `
  --data-binary '@-'
```

Keep the key unchanged when checking a replay of that same request; changing
the key creates a different standalone payment request. Sequential replay
coverage is not proof of concurrent line-item charging or processor recovery.

## ADCM-171-v2 implementation handoff (2026-10-14)

Both repositories are on `feat/ADCM-171-v2`. This branch retains the earlier
verification/payment groundwork; it does **not** yet satisfy the complete
ADCM-167/170/171 workflow. This section supersedes earlier rollover status
statements below. No live Jira or Confluence update was made.

Sources: the supplied ADCM-171 snapshot, R1-R11 and AC1-AC18; the supplied
ADCM-170 snapshot, R2/R5; and Confluence **Payment, Charging, and Rollover**,
sections 2, 4 and 5. Requirement labels below refer to those snapshots, not an
independently retrieved live ticket.

### Schema and deployment scope

The only new database columns are:

| Owner    | Column                                                                | Source                          |
| -------- | --------------------------------------------------------------------- | ------------------------------- |
| ADCM-171 | `dsp_line_item.ended_at`, nullable `DATETIME(3)`                      | R2: immutable first end instant |
| ADCM-171 | `dsp_line_item.rolled_over_at`, nullable `DATETIME(3)`                | R1/R6/R8: rollover marker       |
| ADCM-171 | `dsp_payment_ledger_entry.overspend_amount`, nullable `DECIMAL(18,2)` | R5/R6: absorbed overspend       |

See [schema](../prisma/schema.prisma) and
[migration](../prisma/migrations/20261014120000_adcm_171_rollover_state/migration.sql).
The existing ADCM-170 ledger, balance/funding fields and `BALANCE_CREDIT` type
are reused, not recreated. No new table, index, spend source, fee column,
correction mechanism or change to `remaining_budget` precision was introduced.

The normal test setup deployed this migration to the approved dedicated
`admedia_dsp_test` database. Development/production deployment was **not**
performed. The application must deploy the migration before running the new
completion sweep or querying the changed Prisma models.

Money precision follows the existing two-decimal ledger convention; no
speculative higher-precision migration or new financial validation was added.
The calculator preserves raw overspend, but the ledger cannot preserve a
sub-cent raw value. This remains an unresolved reporting/schema contract, not
a claim of raw sub-cent persistence compliance. Production rollover remains
unwired; confirming billing precision is a prerequisite to connecting it.

### Requirement-to-workflow-to-code-to-test checklist

**Core tested** means execution with explicitly injected test billing spend,
not a working live billing integration. **Lifecycle implemented** means the
local API behavior exists; external delivery acceptance remains separate.

| Source                                          | Workflow / implementation evidence                                                                                                                                                                                                                                                                                                                                      | Tests / remaining gap                                                                                                                                                                                                                                                |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R1; Confluence 4 eligibility                    | [collection](../src/modules/payments/payment-rollover.collection.ts) selects only charged Completed/Archived items with no rollover marker                                                                                                                                                                                                                              | [integration tests](../tests/payment-rollover.e2e.test.ts): repeat/concurrent calls, uncharged archive, zero-credit and archived cases. Core tested; no live caller.                                                                                                 |
| R2; Confluence 4 end time                       | [flight helper](../src/modules/payments/payment-flight.ts), [completion service](../src/modules/line-items/line-item-completion.service.ts), [archive service](../src/modules/line-items/line-item.service.ts) set `ended_at` only if null; completion uses inclusive campaign-zone end, archive uses action time; completed-then-archived retains the original instant | [unit tests](../tests/payment-rollover.unit.test.ts) cover DST, midnight transitions, leap/day boundaries and invalid zones/dates. Integration tests cover delayed detection, early/repeated archive and missing completion timestamp repair. Lifecycle implemented. |
| R3; Confluence 4 final spend                    | [rollover service](../src/modules/payments/payment-rollover.service.ts) waits 24 hours, derives committed total through the existing ADCM-170 budget helper, and passes a fixed `ended_at + 24h` cutoff to an explicit `FinalSpendReader`                                                                                                                               | Tests prove the injected billing value overrides realtime remaining budget and late processing does not shift the cutoff. Actual Display billing and Text Admedia adapters, including late-record exclusion, are **blocked**.                                        |
| R4; Confluence 4 archive                        | Local archive status remains visible to existing API eligibility filtering                                                                                                                                                                                                                                                                                              | Immediate Text pause/sync and proof of Display catalog withdrawal within five minutes are **not implemented/verified**; external contracts are unavailable.                                                                                                          |
| R5; Confluence 4 amounts                        | [calculator](../src/modules/payments/payment-rollover.ts) clamps credit to zero, rounds credit half up to cents and calculates absorbed overspend without a second charge                                                                                                                                                                                               | Unit tests cover partial/full spend, overspend, half-cent credit and invalid numeric inputs. Cent-valued overspend is persisted in integration tests; raw sub-cent persistence remains blocked as above. No production spend source or card call.                    |
| R6; Confluence 5 ledger                         | Collection records `BALANCE_CREDIT`, including zero, associates advertiser/line item, records overspend and sets the rollover marker                                                                                                                                                                                                                                    | Integration tests verify credit, zero ledger rows, marker and balance reconciliation for rollover-only sequences. Mixed activation/rollover reconciliation is **not complete**.                                                                                      |
| R7; Confluence 4 atomicity                      | All core writes use the caller-owned transaction: balance increase, remaining reset, ledger entry and marker                                                                                                                                                                                                                                                            | Integration tests verify rollback after a later reader failure and after ledger insertion failure. No external request is permitted inside the reader while the lock is held.                                                                                        |
| R8; Confluence 2/4 serialization                | Service reuses the existing advertiser row lock; collection rechecks eligibility when conditionally marking the item, protecting against stale reads                                                                                                                                                                                                                    | Concurrent real-MySQL test credits once. Serialization with production activation is still **blocked** because its reserve step is absent.                                                                                                                           |
| R9; ADCM-170 R5; Confluence 2 rollover priority | Core accepts the reserve transaction and processes ready rows by oldest `ended_at`, then ID                                                                                                                                                                                                                                                                             | Tests verify ordering and exclusion inside the window. Invocation before actual activation funding is **not wired**.                                                                                                                                                 |
| R10; Confluence 4 hourly job                    | Not implemented                                                                                                                                                                                                                                                                                                                                                         | An hourly money-moving job must not run without authoritative final-spend adapters. No placeholder zero-spend job was added.                                                                                                                                         |
| R11; Confluence 4 completion                    | [completion plugin](../src/plugins/payment-completion.ts), registered in [app](../src/app.ts), sweeps charged non-Archived items every five minutes and updates linked targeting profiles; the legacy sweep excludes charged items                                                                                                                                      | Integration tests cover Active/Paused/Pending, exact local end and uncharged/Archived exclusions. [scheduler tests](../tests/payment-completion.unit.test.ts) cover intervals, test disablement, shutdown and explicit error logging.                                |

### Acceptance-criterion disposition

| ADCM-171 criteria | Current evidence / disposition                                                                                                                              |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AC1               | Core test: committed $1,000 minus injected $800 billing spend credits $200; starting $50 becomes $250, marker set, remaining reset and ledger reconciles.   |
| AC2               | Core test: fully spent item writes a zero-credit row and marker.                                                                                            |
| AC3               | Core test: $100 overspend is recorded, remaining is zero and no card operation exists in rollover. Raw sub-cent persistence is unresolved.                  |
| AC4               | Repeat/concurrent core tests show only one credit.                                                                                                          |
| AC5               | Boundary test: one millisecond before 24 hours does not credit; exact boundary does. No live hourly-job acceptance.                                         |
| AC6, AC7, AC8     | **Pending**: require actual activation reserve/finalize with ready-rollover priority. Ordering/window tests are not substitutes for these charge scenarios. |
| AC9               | Archived eligibility/arithmetic covered by core tests; complete live archive-to-reporting-to-credit flow remains blocked.                                   |
| AC10              | Uncharged archived item does not roll over.                                                                                                                 |
| AC11              | **Blocked**: missing Admedia immediate-pause contract/integration.                                                                                          |
| AC12              | Test: completed/rolled item archived later retains markers and receives no second credit.                                                                   |
| AC13              | Test: completed item archived later retains its original end timestamp; the window does not restart.                                                        |
| AC14              | Charged Paused/Pending items become Completed; post-window credit is covered separately by core tests, not live scheduled rollover.                         |
| AC15              | Three-minute-late completion test records the actual next-day campaign-zone instant.                                                                        |
| AC16              | Core test: $100 Daily over ten days, archived on day four with $350 spend, credits $650.                                                                    |
| AC17              | Rollover-only ledger sum tested; mixed activation/rollover sequences remain **pending**.                                                                    |
| AC18              | Injected money-path value, rather than realtime remaining budget, is used. Production reporting-source acceptance remains **blocked**.                      |

### High-level and detailed workflow

```mermaid
flowchart TD
  A[Charged line item] --> B{Archived or flight ended?}
  B -->|Flight ended, not Archived| C[Completion sweep: Completed and actual local flight-end instant]
  B -->|Archived| D[Archive action: first ended_at only]
  C --> E{24 hours elapsed and not rolled over?}
  D --> E
  E -->|No| F[Wait; do not credit]
  E -->|Yes| G[Authoritative billing / Admedia spend: integration blocked]
  G --> H[Caller transaction and advertiser lock]
  H --> I[Recheck ready items; oldest first]
  I --> J[Committed total minus final spend; credit clamp and half-up cents]
  J --> K[Atomic balance, remaining, ledger and rollover marker]
  K --> L[Activation funding or hourly caller: both not wired]
```

Detailed implemented sequence:

1. Outside tests, the completion scheduler runs at five-minute intervals without
   overlapping sweeps; failures are logged and a subsequent sweep is scheduled.
2. Charged candidates are re-read inside an advertiser-locked transaction.
   Archived/unpaid candidates are skipped; future flight ends are not completed.
3. Flight end is the first instant after the inclusive UTC-stored calendar-date
   label in the campaign's time zone, not job detection time.
4. The first `ended_at` is retained; local line item and linked targeting profile
   become Completed. An early archive records its action time; repeat archive is
   idempotent and a later archive does not restart the window.
5. A future production caller must obtain authoritative Text reporting before
   acquiring the balance lock; no external call may be made under that lock.
6. The caller opens one transaction and invokes the rollover core with its
   explicit final-spend reader. Missing advertisers/reporting failures are
   errors, not zero-spend success fallbacks.
7. The core acquires the shared advertiser lock, selects ready charged
   Completed/Archived items and processes oldest first.
8. The existing budget formula derives the full committed total, including the
   full Daily flight even if archived early.
9. The reader receives the fixed final-spend cutoff; the core does not consume
   the realtime pacing counter.
10. The core computes non-negative whole-cent credit and absorbed overspend,
    conditionally rechecks/sets the marker, resets remaining, increments the
    balance and inserts the ledger row, including zero-credit rows.
11. All writes commit together; any error rolls all writes back. Already-rolled
    items are not credited again. No card call exists in this operation.
12. The hourly caller and activation reserve invocation are pending integrations,
    not executed production steps in this branch.

### Blockers and dependencies for PM / technical lead

| Owner / dependency        | Required input or work                                                                                                                                                                                              | Current safe behavior                                                                                                                                    |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Display billing/reporting | Authoritative money-path source, line-item mapping, recording-time cutoff and money precision; include wins recorded in the archive/catalog gap                                                                     | No production reader; no invented spend table and no zero-spend default.                                                                                 |
| Admedia/reporting         | Spend endpoint/authentication, campaign mapping and cutoff semantics; resolve Jira's open question about a longer Text attribution window                                                                           | Text is tested only with an injected reader. Documented 24-hour core is unchanged; no invented longer window.                                            |
| Admedia/campaign owner    | Immediate archive sync/pause contract, and payment-success/start notification contract from Confluence 6                                                                                                            | Local archive works; external pause/start is not claimed.                                                                                                |
| Payment/Clover owner      | Reuse the same processor order for same-attempt retries; resolve outcome by original idempotency key, including definitive missing/unknown result                                                                   | Automatic charging/recovery stays disconnected. Current saved-card implementation creates a new order per call and recovery requires a known payment ID. |
| API payment workflow      | Reserve/charge/finalize, restore on decline, up to three transient retries with the same key, recovery job, declined email/Pending reason, explicit retry, new-card retry fanout and no charge after expired flight | ADCM-170 groundwork exists, but this runtime flow is incomplete. Do not enable funding without rollover priority.                                        |
| API scheduling            | Hourly rollover caller and ready rollovers inside the activation reserve transaction                                                                                                                                | Core ready/ordering/lock behavior tested; neither money-moving production caller exists.                                                                 |
| DSP/bidder team           | Recorded billing spend and platform-fee formula, paid-delivery enforcement, Display catalog withdrawal within five minutes                                                                                          | API paid-eligibility guard is present; external consumption/timing is not verified.                                                                      |
| Database/reporting team   | Confirm whether billing spend/raw overspend is whole cents; if sub-cent values are required, approve exact ledger/remaining-budget precision and migration scope                                                    | Existing precision retained. Sub-cent raw overspend cannot be claimed preserved by the current two-decimal schema.                                       |
| Verification owner        | Admin approve/reject/reverse writer and verification acceptance evidence                                                                                                                                            | Incoming verification submission/card-validation and real verification gating retained; full ADCM-167 parent is not marked complete.                     |
| Product/source owner      | Resolve the older ADCM-167 extra-charge-on-negative-budget clause against the newer Confluence/ADCM-171 absorbed-overspend rule; confirm campaign-zone changes after payment                                        | No extra overspend charge or undocumented timezone edit lock was added.                                                                                  |

The inclusive campaign-zone activation/serving date predicates are still
outstanding from ADCM-170. The new timezone-correct completion service does not
fix or verify those existing raw-instant predicates or campaign completion.

No new rollover UI was prescribed by ADCM-171, so no speculative billing page,
balance widget or rollover endpoint was added. Existing UI status display is
retained. The ADCM-170 retry-payment UI remains pending with its backend contract.

Defaults and mocks are explicit:

- Documented constants: 24-hour finalization window, hourly rollover requirement
  (not wired), five-minute completion sweep (wired), whole-cent half-up credits.
- New timestamps and overspend are nullable; no fabricated backfill was added.
- `FinalSpendReader` has no default implementation or fallback amount.
- Sample spend, charges/`charged_at`, opening balance ledger and test-only Text
  responses are fixtures, not payment or reporting integrations.
- Clover is disabled by existing test setup; no real card charge is executed.
- Completion timers are disabled by `NODE_ENV=test`; scheduler tests separately
  exercise development behavior using fake timers and a mocked sweep.
- No new retry count, fee percentage, Text window, automatic correction entry,
  environment toggle or database precision policy was invented.

### Validation and remaining acceptance

Full API regression: `npm run test -- --silent=true` passed **38 files,
436 tests**, including the new rollover, archive and scheduler cases, on the
approved dedicated test database. The earlier targeted run passed 71 tests.
An additional scheduler assertion initially failed because it recursively
compared the Prisma client; it was corrected to check reference identity and
passed in the full run.

API Prisma validation, typecheck and changed-file formatting/whitespace checks
passed. Focused API lint could not start because the existing ESLint configuration
imports missing `@eslint/js`, which is not declared in the dependency manifest;
no unrelated dependency change was made. UI typecheck passed; full UI lint
found 11 pre-existing errors in unchanged files. Those unrelated errors were
not modified. Browser, live processor, real reporting, live Admedia/bidder and
mixed activation/rollover acceptance remain unexecuted.

**Scope/completeness verdict:** ADCM-171 lifecycle and transactional rollover
foundations are implemented and tested locally; production money movement and
the combined three-ticket end-to-end flow remain incomplete for the dependencies
above. The old full API result below is the pre-171 baseline, not acceptance of
these new integrations.

## Full API regression execution (2026-10-14)

`npm run test` passed: **35 test files, 383 tests**, after the corrections below.
API typecheck, focused test formatting and whitespace checks also passed.
This result supersedes the database-test execution limits in the earlier handoff,
but does not establish completion of the outstanding activation/rollover workflow.

- The user explicitly approved resetting only local `admedia_dsp_test`. Its old
  applied payment migration conflicted with the incoming verification migration
  (`verified` already existed). The dedicated test database was recreated; the
  development database and environment configuration were not changed.
- Removed the empty, untracked
  `20261013120000_adcm_167_payment_balance_and_line_item_state` migration
  directory, which caused Prisma P3015. No migration SQL was rewritten.
  The current migration chain then deployed through the standard test setup.
- Corrected signup assertions to expect `verified=false` and `NOT_SUBMITTED`,
  including the persisted advertiser flag.
- Corrected paid eligibility fixtures. Display/Text creative tests now assert
  ineligibility before `chargedAt` and eligibility after setting that test state.
  These fixtures simulate finalized payment, not a real activation charge.
- Corrected missing/null end-date create/PATCH assertions to expect the existing
  schema-validation HTTP 400. Business date-window violations still expect 422.
- Clover was disabled in the standard setup; provider unit requests were mocked.
  No real card charge or live bidder/Admedia acceptance was performed.

## Current handoff: safe ADCM-170 continuation (2026-10-14)

This section supersedes the verification-bypass and unpaid-eligibility findings
in the historical audit below. **ADCM-170 is still not complete.**

The user approved continuing independent API/UI work while keeping automatic
activation charging disconnected until the processor retry/recovery contract
is confirmed. Ready rollover integration remains assigned to ADCM-171.
No database deployment, new migration, live card charge or commit was performed
for this continuation.

| Requirement / finding                                                                                      | Current implementation                                                                                                                                                                                                                                                                                                                                    | Limit                                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ADCM-167: only verified advertisers create campaigns; Confluence section 1: rejection takes precedence     | Admin detail now uses the shared verification-state computation rather than returning hardcoded true. Campaign-list UI waits for successful auth, uses state-aware messages and removes the obsolete website gate. Campaign API continues enforcing advertiser verification.                                                                              | Admin approval/rejection workflow still requires its separate owner.                                                                                                                                                        |
| ADCM-170 R1/R4/R7: activation readiness is distinct from successful payment; unpaid items must not deliver | `statusChainOk` remains independent of payment so it can trigger a first charge. `isLineItemEligibleToServe` additionally requires `chargedAt`. Line-item lists/details, campaign child summaries, creative lists/details/attachments and creative SQL eligibility filters use the paid condition. UI shows the payment-not-completed eligibility reason. | These are API eligibility safeguards, not proof that the external bidder or Admedia consumes/enforces them. Existing raw-instant date checks remain; inclusive campaign-zone flight semantics are still outstanding.        |
| ADCM-170 R5/R6/R7: processor-safe retries and recovery                                                     | Automatic activation charging remains unwired. Existing Clover saved-card flow creates an order on every call; existing recovery needs a known provider charge ID.                                                                                                                                                                                        | Backend/payment team must confirm how one attempt reuses its order and how recovery resolves the original idempotency key, including definitive no-record behavior. No guessed endpoint or new retry policy was introduced. |
| ADCM-170 R5 / ADCM-171 R9: ready rollovers before funding                                                  | Not integrated.                                                                                                                                                                                                                                                                                                                                           | Tickets explicitly ship together. Do not reserve balances or enable activation charges without this dependency.                                                                                                             |
| ADCM-170 R2/R8: calculations, required dates and charged/pending edit locks                                | Prior implementation retained.                                                                                                                                                                                                                                                                                                                            | No reserve/finalize/decline ledger writers, retry endpoint/button, card-change fanout or activation sweep were added in this continuation.                                                                                  |

Database-free regression coverage for this continuation:

- Unverified, pending-review, rejected and missing advertisers cannot create
  campaigns; a verified advertiser can create Draft campaigns without a
  separate verified-site prerequisite.
- Admin advertiser detail reflects verified/rejected state.
- An unpaid Active line item can satisfy activation readiness but cannot satisfy
  serving eligibility. Charged Active items can; Paused items cannot.
- Approved creatives attached only to unpaid items are ineligible; one paid
  eligible attachment is sufficient. The API supplies a payment-specific reason.
- The creative database filter requires a non-null charged timestamp.

Validation must use the isolated database-free configuration, not the normal
test setup, which deploys migrations and seeds the database. Browser, MySQL
concurrency, processor and external-delivery acceptance remain unexecuted.

Executed checks: 123 database-free tests passed across seven files; API and UI
typechecks and focused UI ESLint passed. Clover requests were mocked. No test
used the database setup or a real processor request.

## Line-by-line ADCM-167 / ADCM-170 audit

**Verdict: ADCM-167 parent and ADCM-170 are NOT complete.**
This audit supersedes conflicting historical "Done", "Implemented", verification
guard, migration-applied and complete-coverage statements later in this document.
It verifies the current code, not the wording of commit messages or earlier plans.
No runtime code was changed for this audit.

Sources:

- **P:** newly supplied ADCM-167 parent snapshot, 92 lines: signup/verification,
  activation, formulas, budgets, delivery/spend, completion, field locks,
  examples, backend eligibility and three schema additions.
- **T:** supplied ADCM-170 snapshot, 232 lines: summary, R1-R8 and AC1-AC16.
- **C:** the user's payment-flow Confluence text in this conversation,
  **Payment, Charging, and Rollover**, Overview/Lifecycle and sections 1-6,
  including supplied budget/funding/ledger examples.
- Live Jira/Confluence acceptance or ticket state was not verified; these are
  supplied-source references, not claims of a live ticket update.

Status key: **Implemented** = present in current code with stated test limits;
**Partial** = groundwork or existing behavior does not satisfy the whole clause;
**Missing** = required runtime implementation absent; **Exception** = explicitly
approved temporary deviation, not original-ticket completion;
**Other owner** = still open in parent/document coverage, assigned to another
ticket/team; **Conflict** = inconsistent source clauses requiring a decision.
No item below means production acceptance has passed.

### Evidence index (code and tests)

| Evidence | Current implementation / inspected surface                                                                                                                                                                                                                                                               |
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| E1       | API `src/modules/auth/auth.service.ts:152`, `src/modules/advertisers/advertiser.service.ts:89` return hardcoded `verified: true`. `src/modules/campaigns/campaign.service.ts:111` and `src/modules/payments/payment.service.ts:421` have bypass comments, not verification guards.                       |
| E2       | UI `src/features/campaigns/pages/CampaignsPage.tsx:56`, `CreateCampaignPage.tsx:58` guard false/loading/errors; required boolean API response schemas. Real false advertiser state is not supplied by E1.                                                                                                |
| E3       | API `src/modules/line-items/line-item.schema.ts:145`, routes/types/service; UI AddLineItem/details form/helper/payload types enforce new input end dates and remove no-end controls. Existing nullable DB rows are not backfilled.                                                                       |
| E4       | `src/modules/payments/payment-budget.ts:11` computes Lifetime/Daily totals; `:51` computes balance/card portions using decimal half-up. Search of all API source finds definitions only, no runtime caller.                                                                                              |
| E5       | `src/modules/line-items/line-item-payment-lock.ts:4`; patch service initial check and transaction-time recheck after advertiser row lock; query exposes charged/pending state.                                                                                                                           |
| E6       | UI `LineItemDetailsForm.tsx` disables eight fields; `LineItemDetailPage.tsx:165` omits locked fields from PATCH; locked Yup schema excludes those fields so unchanged locked dates do not prevent a name edit.                                                                                           |
| E7       | `prisma/schema.prisma` and `prisma/migrations/20261013183000_adcm_170_activation_payment_ledger/migration.sql`: five payment columns, ledger/enums/indexes/FKs; no `verified` mapping, no ledger writer or charged-state writer.                                                                         |
| E8       | `src/lib/serving-status.ts:164` / `statusChainOk:171` use raw timestamps and campaign dates; `line-item.query.ts:357` derives eligibility without payment state. `line-item.service.ts:535` activates by creative-derived status, not by charging.                                                       |
| E9       | `src/modules/payments/providers/payment-provider.ts` takes `sourceToken` plus customer IP; recovery reads by processor payment ID, not idempotency key. Existing manual payment service is not line-item activation billing. Clover adapter distinguishes FAILED/UNKNOWN but maps auth errors to FAILED. |
| E10      | Existing `src/lib/serving-status-completion.ts:82` completes Active/Pending by raw end timestamps; it excludes Paused, does not set `ended_at` and is not a rollover job.                                                                                                                                |
| E11      | CompanySettingsPage manages company name and website verification; BillingPage reads existing manual payment records. These do not implement advertiser card/ID review or new line-item-ledger billing history.                                                                                          |
| E12      | `tests/payment-budget.unit.test.ts` (30), `line-item-payment-lock.unit.test.ts` (36), `line-item-payment-patch.unit.test.ts` (7), inherited `campaign-verification.test.ts` (3). All 76 re-executed successfully with no DB setup.                                                                       |
| E13      | `tests/line-items.e2e.test.ts` updated for mandatory dates, not executed. Creative attach/detach service unchanged; no new payment lock in those actions, but paid-item DB/browser acceptance not executed.                                                                                              |

### ADCM-167 parent: every described clause and example

| ID  | Source clause                                                                    | Status and exact gap / evidence                                                                                                                                                    |
| --- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| P01 | Advertiser signs up                                                              | Partial / existing signup; not a new payment-verification workflow. Signup end-to-end not executed in this audit.                                                                  |
| P02 | Billing information collected during advertiser verification                     | Other owner / signup-verification handoff; E11 does not implement this card/ID workflow.                                                                                           |
| P03 | Card not charged at verification                                                 | Other owner / no save-only card flow verified. Existing manual payment route charges a token and is not evidence of this requirement.                                              |
| P04 | Advertiser identified as verified                                                | Exception: E1 hardcodes true. No authoritative stored verification/read/write flow.                                                                                                |
| P05 | Only after verification can advertiser create campaigns in UI                    | Exception: E2 gates the boolean, but E1 always returns true and API enforcement is bypassed. Verified website enforcement remains, but is not advertiser verification.             |
| P06 | First backend status-chain eligibility and charged_at null trigger card charging | Missing: E8 activation never invokes E4/E9 for line-item charging.                                                                                                                 |
| P07 | Charge committed total, set charged_at now, begin delivery only on success       | Missing: no writer/finalizer; E8 does not require payment success for eligibility.                                                                                                 |
| P08 | Apply MIN(balance,total), card MAX(0,total-applied), deduct applied              | Partial: E4 computes all three correctly; no persisted deduction or card request.                                                                                                  |
| P09 | New advertiser balance zero; full card amount                                    | Partial: E7 zero default and E4 formula; actual database migration/charge not executed.                                                                                            |
| P10 | Lifetime full amount                                                             | Implemented calculation only in E4/E12; not wired to activation.                                                                                                                   |
| P11 | Daily amount times inclusive flight days                                         | Implemented calculation only in E4/E12; not wired to activation. UTC stored date-part counting is not campaign-zone eligibility.                                                   |
| P12 | Daily no-end removed; every line item requires end_date                          | Implemented new create/PATCH input validation and UI in E3/E12. Partial for pre-existing null-end rows: nullable schema remains, no backfill or payment eligibility rejection yet. |
| P13 | Deduct advertiser_cost on each won impression                                    | Other owner / DSP billing dependency; no remaining-budget update exists in this API source.                                                                                        |
| P14 | advertiser_cost = supply_cost / (1-platform_fee)                                 | Other owner / DSP. Formula not implemented/tested here.                                                                                                                            |
| P15 | Completion moves positive remaining budget to advertiser balance and zeroes item | Other owner / ADCM-171; missing runtime.                                                                                                                                           |
| P16 | Negative remaining budget charged as absolute value ("never happen")             | Conflict: C4 / ADCM-171 prohibit another charge and absorb overspend. Neither path implemented; cannot silently mark this clause done.                                             |
| P17 | Channel locked after charge                                                      | Implemented conditional guard/UI in E5/E6; no charge writer currently produces this state.                                                                                         |
| P18 | Budget amount, type, bid strategy, bid amount, pacing, start/end dates locked    | Implemented exact seven budget fields plus channel in E5/E6/E12. No extra subtype/priority locks. DB/UI behavioral tests outstanding.                                              |
| P19 | Example 1000 budget / 50 balance -> applied 50, card 950, balance 0              | Implemented arithmetic test E12; real money movement missing.                                                                                                                      |
| P20 | Example 200 budget / 500 balance -> applied 200, card 0, balance 300             | Implemented arithmetic test E12; zero-processor-call/persisted-balance path missing.                                                                                               |
| P21 | Shared eligibility computed on backend: Active item/campaign and today in dates  | Partial E8; existing backend predicate present, but no campaign-local inclusive day semantics or activation charge caller.                                                         |
| P22 | verified BOOLEAN NOT NULL DEFAULT FALSE                                          | Exception / not mapped or migrated. Hardcoded true was user-approved temporarily, not original default-false schema compliance.                                                    |
| P23 | available_balance DECIMAL(10,2), not null, default zero                          | Implemented E7 schema + migration file on 170, not in committed 167 and not applied by assistant.                                                                                  |
| P24 | charged_at nullable DATETIME                                                     | Implemented E7 on 170, not in committed 167. DATETIME(3) follows repository precision. No timestamp writer or DB deployment evidence.                                              |

### ADCM-170: each requirement, decision branch and failure path

| ID  | Source clause                                                                                | Status and evidence / missing logic                                                                                                                       |
| --- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| T01 | R1 first shared status_chain_ok and charged_at null                                          | Missing charge trigger; existing shared helper only (E8).                                                                                                 |
| T02 | R1 line item Active; approved creative prerequisite                                          | Partial: existing creative-derived activation; not a payment trigger or paid delivery guarantee.                                                          |
| T03 | R1 campaign Active                                                                           | Existing predicate E8; not wired to payment.                                                                                                              |
| T04 | R1 flight inclusive/current campaign-zone date                                               | Missing; raw timestamp windows are not local calendar-day boundaries.                                                                                     |
| T05 | R1 Activate event charges when eligible                                                      | Missing.                                                                                                                                                  |
| T06 | R1 creative approval event charges when eligible                                             | Missing.                                                                                                                                                  |
| T07 | R1 campaign activation event charges when eligible                                           | Missing.                                                                                                                                                  |
| T08 | R1 five-minute sweep catches future-dated items; always server-side                          | Missing payment sweep. Existing status/expiry jobs are not activation billing.                                                                            |
| T09 | R2 Lifetime / inclusive Daily / half-up whole cents                                          | Implemented standalone E4/E12; no activation integration.                                                                                                 |
| T10 | R2 balance first; card only remainder; new balance subtraction                               | Implemented standalone E4/E12; actual reserve/debit/charge missing.                                                                                       |
| T11 | R2 examples: 1000 with 0/50/1000/1500 balance, Daily100 x10                                  | All arithmetic examples tested (E12); no card/ledger/balance persistence test.                                                                            |
| T12 | R3 zero remainder skips processor, deducts balance and sets charged_at                       | Missing runtime. Returning zero from E4 is not completion of R3.                                                                                          |
| T13 | R4 BALANCE_APPLIED and LINE_ITEM_CHARGE rows for all movements                               | Partial E7 schema; no inserts.                                                                                                                            |
| T14 | R4 card processor reference; funding trace; sum equals balance                               | Missing ledger writer/reconciliation/invariant.                                                                                                           |
| T15 | R4 success timestamp now and remaining_budget total, agreed precision                        | Partial E7 DECIMAL(18,2) approved/schema/migration; successful writer missing, bidder contract unexecuted.                                                |
| T16 | R5 short reserve transaction locks advertiser                                                | Missing money reserve. E5 only locks edits and cannot be counted as charge serialization.                                                                 |
| T17 | R5 ready rollovers before amount calculation                                                 | Missing; ADCM-171 dependency. Source points to 171 R7 but supplied rollover scheduling clause is R9.                                                      |
| T18 | R5 reserve deducts balance, writes balance entry and pending card entry/key                  | Missing.                                                                                                                                                  |
| T19 | R5 zero charge finalized in same transaction                                                 | Missing.                                                                                                                                                  |
| T20 | R5 external call with key and without held DB lock                                           | Missing automatic saved-card workflow. Manual payment calls are not this requirement.                                                                     |
| T21 | R5 success finalization in second short transaction                                          | Missing.                                                                                                                                                  |
| T22 | R5 decline FAILED, balance reversal, R7 fallback                                             | Missing.                                                                                                                                                  |
| T23 | R5 pending recovery after few minutes looks up idempotency key                               | Missing provider operation/job; age threshold unspecified. E9 lookup requires charge ID.                                                                  |
| T24 | R5 processor success + DB failure eventually finalized, never lost/duplicated                | Missing recovery implementation and failure-injection test.                                                                                               |
| T25 | R6 check charged_at and ledger under advertiser lock, at most one charge                     | Missing reserve/finalizer; a nullable column or unique processor key alone is insufficient.                                                               |
| T26 | R6 line-item ID + attempt-number idempotency key                                             | Partial E7 stores key/number; no automatic generator or persisted attempt policy. Existing manual-payment key is not a line-item key.                     |
| T27 | R6 automatic retries reuse same attempt/key                                                  | Missing.                                                                                                                                                  |
| T28 | R6 advertiser retry after decline increments attempt                                         | Missing; no new retry endpoint/button.                                                                                                                    |
| T29 | R6 concurrent same-advertiser reserve serializes, balance not double-applied                 | Missing real reserve. Sequential E12 math is not DB concurrency evidence.                                                                                 |
| T30 | R7 transient errors up to three automatic backoff retries                                    | Missing; retry count interpretation/backoff schedule require confirmation.                                                                                |
| T31 | R7 unresolved -> recovery; confirmed no processor record -> decline                          | Missing; do not restore balance merely on a timeout/unknown response.                                                                                     |
| T32 | R7 definitive declines never automatically retried                                           | Missing line-item decline policy.                                                                                                                         |
| T33 | R7 decline charged_at null, reserved balance restored, no delivery                           | Missing restoration/gating.                                                                                                                               |
| T34 | R7 Pending + exact "Payment failed, update your card" tooltip                                | Missing status reason and UI tooltip. Existing Pending creative messages are not payment failure.                                                         |
| T35 | R7 advertiser emailed on decline                                                             | Missing payment-failed notification path.                                                                                                                 |
| T36 | R7 Retry payment UI + POST /line-items/{id}/retry-payment                                    | Missing both.                                                                                                                                             |
| T37 | R7 new validated card retries all failed unended items, new attempts                         | Missing saved-card event and per-item retry orchestration.                                                                                                |
| T38 | R7 ended before successful charge -> Completed and never newly charged                       | Partial old completion E10; wrong local end semantics/no charge-recovery expiry policy.                                                                   |
| T39 | R8 charged/pending field locks: channel, amount/type, bid strategy/amount, pacing, start/end | Implemented conditional E5/E6 with field-specific API rejection; E12 mocks recheck between initial and locked reads. Charge path/state generation absent. |
| T40 | R8 name remains editable                                                                     | Implemented E5/E6 and mocked save/targeting rename for charged legacy/normal rows. Browser/DB unexecuted.                                                 |
| T41 | R8 creative attachment/detachment stays available                                            | Existing unchanged actions, no new payment locks (E13). Paid/pending regression execution outstanding.                                                    |

### All ADCM-170 acceptance criteria: no inferred passes

| Criterion                                                               | Current result                                                                                                                         |
| ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| AC1 no balance -> card1000, charged timestamp                           | Partial arithmetic; activation/card/DB NOT executed/implemented.                                                                       |
| AC2 balance50 -> card950, balance0                                      | Partial arithmetic; real debit/charge missing.                                                                                         |
| AC3 balance1500 -> no request, balance500, charged and ledger           | Partial arithmetic; no-call/finalization/ledger workflow missing.                                                                      |
| AC4 pause/resume/no double charge                                       | Missing line-item idempotent executor/test.                                                                                            |
| AC5 inactive/future -> no premature charge                              | Existing predicate partial; payment eligibility/event behavior unimplemented.                                                          |
| AC6 decline restores50, charged null, Pending/tooltip/email/no delivery | Missing end-to-end decline path.                                                                                                       |
| AC7 balance500/two400 -> applied500/card300 either order                | Arithmetic tested only; real concurrent transactions missing/unexecuted.                                                               |
| AC8 charged fields read-only/rejected clearly                           | Conditional implementation and API unit/mocked tests passed; browser/real DB NOT executed.                                             |
| AC9 uncharged/nonpending fields save normally                           | Guards tested to allow; existing normal writes retained, DB/UI save NOT executed. Existing creative/channel restriction still applies. |
| AC10 ledger funding matches formula                                     | Schema only, no ledger writer.                                                                                                         |
| AC11 campaign-zone tomorrow start charges within five minutes           | Missing sweep and local-date eligibility.                                                                                              |
| AC12 Daily100 x10 =1000                                                 | PASS standalone calculation test; not activation acceptance.                                                                           |
| AC13 manual/new-card retry new attempt                                  | Missing endpoint, UI, hook and attempt policy.                                                                                         |
| AC14 success then DB failure recovered without second charge            | Missing lookup-by-key recovery/failure test.                                                                                           |
| AC15 transient up to3 same-key retries, never duplicate                 | Missing automatic retry/recovery/concurrency implementation.                                                                           |
| AC16 charged or pending date/budget locks                               | Conditional implementation and unit/mocked tests passed; real pending/charged workflow and browser acceptance missing.                 |

### Confluence-only additions and full-parent dependencies

These rows account for document details even when implementation belongs to 171
or another owner. Deferring ownership does not make the parent complete.

| ID/source                  | Required detail                                                                                              | Current state                                                                                                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| C01 Overview/Lifecycle     | Upfront collection only on first deliverable eligibility, spend from prefunded budget, end rollover          | Missing integrated lifecycle; not delivered by manual Make Payment.                                                                                                        |
| C02 section1               | Company Settings billing card/name/address and ID verification; card saved not charged                       | Other owner; E11 website/name form is not this workflow. Signup validation/handoff not tested.                                                                             |
| C03 section1               | Admin verifies/rejects; rejection final except admin reversal                                                | Other owner; no stored advertiser review state or admin reversal verified in payment changes.                                                                              |
| C04 section1               | Only verified advertisers create campaigns                                                                   | Exception E1/E2; currently not genuinely enforced.                                                                                                                         |
| C05 section2               | Inclusive campaign-local flight day boundaries; all three events plus <=5min sweep                           | Missing as T04-T08.                                                                                                                                                        |
| C06 section2               | Ready rollovers used first; inside-24h funds not yet available                                               | Missing 171 integration; no silent skip approved.                                                                                                                          |
| C07 section2               | Funding source balance_applied/card_charged stored; remaining budget initialized                             | E7 columns only, no writer.                                                                                                                                                |
| C08 section2               | Charged once under advertiser lock; per-advertiser charge/rollover serialization                             | Missing money workflow/real concurrency tests.                                                                                                                             |
| C09 section2 Card Declined | Reserve restoration; Pending tooltip/email; automatic vs advertiser retries; no late new charge              | Missing as T30-T38. Success discovered after flight end needs an explicit policy, not invented refund/extra charge.                                                        |
| C10 section3               | Display advertiser cost supply/(1-fee); fee fraction, e.g.0.20                                               | Other owner / DSP/reporting. No spend update or test here.                                                                                                                 |
| C11 section3               | Text spend from Admedia reports, not DSP impressions                                                         | Other owner / 171/reporting; missing integration.                                                                                                                          |
| C12 section4 When Ends     | Charged nonarchived Active/Paused/Pending -> Completed at local flight end, start of next local day          | Other owner / 171. E10 handles Active/Pending only and raw timestamp expiry, no ended_at.                                                                                  |
| C13 section4               | Archive ended_at=archive instant; set once; later archive retains original completed end                     | Other owner / 171; fields/writer absent.                                                                                                                                   |
| C14 section4               | Text archive sync immediately pauses Admedia; Display leaves catalog within5min; intervening wins count      | Other owner / 171/Admedia/bidder; not verified or implemented by these changes.                                                                                            |
| C15 section4               | Never-charged archived item has no rollover                                                                  | Other owner / 171; rollover implementation absent.                                                                                                                         |
| C16 section4 Eligibility   | Completed/early archived + charged + not rolled + >=24h since ended                                          | Other owner / 171; all four predicates still need runtime code.                                                                                                            |
| C17 section4 Final Spend   | At24h MAX(0,total-final spend), include reporting billing-path spend in window, not realtime pacing counter  | Other owner / 171/reporting; missing source contract and implementation.                                                                                                   |
| C18 section4               | Text final spend uses Admedia reporting API; post-rollover spend not collected                               | Other owner / 171/Admedia; missing integration and late-spend tests.                                                                                                       |
| C19 section4 Rollover      | Credit available balance and zero remaining; no negative budgets or additional advertiser charge             | Other owner / 171; missing. Conflicts with P16 extra-charge sentence.                                                                                                      |
| C20 section4               | Platform absorbs overspend, records amount on rollover ledger                                                | Other owner / 171; overspend field/writer not included on 170.                                                                                                             |
| C21 section4               | Record rollover even zero; half-up cents                                                                     | Other owner / 171 runtime missing; E4 math alone does not implement rollover rounding/zero entries.                                                                        |
| C22 section4               | Hourly rollover job (<=1h lag); immediate ready rollover before same-advertiser charge                       | Other owner / 171 + required 170 reserve dependency; neither runtime operation exists.                                                                                     |
| C23 section5               | Every movement row; amounts never edited, entries never deleted, corrections new; only charge status mutable | E7 schema groundwork only; runtime policy missing. Restrict FKs are not ledger amount immutability. Processor-reference finalization must be consistent with this wording. |
| C24 section5               | Available balance equals signed sum of balance entries                                                       | Missing writer/reconciliation/opening-balance handoff; no balance-only writes are implemented.                                                                             |
| C25 section5               | Ledger billing history and support trace to origin line items                                                | E11 existing manual-payment history is NOT new ledger history. Missing integration; do not add an undocumented public endpoint by assumption.                              |
| C26 section6               | Admedia notified when payment processed/card charged before campaign starts                                  | Missing approved request/response contract and payment gating. Balance-only Text start is an unresolved documented edge case.                                              |
| C27 supplied examples      | Lifetime1000 balance0/50; lifetime200 balance500; daily100 x10 balance250                                    | E12 exact expected arithmetic covered; persisted funds/processor behavior not covered.                                                                                     |

### Scope audit, defects and unresolved decisions

1. **Do not mark either ticket complete.** Parent scope includes both child
   tickets and external verification/DSP/Admedia ownership. A committed 167
   branch is not a completed parent workflow.
2. **Paid-delivery gate missing:** Active/in-window can currently report
   `eligibleToServe=true` with `charged_at=null`; activation changes status
   without collecting funds. This is an unfinished payment requirement, not
   acceptable proof of delivery-after-payment.
3. **Budget code unconnected:** no caller of the new calculation helpers;
   no available-balance debit, ledger insert, charge timestamp or remaining
   budget writer anywhere in the API source.
4. **Existing date-only gap:** raw end timestamps can exclude most of the
   intended inclusive end day. Existing expiry ignores campaign-local next-day
   instant and Paused charged rows. Mandatory input dates do not fix this.
5. **Approved exception retained:** verified=true and removed API guards were
   explicitly requested; it is neither default-false schema compliance nor
   verified-only business enforcement. Restore only at the agreed handoff.
6. **Migration exists but is unexecuted:** committed schema has neither
   balance nor charged columns; new migration supplies them on 170. Prior
   local/test applied histories may already contain them. DB owner must
   reconcile before applying; no applied-file edits or resets performed.
7. **Integration blockers:** reusable validated-card owner/reference and
   background charge contract, lookup-by-idempotency/no-record outcome,
   provider decline/transient/config-error taxonomy, validated-card hook,
   authoritative reporting spend, Admedia payment/archive/report contracts.
   Clover auth failure is not a card decline.
8. **Source questions:** negative-budget extra charge vs no-charge overspend;
   erroneous 171 R7 reference; zero-card Text notification; recovery age,
   backoff/retry count; success discovered after flight end; opening ledger
   reconciliation and immutable-entry/reference finalization semantics.
   No speculative solution implemented.
9. **Implementation limits are not all external blockers:** local scheduler,
   event wiring, local-date predicates, reserve/finalize state handling,
   failure-status presentation, explicit retry surface and mocked tests
   remain unfinished engineering work. Do not claim waiting for contracts
   completes those requirements.
10. **Scope preserved:** no 171 rollover runtime, DSP billing implementation,
    restored verification guard, new processor/Admedia endpoint, secret,
    retry timing, opening balance backfill or live charge was invented.
    Nullable legacy dates remain intentionally; every-existing-row compliance
    still needs a scoped handoff decision. Name/creative behavior preserved
    in code, with integration tests still outstanding.

### Fresh audit execution evidence

- API and UI typechecks passed again; Prisma schema validation passed.
- UI ESLint passed for all five 170 files and both 167 campaign pages.
- All 76 isolated tests passed again: 30 money calculations, 36 locks/date
  schemas, seven mocked patch-service cases and three temporary-bypass
  regressions. These do NOT test live concurrency, HTTP E2E or processor calls.
- Existing DB-backed date tests remain unexecuted. No migration application,
  database inspection/write, seed, card charge, email/Admedia request or browser
  acceptance execution was performed for this audit.
- API lint previously could not start because its existing config imports
  missing `@eslint/js`; no dependency/config changes made during the audit.
- The temporary outside-repository Vitest config disabled setup/globalSetup
  and was deleted after execution. Normal `npm test` was not used because
  its setup applies migrations and seeds.

**Closeout:** every clause in the supplied parent/170 snapshots and payment-flow
text has an explicit checklist status above. This is requirement accounting,
not a statement that all requirements are implemented, tested or approved.
ADCM-167 original verification behavior remains an approved exception;
ADCM-170 is partial. Full payment implementation and acceptance remain open.

## Current ADCM-170 implementation and open integration contracts

This section is the current source of truth for `feat/ADCM-170` in both repositories.
It supersedes the historical implementation/schema assertions below. ADCM-170 is
**not complete or deploy-ready**. No commit, push, migration application, seed,
database-writing test, or real payment request was performed for these changes.
The user's latest instruction permits required ticket work and asks that missing
contracts be listed for confirmation, not replaced by invented behavior.

### Latest approval: schema changes include a migration

The user superseded the earlier mappings-only approval: every Prisma schema
change must include its migration. This branch now includes
`prisma/migrations/20261013183000_adcm_170_activation_payment_ledger/migration.sql`.
It was generated offline with Prisma from the committed ADCM-167 schema to
the current schema; no datasource or shadow database was used.

The migration adds only `available_balance`, `charged_at`, `remaining_budget`,
`balance_applied`, `card_charged` and the ledger table with its indexes and
foreign keys. It does not add `verified`, change existing data, modify flight
date nullability, or alter unrelated tables/columns. Existing applied migration
files were not edited.

**Not applied or DB-tested.** The configured local database was previously
reported to contain `available_balance` and `charged_at` from a separately
applied ADCM-167 migration that is absent from the committed baseline.
The earlier test database also has a different payment-schema history.
Applying this migration blindly to either database could fail with duplicate
columns/tables. The DB owner must reconcile those histories before deployment;
this generated migration targets the committed schema, not the current local DB.
Do not edit applied files, reset the database, or mark this migration applied
without verifying all of its objects actually exist.

This subsection supersedes older references below to supplying no migration.
Validation: Prisma schema validation passed. Regenerating the SQL from the
same committed/current schemas matched the migration file exactly; assertions
confirmed the five approved columns, one ledger table, indexes and foreign
keys, with no destructive or data-write statements. This is offline validation,
not evidence of successful migration application.

### Source checklist and requirement-to-code-to-test traceability

Sources are the supplied ADCM-170 ticket snapshot, ADCM-167 parent, ADCM-171
snapshot, and Confluence **Payment, Charging, and Rollover**, sections 2, 4, 5, 6.
Live Jira access currently requires GitKraken sign-in; no new ticket or comment
has been created. Do not treat a supplied snapshot as a live Jira update.

| Requirement                                                                                                           | Source/workflow step                                                    | Current code                                                                                                                                                                                   | Verification/status                                                                                                                                                                                                                                                                |
| --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R1 shared backend eligibility, activation/approval/campaign events, sweep within five minutes                         | ADCM-170 R1, AC5/AC11; Confluence 2: Trigger                            | Existing `src/lib/serving-status.ts` remains unchanged                                                                                                                                         | Outstanding: campaign-time-zone inclusive dates, paid-delivery gating, event wiring and sweep. Existing helper uses raw instants and also checks campaign dates; this is not the specified payment trigger implementation.                                                         |
| R2 Lifetime and Daily inclusive totals; half-up cents; balance first                                                  | ADCM-170 R2, AC1/AC2/AC3/AC12; Confluence 2: Total Budget/Charge Amount | `src/modules/payments/payment-budget.ts`                                                                                                                                                       | Decimal calculation helpers implemented and tested. Not connected to a reserve/charge workflow; actual card charging and balance writes are outstanding.                                                                                                                           |
| Every line item requires an end date; no Daily/no-end MVP                                                             | ADCM-167 Total Budgets; Confluence 2: Total Budget                      | API line-item schema/types/routes/service; UI `AddLineItem.tsx`, `LineItemDetailsForm.tsx`, helper validation and payload types                                                                | API schema tests executed. Existing DB-backed date tests updated but not executed. UI type/lint validation is not browser acceptance. Campaign no-end-date support is preserved.                                                                                                   |
| R3 zero-card remainder: no processor request, still deduct and finalize                                               | ADCM-170 R3, AC3; Confluence 2: Charge Amount                           | Funding helper returns exactly zero                                                                                                                                                            | Runtime balance deduction, zero-charge ledger and finalization remain outstanding. A calculation test is not a zero-processor-call test.                                                                                                                                           |
| R4 ledger rows, processor reference, charged timestamp and remaining budget                                           | ADCM-170 R4, AC10; Confluence 2 and 5                                   | Approved Prisma mappings for advertiser balance, charge/funding/remaining-budget fields, `DspPaymentLedgerEntry` and enums                                                                     | Prisma validation and client generation executed. No ledger writer/finalizer, migration or DB acceptance execution. Monetary fields use approved precision; verification stays temporarily hardcoded, not remapped.                                                                |
| R5 reserve/charge/finalize; ready rollovers; recovery by idempotency key                                              | ADCM-170 R5, AC14; Confluence 2: How a Charge Runs                      | Advertiser row-lock collection helper added for edit safety                                                                                                                                    | Money workflow/recovery not implemented. Existing provider has no idempotency-key lookup or missing-record result. Ready rollovers depend on ADCM-171; no fake/no-op rollover was added.                                                                                           |
| R6 charged once, attempt-number key, advertiser serialization                                                         | ADCM-170 R6, AC4/AC7/AC13/AC15                                          | Ledger mappings include attempt number and unique idempotency key                                                                                                                              | Activation orchestration and real concurrency tests outstanding. Sequential arithmetic tests demonstrate the formula only, not concurrent DB correctness.                                                                                                                          |
| R7 transient retries, decline reversal/Pending/email, explicit retry, validated-card retry, expired-flight completion | ADCM-170 R7, AC6/AC13/AC15; Confluence 2: Card Declined                 | No new failure/retry implementation                                                                                                                                                            | Outstanding. Existing completion job is based on raw instants, not campaign-local flight end; it is not acceptance evidence for this requirement.                                                                                                                                  |
| R8 eight fields read-only charged/pending; name and creatives stay editable                                           | ADCM-170 R8, AC8/AC9/AC16; Confluence 2: Successful Charge              | `line-item-payment-lock.ts`; query/detail schema; patch rechecks state after advertiser lock inside write transaction; UI disables exact eight fields and omits them from locked edit payloads | DB-free helper and service tests cover charged/pending/unlocked states and a charge-state change between initial and locked reads. Real MySQL lock behavior and browser/creative acceptance remain unexecuted. Text subtype and delivery priority were not added to the lock list. |
| Text payment notification/activation                                                                                  | Confluence 6                                                            | Existing Admedia integration unchanged                                                                                                                                                         | Approved saved-card and payment-success notification contracts are missing. Do not claim ordinary status sync implements payment gating.                                                                                                                                           |
| Completion/end timestamps, 24-hour final spend, hourly rollover, overspend absorption                                 | ADCM-171; Confluence 4                                                  | No ADCM-171 runtime changes on this branch                                                                                                                                                     | Reserved for ADCM-171. Its ready-rollover operation is nevertheless a dependency of ADCM-170 reserve.                                                                                                                                                                              |

### Approved schema and migration handoff

The user now requires Prisma mappings and their corresponding migration file.
The database owner must reconcile and apply the migration before this branch
is run. The assistant generated the file but did not execute it:

- `advertiser.available_balance`: `DECIMAL(10,2)`, default zero.
- `line_item.charged_at`: nullable timestamp.
- `line_item.remaining_budget`, `balance_applied`, `card_charged`: nullable
  `DECIMAL(18,2)` until the successful charge writer initializes them.
- `dsp_payment_ledger_entry`: advertiser/optional line item, immutable amount,
  `BALANCE_APPLIED` / `LINE_ITEM_CHARGE` / `BALANCE_CREDIT`, nullable
  `PENDING` / `SUCCEEDED` / `FAILED` card status, unique optional idempotency key,
  processor reference, attempt number and timestamps.
- Advertiser/line-item ledger relations restrict deletion. Money must be
  corrected by a new entry, not by editing or deleting an existing amount.
  No runtime ledger mutation implementation is present yet.
- `verified` is still hardcoded true under the separately approved ADCM-167
  exception. No database verification mapping or restored verification guard
  is included here.

Adding mappings or generating a migration file does not add columns to a running
database. API queries now require the mapped columns and ledger table.
Generating a client is not applying a migration and does not make this change
deployable against the old database.

### High-level required workflow (design, not executed implementation)

```mermaid
flowchart TD
  A[Activate / approval / campaign event / five-minute sweep] --> B{Shared backend status_chain_ok and not charged?}
  B -- No --> N[No charge]
  B -- Yes --> R[Reserve under advertiser lock: ready rollovers, balance first, immutable ledger]
  R --> Z{Card remainder zero?}
  Z -- Yes --> S[Finalize in reserve transaction]
  Z -- No --> C[Charge saved validated card without DB lock]
  C -- Success --> S2[Finalize under advertiser lock]
  C -- Decline --> F[Failed ledger, balance credit reversal, Pending, tooltip and email]
  C -- Transient --> T[Automatic backoff retry with same attempt key]
  T -- Still unresolved --> P[Keep pending for processor lookup recovery]
  P -- Success --> S2
  P -- Decline / confirmed no record --> F
  F --> U[Advertiser Retry payment / validated replacement card]
  U --> E{Flight still open?}
  E -- Yes --> R
  E -- No --> X[Completed, never initiate charge]
  S --> D[Charged timestamp, funding amounts, remaining budget; paid delivery / Text notification]
  S2 --> D
  D --> L[Eight fields locked; name and creatives remain editable]
```

### Detailed required workflow and decision rules

1. Evaluate shared backend eligibility using Active line item, Active campaign
   and inclusive line-item dates in the campaign's time zone. A pending or
   failed payment must not allow delivery. Do not replace the shared predicate
   with a different payment-only date calculation.
2. Reserve in a short transaction: lock the advertiser, re-read the line item
   and charge ledger, and refuse duplicate/reserved attempts. Apply only ready
   rollovers (24 hours since the recorded end). Calculate the Lifetime/Daily
   total and balance/card portions in cents.
3. Write the balance application and pending card entry with line-item ID plus
   attempt number; deduct the reserved balance. Persist the amount needed by
   recovery, rather than trusting a later UI payload.
4. For zero remainder, initialize remaining budget, funding amounts and
   charged timestamp and finish without calling the processor.
5. Otherwise release the database lock before calling the validated saved
   card with the same attempt key on each transient retry.
6. Finalize success in a separate locked transaction, recording the processor
   reference and succeeded card status. Mark charged and initialize remaining
   budget once. Failure after a processor success must leave a recoverable
   pending record, not cause another charge.
7. On definitive decline, fail that card entry, restore the applied balance
   with a new balance-credit entry, leave charged timestamp empty, set Pending,
   expose "Payment failed, update your card" and email the advertiser.
8. Unresolved transient attempts stay pending; a recovery job queries by key.
   Only a confirmed no-record/decline result follows the decline path.
9. Manual retry/new validated card after a decline uses a new attempt number.
   New-card processing covers every payment-failed line item whose flight is
   still open. An ended flight is Completed and is never newly charged.
10. The UI and API enforce the same eight locks during pending and after success.
    Name edits and creative attachment/detachment remain available.

Steps 1-9 are the outstanding activation implementation, not a claim that the
new field-lock code performs them.

### Missing contracts and Jira comment prepared for confirmation

The following is ready to post to **ADCM-170** once Jira sign-in is available.
It has **not** been posted:

> Implementation dependencies and clarification list, strictly from R1-R8:
>
> 1. R4/schema: this branch supplies the approved balance, charge/funding,
>    remaining-budget and ledger mappings plus migration
>    `20261013183000_adcm_170_activation_payment_ledger`.
>    DB owner must reconcile local/test migration history before applying it.
> 2. R5/R7 saved-card handoff: identify the advertiser's reusable validated
>    processor/vault reference, its owner/storage relation, and the API for
>    charging it. Current `PaymentProvider.createCharge` accepts `sourceToken`
>    and requires `customerIp`; it does not define background saved-card use.
>    Do not reuse a one-time signup token or fabricate an IP.
> 3. R5 recovery: provide lookup by idempotency key, including a definitive
>    no-record result. Current `getCharge` requires a processor payment ID,
>    which may be unavailable after a timeout/process crash.
> 4. R7 provider outcomes: confirm decline vs transient/configuration errors.
>    The existing Clover adapter can label authentication errors FAILED;
>    these must not be treated as an advertiser card decline.
> 5. R7 new validated card: provide the success event/hook and ownership
>    contract that starts retrying every unended payment-failed line item.
> 6. R5 dependency correction: the reference to ADCM-171 R7 for ready rollovers
>    should point to its rollover-processing requirement (R9 in the supplied
>    snapshot). ADCM-170 must call that operation under the same advertiser
>    lock; do not silently skip ready rollovers while developing 170 first.
> 7. Confluence 6: confirm the Admedia payment-success request/payload and
>    response contract, including balance-only funding when the card portion
>    is zero. No new Admedia endpoint is assumed.
> 8. R5/R7 timing: confirm the recovery age ("a few minutes"), automatic
>    backoff schedule and whether "up to 3 times" means three retries after
>    the initial request. No undocumented timing values were added.
> 9. R7 expiry: confirm handling when a pending processor outcome crosses
>    flight end, particularly success discovered after the flight ends.
>    No additional refund or second charge is assumed.
> 10. Ledger initialization: DB owner must reconcile any existing positive
>     available balance to opening ledger entries; the ticket requires
>     balance to equal the sum of balance movements.
> 11. Cross-ticket conflict: ADCM-167 mentions a negative-budget charge,
>     whereas Confluence/ADCM-171 require clamping to zero and recording
>     platform-absorbed overspend. No additional card charge is implemented.
>
> Already implemented on 170: mandatory line-item end dates; exact charged/
> pending field locks in API/UI with lock-time recheck; approved schema
> mappings and unexecuted migration; decimal budget/balance arithmetic and isolated tests. Reserve/
> processor/finalize/recovery/events/retry workflow is not complete.

Recommendations are separate from ticket changes: do not deploy before the DB
handoff and these integration contracts; use sandbox-only processor and Admedia
fixtures for acceptance; restore temporary verification enforcement at the
approved handoff. None is represented as an already implemented integration.

### Acceptance execution plan

Preconditions for integration/E2E: DB owner has reconciled and supplied the
schema; disposable test advertiser has a sandbox validated card; processor,
email and Admedia traffic is mocked or sandbox-only; flight dates/time zone
and clock are controllable; report both DB/ledger state and external-call count.
Do not run the normal test setup now: it applies migrations and seeds.

Executed evidence for this change:

- Prisma validation and client generation passed, without accessing/writing the
  database. Unrelated formatter-only Prisma changes were removed.
- API and UI typechecks passed.
- All five changed UI files passed ESLint.
- 76 isolated tests passed: 30 budget calculations, 36 field-lock/end-date
  schema cases, seven mocked patch-service cases and three inherited temporary
  campaign-verification regressions. Setup/global-setup arrays were empty;
  no DB-backed test was included and no processor was contacted.
- API ESLint could not start: the existing configuration imports `@eslint/js`,
  which is absent from the API installation/manifest. No unrelated dependency
  or lint-configuration change was added.
- Changed-file Prettier and diff whitespace checks were run. No browser,
  MySQL locking, card, email or Admedia acceptance pass is claimed.

The temporary isolated test configuration was stored outside either repository
and removed after execution. To reproduce without the database-writing setup,
run Vitest with an equivalent temporary config:

```js
export default {
  test: {
    environment: "node",
    setupFiles: [],
    globalSetup: [],
    fileParallelism: false,
    include: [
      "tests/payment-budget.unit.test.ts",
      "tests/line-item-payment-lock.unit.test.ts",
      "tests/line-item-payment-patch.unit.test.ts",
      "tests/campaign-verification.test.ts",
    ],
  },
};
```

From the API root, use `npx vitest run --config <absolute-path-to-that-config>`.
Do not substitute `npm test`: that uses the migration/seed setup.

| Case/source         | Test data and steps                                                                                                                                             | Expected result/evidence                                                                                                                  | Execution                                                                                                |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| AC1/AC2/AC10        | Eligible Lifetime 1000; balances 0 and 50. Fire an eligibility event, read advertiser/line item/ledger, capture processor request.                              | Card 1000 or 950; balance zero; applied+card=1000; succeeded reference and initialized charged/remaining state.                           | Formula unit tests executed; activation/DB evidence outstanding.                                         |
| AC3                 | Eligible budget 1000, balance 1500; instrument all processor calls.                                                                                             | Zero processor calls, balance 500, charged timestamp and balance ledger.                                                                  | Zero arithmetic executed; runtime not executed.                                                          |
| AC4                 | Activate twice, concurrently and after pause/resume, using an already charged item.                                                                             | No extra card call or balance movement, original funding unchanged.                                                                       | Not executed.                                                                                            |
| AC5                 | Inactive campaign / future date / no approved creative; activate and fire approval/campaign events in each valid order.                                         | No premature charge/delivery; once all shared conditions hold, one funded activation.                                                     | Not executed.                                                                                            |
| AC6                 | Budget 1000, balance 50, definitive card decline. Inspect ledger, balance, delivery and captured email.                                                         | Balance 50, charged null, Pending, exact tooltip, balance-credit reversal and one email; no automatic decline retry.                      | Not executed.                                                                                            |
| AC7                 | Balance 500, two eligible items of 400; start reserve concurrently in separate DB transactions. Repeat in both orders.                                          | Applied sum 500, card sum 300, no lost balance or duplicate ledger.                                                                       | Sequential math executed; real concurrency not executed.                                                 |
| AC8/AC9/AC16        | Each exact locked field, each charged/pending/unlocked state; submit API PATCH and try UI editing. Start a reserve between edit's initial read and locked read. | Charged/pending reject with field feedback, UI read-only; unlocked normal edits. Name and creative actions still work.                    | Pure guards and mocked locked-recheck/name-write tests executed; DB/browser/creative tests outstanding.  |
| Mandatory end dates | Create Lifetime/Daily with omitted/null/empty/invalid end date, including campaign without end. Patch end date to null; use same-day valid flight.              | Invalid dates rejected; one-day flight supported; valid-end Pace Evenly still allowed.                                                    | Schema tests executed; existing DB-backed regression tests updated but unexecuted.                       |
| AC11                | Active future-dated item; use campaign zones on either side of UTC and DST transitions. Move clock to start date.                                               | No early charge; one charge by five minutes after campaign-local start; end date included through local day end.                          | Not executed.                                                                                            |
| AC12/R2             | Daily 100 over ten inclusive calendar dates; single day, leap-day and DST flights; decimal half-cent inputs.                                                    | 1000 / one daily amount / correct calendar-day count; half-up cent total without binary-float drift.                                      | Calculation tests executed, no runtime charge asserted.                                                  |
| AC13/R7             | Decline, then Retry payment; separately save a new validated card with several failed items, one expired.                                                       | New attempt/key for advertiser retry; every unended failed item retried, expired item Completed and never charged.                        | Not executed.                                                                                            |
| AC14                | Processor succeeds, then fail DB finalize; run recovery using only persisted key.                                                                               | One processor charge; recovery finalizes original pending entry; no extra debit.                                                          | Not executed.                                                                                            |
| AC15/R7             | Timeout/processor error followed by success or exhausted retries; also confirmed lookup no record. Capture request keys and time.                               | Same attempt/key across automatic retries; unresolved stays pending; confirmed no record follows decline restoration, not silent success. | Not executed.                                                                                            |
| Confluence 5        | Inspect all successful/failed money paths and immutable historical rows; compare sum of balance entries to available balance.                                   | Corrections/reversals are new rows; money never edited/deleted; balance reconciles.                                                       | Schema validated only; ledger-runtime evidence outstanding.                                              |
| Confluence 6        | Paid Text activation, card-funded and balance-only cases; simulate Admedia error with agreed contract.                                                          | No unpaid Text delivery; correct approved notification, explicit error handling.                                                          | Blocked on contract, not executed.                                                                       |
| ADCM-171 dependency | Have one ready rollover and one inside 24 hours when reserving a new activation.                                                                                | Only ready funds applied before calculating card amount; no premature/double rollover.                                                    | Reserved for cross-ticket integration; not executed.                                                     |
| Regression          | Existing verified-site gate, approved temporary verified=true API, campaign no-end support, name/targeting rename, creative attachment actions.                 | Existing approved behavior outside payment scope preserved.                                                                               | Three mocked campaign regressions and name-write test executed; remaining DB/browser checks outstanding. |

Final audit: R8 implementation and mandatory end-date input handling are present;
R2 is a tested calculation foundation; R4 is a schema-only foundation.
R1/R3/R5/R6/R7, runtime R2/R4, Text payment gating and cross-ticket integration
remain open. Consequently neither all ADCM-170 acceptance criteria nor the
parent payment workflow can be marked complete.

## Current temporary implementation - application-only verification bypass

The user explicitly approved a temporary hardcoded API value `verified=true`,
removal of campaign/payment advertiser-verification checks, and removal of all
three proposed Prisma fields until another developer supplies the database changes.
This section supersedes every schema/default/verification-enforcement statement
below, which describes earlier implementation stages.

- Auth responses and admin advertiser details return `verified=true` without
  reading a verification column. UI response schemas still require a boolean;
  existing UI checks consume that API value, so advertiser verification does not
  block campaign creation during this bypass.
- Campaign creation and payments do not enforce advertiser verification.
  Existing authentication, ownership checks, verified-website restrictions,
  payment validation and idempotency behavior are preserved.
- Prisma contains no new `verified`, `availableBalance` or `chargedAt` fields,
  and this branch supplies no ADCM-167 migration. There is no fake balance
  accounting or charge timestamp writer; activation/rollover remain outstanding.
- No database state is changed by removing model fields. Previously applied local
  migration history still requires the database owner's reconciliation.

This is an approved temporary exception, **not completion of the ticket's
verified-only campaign/payment requirements**, and not a deploy-ready payment
workflow. It allows unverified advertisers past the advertiser-verification
gate; a verified website is still required by the existing campaign workflow.

### Required removal after database handoff

1. Receive the authoritative columns/defaults and verification writer from the
   database/signup owner; reconcile previously applied local/test history.
2. Restore the three Prisma field mappings and generate the client.
3. Replace both hardcoded response values with the stored verification flag.
4. Restore campaign/payment checks using the target advertiser; reinstate
   false/revoked-verification tests and remove temporary bypass assertions.
5. Run API/UI acceptance checks and complete the child-ticket/DSP dependencies
   before claiming parent coverage.

Temporary bypass coverage uses isolated mocked tests. Historical six-test
verification-enforcement results below do not validate this new behavior.
Database-backed tests remain unexecuted under the no-database-writes restriction.
Current execution: Prisma format/validate/client generation and API/UI typechecks
passed; all three database-free campaign bypass/regression tests passed.

## Latest approved change - database migrations owned externally

The user confirmed TL/PM approval to use `verified=true` as the Prisma default,
superseding the ticket's original `false` default. This means new advertisers
are considered verified by default unless the verification owner explicitly sets
false. API/UI guards still reject an actual false value; they do not treat a
missing response field as true.

Another developer owns all ADCM-167 database migrations. The assistant-created
`20261013120000_adcm_167_payment_balance_and_line_item_state` migration file has
been removed from this change set. Existing committed migrations are untouched.
Prisma retains the required application contracts: `verified` default true,
`available_balance DECIMAL(10,2)` default zero, and nullable `charged_at`.
No balance or timestamp defaults were changed to true.

**Deployment dependency:** removing the migration file does not remove any
already-applied columns or migration-history records, or change the live
database's false default. The configured local database previously applied this
migration and will now have an applied history entry absent from this branch.
The earlier test-database history also needs reconciliation. The migration owner
must reconcile both histories and supply the columns/default before deployment.
Do not run migrate dev/reset or DB-backed tests until that handoff is resolved.
Application queries still require the columns; this is not a no-schema-change
implementation.

This section supersedes the historical schema/default/migration statements below.

## Current implementation - ADCM-167 advertiser campaign restriction

The user approved enforcing `advertiser.verified` now, with signup supplying the
flag before rollout. No verification endpoint or database-record updates were
added. The latest approved schema default is true, as described above; existing
advertiser values remain under the migration/verification owner's control.
An active account or a verified website is not advertiser verification.

| Parent requirement                             | Implementation                                                                                                                                                                         | Verification                                                                                                      |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Only verified advertisers can create campaigns | `campaign.service.ts` reads the target advertiser's flag on every create, including admin-created campaigns, and rejects false before any campaign write.                              | Six isolated, mocked service tests passed with no database setup or calls.                                        |
| Expose the verification state needed by the UI | Existing auth responses and admin advertiser-detail responses include a required boolean `verified`; UI response schemas validate it without a permissive default.                     | API and UI typechecks passed.                                                                                     |
| Prevent unverified campaign creation in the UI | Campaign-list create action and direct create page are blocked; admin selection checks the selected advertiser. Loading/error states do not enable creation, and errors are displayed. | Typechecked; browser and database-backed acceptance results must be recorded separately, not inferred.            |
| Preserve existing campaign restrictions        | Objective validation, verified-website checks, Draft creation, actor attribution, and editing of existing campaigns are unchanged.                                                     | Mocked tests cover verified success and preserved site rejection; affected E2E fixtures updated but not executed. |

No new database columns beyond the three ADCM-167 additions are introduced here.
The payment-time verification guard remains in scope under the approved PM/TL
clarification. The upstream verification/card-storage workflow is not implemented
by this change and must not be described as complete.

Execution evidence: API and UI typechecks passed, six isolated database-free
service tests passed, changed UI files passed ESLint, and diff whitespace checks
passed. Database-backed HTTP tests were added but not run. A mocked integrated
browser check was attempted; it stayed on the loading screen and its assertion
timed out, so no UI behavioral pass is claimed. The temporary UI server was
stopped. No commits, pushes, migrations, seeds, or database writes were performed
for this update.

### Remaining parent requirements and branch ownership

| Remaining requirement                                                                                                                                                             | Implementation branch/dependency                                            | Current state                                                                    |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Signup verification, validated saved card, and verified-flag writer                                                                                                               | Signup/advertiser-verification team handoff                                 | Not supplied in this implementation.                                             |
| First-eligible activation, event hooks/sweep, total budget, balance-first formula, zero-card funding, charged timestamp, paid delivery, ledger, retries/recovery, and field locks | ADCM-170 R1-R8 / AC1-AC16                                                   | Not implemented; preserved earlier partial work is not an active implementation. |
| Mandatory line-item end date                                                                                                                                                      | Parent ADCM-167 requirement; implement with ADCM-170 budget/flight handling | Not implemented on current 167 branch.                                           |
| Completion/end timestamp, final spend, positive rollover/reset, overspend absorption, archive handling, scheduling and ready-rollover priority                                    | ADCM-171 R1-R11 / AC1-AC18                                                  | Not implemented.                                                                 |
| Win cost `supply_cost / (1 - platform_fee)` and remaining-budget deduction                                                                                                        | Separate DSP dependency explicitly referenced by parent                     | Ownership/integration must be confirmed; not implemented here.                   |
| Notify Admedia on payment and read Text final spend                                                                                                                               | ADCM-170 activation / ADCM-171 reporting integrations                       | Not implemented; approved API contracts still required.                          |

The parent is complete only when these child implementations and upstream/DSP
dependencies are delivered and verified. The parent's negative-budget card-charge
statement conflicts with Confluence and ADCM-171; the latter specify platform
absorption without another card charge. No negative-budget charge was added.

### Campaign verification acceptance checks

The following database-backed/browser checks are planned unless execution evidence
is recorded below. The ordinary API test runner migrates and seeds its database and
must not be run under the user's current no-database-operations restriction.

| Case                                     | Preconditions/data                                                                       | Steps                                                                           | Expected result                                                                                    |
| ---------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| Unverified advertiser                    | `verified=false`, valid objective, verified site                                         | Attempt creation from campaign list, direct create URL, and authenticated POST. | UI blocks creation; API returns 403 with `advertiserId` field explanation; no campaign is written. |
| Verified advertiser                      | `verified=true`, valid objective, verified site                                          | Submit valid campaign details.                                                  | Existing Draft creation and actor attribution remain intact.                                       |
| Verification is not website verification | `verified=true`, no verified site                                                        | Submit a valid campaign.                                                        | Existing website-verification rejection remains intact.                                            |
| Admin target                             | Admin actor; selected advertiser false, then separately a true target with verified site | Select each target and attempt creation.                                        | False target is blocked regardless of admin identity; true target uses existing creation behavior. |
| Revoked/stale verification               | UI previously read true; authoritative flag now false                                    | Attempt POST with stale UI state.                                               | Server rechecks target and rejects; clear field message is available.                              |
| Read failure/loading                     | Auth or selected advertiser request pending/fails                                        | Open creation page or switch selected advertiser.                               | Creation remains disabled; errors are visible, not treated as a verified response.                 |
| Regression                               | Existing campaign and its normal edit permissions                                        | List/view/edit an existing campaign.                                            | No new verification restriction is added to existing campaign editing.                             |

## Current correction — ADCM-167 schema scope

This section supersedes earlier shared-schema allocation and precision findings
in the historical audit below.

The ADCM-167 Prisma schema and migration now introduce **only three columns**:

| Ticket schema requirement                    | Current schema/migration                                | Status                                                                 |
| -------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------- |
| Advertiser verified, not null, default false | `verified BOOLEAN NOT NULL DEFAULT false`               | Matches ticket.                                                        |
| Advertiser balance, not null, default zero   | `available_balance DECIMAL(10,2) NOT NULL DEFAULT 0.00` | Matches ticket precision.                                              |
| Line-item charge timestamp, nullable         | `charged_at DATETIME(3) NULL`                           | Matches nullable timestamp; repository-standard millisecond precision. |

Removed from ADCM-167: remaining-budget/end/rollover columns, new indexes,
ledger table, ledger enums and relations. Full prior files are preserved in
session artifacts for child-ticket implementation. Ledger and remaining budget
belong with ADCM-170/its schema dependency; end/rollover state and rollover
extensions belong with ADCM-171. Neither child schema nor runtime is currently
implemented on this branch.

The payment-time verification guard and its tests remain in ADCM-167, based on
the approved PM/TL clarification. The parent workflow is still incomplete.

**Database history warning:** the previous broader version of this uncommitted
migration was automatically applied to the local test database earlier in the
session. Narrowing its file does not undo those database changes, update its
stored checksum, or shrink the database column. Do not run migration commands
or database-backed tests against that database before the user/TL reconciles
its history. No migration, database correction, delete or reset was executed
for this scope correction. A database known never to have applied the old
version may use the narrowed migration through the approved deployment process.

## ADCM-167 pre-commit audit — 13 October 2026

Audit basis: both attached 92-line ADCM-167 snapshots have the same requirement
text; compare that text with the supplied Confluence sections 1–6, approved
PM/TL payment-time verification clarification, and the actual staged API diff.
At that earlier audit the UI working tree had no changes; the current implementation
section above supersedes that state. This is a foundation commit audit, not a
certification that the parent ticket is complete.

### Parent requirement checklist

| ID  | Requirement in ADCM-167 / applicable Confluence                                                                                             | Evidence on current ADCM-167 branch                                                                                                                                    | Status                                              |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| P01 | Advertiser signs up.                                                                                                                        | Existing signup path is unchanged; no new signup implementation/test in this commit.                                                                                   | Existing behavior, not reverified in this audit.    |
| P02 | Billing/card details collected during advertiser verification; save card without capture.                                                   | Signup owns this per PM/TL; no saved-card handoff or validation implementation in this commit.                                                                         | Outstanding upstream dependency.                    |
| P03 | Admin verifies/rejects; only admin can reverse rejection.                                                                                   | Boolean verified field added, but no review/rejection/reversal workflow.                                                                                               | Field only; not implemented.                        |
| P04 | Only verified advertisers can create campaigns in UI.                                                                                       | No campaign API or UI change. Payment verification guard is not a campaign-creation guard.                                                                             | Not implemented.                                    |
| P05 | Approved clarification: payment checks advertiser verification, not signup AVS/CVV again.                                                   | `src/modules/payments/payment.service.ts` reads verified before creating payment or calling provider; tests cover denial and verified success.                         | Implemented on existing payment API only.           |
| P06 | First eligible line item, with charged_at NULL, charges card on file.                                                                       | chargedAt column exists; no automatic activation executor or reusable card reader.                                                                                     | Schema only; not implemented.                       |
| P07 | Backend status_chain_ok: line item Active, campaign Active, within inclusive flight dates in campaign timezone.                             | No shared eligibility/trigger change in current staged files.                                                                                                          | Not implemented by this change.                     |
| P08 | Reevaluate on activation/approval events and sweep at least every five minutes.                                                             | No event hook or sweep.                                                                                                                                                | Not implemented.                                    |
| P09 | Lifetime total equals budget_amount.                                                                                                        | No calculation.                                                                                                                                                        | Not implemented.                                    |
| P10 | Daily total equals budget_amount times inclusive flight days.                                                                               | No calculation.                                                                                                                                                        | Not implemented.                                    |
| P11 | Every line item requires end date; daily without end removed from MVP.                                                                      | Required-end-date changes preserved for ADCM-170, not active here; schema endDate remains nullable.                                                                    | Not implemented on current 167 branch.              |
| P12 | Apply MIN(balance,total), charge MAX(0,total-applied), deduct applied balance.                                                              | availableBalance field only; no reserve/calculation/writer.                                                                                                            | Not implemented.                                    |
| P13 | New advertiser starts at zero balance and pays full total.                                                                                  | Balance default zero added; no automatic charge.                                                                                                                       | Default implemented; workflow absent.               |
| P14 | $50 balance/$1,000 budget: apply $50, charge $950, new balance zero.                                                                        | No executable calculation on this branch.                                                                                                                              | Not implemented/tested.                             |
| P15 | $500 balance/$200 budget: apply $200, no card request, new balance $300, mark charged.                                                      | No zero-card branch.                                                                                                                                                   | Not implemented/tested.                             |
| P16 | Process mature rollovers before charge.                                                                                                     | Rollover fields/ledger type only; no processor.                                                                                                                        | Not implemented.                                    |
| P17 | Success sets charged_at, balance_applied, card_charged and remaining_budget; delivery begins.                                               | chargedAt/remainingBudget fields added; balanceApplied/cardCharged fields and finalize/delivery logic absent.                                                          | Incomplete schema and no workflow.                  |
| P18 | Lock channel and budget amount/type, bid strategy/amount, pacing, start/end after charge and while pending; name/creatives remain editable. | Lock changes preserved for ADCM-170; no lock code active on 167.                                                                                                       | Not implemented on current 167 branch.              |
| P19 | Reserve/charge/finalize, restore decline balance, serialize advertiser operations and recover pending results once-only.                    | Ledger enum/model/key fields exist; no activation reserve/finalize/recovery transaction.                                                                               | Schema only; not implemented.                       |
| P20 | Decline Pending/tooltip/email; transient retries; advertiser/new-card retries; uncharged expired flight completes.                          | Existing manual payment behavior unchanged apart from verified guard; no line-item failure/retry flow.                                                                 | Not implemented.                                    |
| P21 | DSP win deducts supply_cost/(1-platform_fee); Text uses Admedia spend.                                                                      | No DSP/reporting change.                                                                                                                                               | Not implemented/verified here.                      |
| P22 | Completion/archive ended_at set once, correct flight boundary; Text pause and Display refresh behavior.                                     | endedAt added; no transition/job/external integration.                                                                                                                 | Schema only; not implemented.                       |
| P23 | After 24 hours credit final unused budget and zero remaining; hourly job; once-only, atomic rollover.                                       | rolledOverAt/remainingBudget fields exist; no job/credit transaction.                                                                                                  | Schema only; not implemented.                       |
| P24 | Platform absorbs overspend, floor remaining at zero, no extra card charge; record raw overspend.                                            | overspendAmount exists; no arithmetic/writer. Parent's negative-budget card-charge wording conflicts with Confluence and ADCM-171; do not implement that extra charge. | Conflict recorded; not implemented.                 |
| P25 | Every movement in immutable ledger, including zero rollover; balance reconciles; history source.                                            | Ledger model exists; no mutation protections, reconciliation or history integration.                                                                                   | Schema only; not implemented.                       |
| P26 | Text payment/card-charge notification starts Admedia.                                                                                       | No integration.                                                                                                                                                        | Not implemented.                                    |
| P27 | Schema: verified BOOLEAN NOT NULL DEFAULT false.                                                                                            | Prisma and migration match.                                                                                                                                            | Implemented in schema.                              |
| P28 | Schema: available_balance DECIMAL(10,2) NOT NULL DEFAULT 0.00.                                                                              | Default/nullability match, but staged Prisma and migration use DECIMAL(18,2).                                                                                          | Exact-ticket mismatch; precision approval required. |
| P29 | Schema: charged_at nullable DATETIME.                                                                                                       | Nullable Prisma field and DATETIME(3) migration; millisecond precision follows repository timestamp convention.                                                        | Implemented with repository precision.              |

### Changed-code scope audit

- Payment guard: a database advertiser read, missing-advertiser NotFound error,
  unverified Forbidden error, and required import. This is the approved
  payment-time check; it does not validate the card or automatically verify
  advertisers. The guard also runs before idempotency replay.
- Guard tests: verified test fixture, provider spy, denial/no-payment assertion,
  verified success coverage, and revoked-verification replay denial with fixture
  restoration. These tests write test data and are not executed under the
  current user restriction.
- Shared schema: advertiser/line-item fields, ledger enums/model, relations,
  foreign keys and indexes support Confluence sections 2/4/5 and the child
  tickets. endedAt/rolledOverAt/overspend are not named in ADCM-167 alone;
  they are explicitly shared child foundations, not parent runtime work.
- Ledger idempotency uniqueness and indexes support child charge/recovery/
  scheduling requirements; they do not guarantee once-only behavior without
  the required locked service operations.
- `updatedAt` is repository-standard metadata, not a money movement; no ledger
  amount updates or deletions are introduced, but immutability is not enforced.
- Prisma formatting changed alignment outside the added fields. Ignoring
  whitespace, the schema diff adds only the payment-related fields/model/
  relations/indexes/enums listed above.
- Audit blockers before calling this exact-source-compliant: available-balance
  precision differs from the parent's explicit DECIMAL(10,2); remaining-budget
  storage uses two decimals while budget/spend-related fields use six, and
  ADCM-170 explicitly requires backend precision confirmation. Do not claim
  bidder compatibility without that confirmation.
- Do not edit the already test-applied migration to hide these mismatches.
  Any approved schema correction needs a follow-up migration reviewed and
  executed by the user.

**Audit conclusion:** payment foundations only. The complete ADCM-167
requirements are not fulfilled. Do not use a commit message claiming complete
payment flow, activation charging, campaign verification gating or rollover.
No runtime code was changed as part of this audit.

## Branch delivery and current working-tree status

The approved delivery sequence in both repositories is:

```text
development
  -> feat/ADCM-167  (shared foundations; user commits)
  -> feat/ADCM-170  (activation charging; user commits)
  -> feat/ADCM-171  (rollover and final integration; user commits)
```

Both repositories are currently on `feat/ADCM-167`, based on development.
No ticket commit has been created. The existing `feat/ADCM-170` and
`feat/ADCM-171` refs were created prematurely from development and are only
placeholders; they must be based on the user's completed preceding ticket
commit before work moves there.

Current allocation:

- ADCM-167 API: shared payment schema/migration, payment verification guard,
  guard tests, and this source/traceability document.
- ADCM-167 UI: no ticket-specific implementation yet; the branch currently
  contains unchanged development UI code. Do not create an empty UI commit
  or claim verification/campaign gating is implemented in the UI.
- ADCM-170 API/UI: earlier required-end-date and pending/charged edit-lock
  changes are preserved outside the repositories as ticket patches, not active
  on the ADCM-167 working trees. Restore them on ADCM-170 only after its base
  includes the user's ADCM-167 commit.
- ADCM-171: no rollover runtime implementation yet. Shared ledger and rollover
  schema fields are foundations, not completed rollover acceptance criteria.

The implementation/test status recorded later in this document includes
historical validation of the preserved ADCM-170 changes. It must not be read
as evidence those changes are active on the current ADCM-167 branch, or that
ADCM-167 is complete. The full parent scope is fulfilled only when the child
requirements and upstream dependencies are implemented and verified.

The user owns all commits, pushes, database writes, migrations and
database-backed test execution. Agents may perform database-free typechecks
and formatting checks. The API E2E setup applies migrations and writes test
records, so it must not be run by an agent under this restriction.

## Scope and evidence

This document tracks the supplied Confluence document, **Payment Flow: Payment,
Charging, and Rollover**, and the supplied Jira snapshots:

- **ADCM-167** — parent payment requirement.
- **ADCM-170** — activation charge, ledger, reservation/finalization, idempotency,
  serialization, declines/retries, and edit locks.
- **ADCM-171** — line-item completion, spend finalization, rollover, and
  overspend.

The Jira connector was unavailable for a live status/duplicate check. These are
existing tickets from the supplied snapshots; no ticket was created or changed.
This implementation is deliberately partial. “Implemented” below means code is
present locally; it does not mean the database change has been deployed or that
the overall payment workflow is operational. The API E2E test setup
automatically runs `prisma migrate deploy` against its local
`admedia_dsp_test` database; the final Prisma status reports all 36 migrations
applied there. No deployment database was accessed.

Product decisions supplied during this work:

- Use the 24-hour spend-finalization window for Text line items.
- Apply ADCM-171's overspend rule: ad.com absorbs overspend; do not charge the
  advertiser again.
- Implement only local API/database/UI groundwork; Clover vaulting and Admedia
  integrations remain blocked.

## PM/TL clarification — 13 October 2026

This clarification updates the earlier blocker assessment below.

- Signup/advertiser verification owns card validation and card storage.
- Enable AVS ZIP and CVV rules in the Clover dashboard.
- Validate with an auth-only pre-authorization, then void immediately when
  validation passes and no hold is needed, or when either check fails.
- At payment time, check only whether the advertiser is verified. Do not rerun
  signup AVS/CVV/pre-authorization checks in the activation/payment workflow.

### Verified documentation and important distinction

The supplied [Clover pre-authorization documentation](https://docs.clover.com/dev/docs/create-pre-authorization)
uses `/v1/charges` with `capture: false`, a token, currency, and an amount in
cents. It describes a **temporary authorization hold**, not a guarantee of no
effect on available funds; its 100-cent example is not an approved validation
amount for this project. No pre-auth amount has been invented here.

The supplied [Clover refund/void documentation](https://docs.clover.com/dev/docs/ecommerce-refunding-payments)
distinguishes voids from refunds and describes voiding sales and
pre-authorizations. Its sale-void timing note must not be treated as proof of
instant release of an authorization hold by a card issuer.

Card validation is now an **upstream signup dependency**, not functionality to
add to payment creation. The exact approved validation amount, applicable void
request/response, and unsuccessful-void handling remain signup-owner questions.
Do not store raw PAN or CVV in the payment database; card-storage handoff must
provide a processor-supported reusable reference.

### Changes from this clarification

| Check       | Approved requirement / dependency                                                                                         | Current status                                                                                                                                                                                         |
| ----------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Done        | Read advertiser verification from the database before accepting payment creation.                                         | `paymentService.create` checks `DspAdvertiser.verified` before payment records, idempotency replay, or processor calls. Unverified advertiser receives HTTP 403 using the existing API error envelope. |
| Done        | Verified advertisers retain the existing payment behavior.                                                                | Existing provider, one-time token charge, payment history, and reconciliation paths are preserved; no new validation charge or void is added.                                                          |
| Done        | Keep AVS/CVV/pre-auth validation out of payment processing.                                                               | Payment code consumes verified status only; no Clover dashboard/API verification automation is added.                                                                                                  |
| Upstream    | AVS/CVV rules enabled in Clover dashboard.                                                                                | PM/TL-approved configuration; actual merchant configuration was not accessed or verified.                                                                                                              |
| Upstream    | Signup performs auth-only validation, immediate void, and card storage.                                                   | Confirmed owner/scope; not implemented or exercised as part of this payment change.                                                                                                                    |
| Dependency  | Signup sets the authoritative advertiser verified flag and supplies reusable card reference.                              | `verified` flag exists; no signup/admin writer or saved-card handoff was identified. This field defaults to false; do not automatically verify existing advertisers.                                   |
| Outstanding | Line-item activation charging, balance/ledger mutations, retry/recovery, completion/rollover jobs and spend finalization. | Still not implemented. The verified check on the existing payment API is not an implementation of the line-item activation executor.                                                                   |

### Revised remaining blockers

| ID  | Dependency / question                             | Owner / exact answer needed                                                                                                                                                                                                                                                              | What remains blocked                                                                                        |
| --- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| B1  | Verified-state and saved-card handoff from signup | Signup/TL: which process writes `DspAdvertiser.verified`, which reusable reference is stored, where/how payment reads it, and how replacement is signalled?                                                                                                                              | Real automatic saved-card activation charging. The current manual payment API still takes a one-time token. |
| B2  | Processor recovery and retry contract             | Payment/TL: idempotency retention, lookup when response/payment ID is missing, error classification, and confirmed-uncharged behavior after transient retry exhaustion. Existing Clover GET-by-charge-ID and idempotency header are present, but do not alone cover missing-ID recovery. | Safe line-item charge retries/recovery.                                                                     |
| B3  | Billing-path final spend                          | Reporting/TL: authoritative Display spend source, units/platform-fee treatment, recorded-time semantics, and reporting-unavailable behavior.                                                                                                                                             | Real final-spend rollover.                                                                                  |
| B4  | Admedia contracts                                 | Admedia/TL: Text start/payment notification, archive pause, reporting API, campaign mapping, test access, and failed-call handling.                                                                                                                                                      | Text start/stop/final spend.                                                                                |
| B5  | Balance-only Text start                           | PM: should a fully balance-funded Text item notify/start Admedia even with no card transaction?                                                                                                                                                                                          | That Text activation branch; no behavior assumed.                                                           |
| B6  | Ledger reservation restoration                    | Billing/TL: approved entry representation/sign/reference for restored reserved balance, preserving immutable entries and reconciliation.                                                                                                                                                 | Complete decline balance/ledger writer.                                                                     |
| B7  | Deployment and integration evidence               | TL: reviewed migration deployment, verified-state rollout/backfill policy, sandbox fixtures/access and live Jira/linked sources.                                                                                                                                                         | Production readiness and complete E2E verification.                                                         |

The signup validation method and payment-side verification responsibility are
now clarified. They must not continue to be reported as unknown payment
business rules. Their upstream implementation/handoff still needs evidence.
Local calculations, completion/rollover eligibility, locking/atomicity,
scheduling, and tests remain **unfinished implementation**, not universally
blocked by these integrations.

## PM/TL review summary

**Coverage accounting:** every requirement visible in the supplied Confluence
payment-flow document and Jira snapshots is represented below, including all
11 ADCM-171 requirements and its 18 acceptance criteria. “Accounted for” means
there is an explicit checklist/trace entry; it does **not** mean implemented.

**Implementation status:** line-item end-date validation, pending/charged
budget-field edit locks, payment schema groundwork, and the approved
advertiser-verification check on payment creation were applied locally.
The complete payment/rollover flow is **not implemented**. In particular,
processor charging, advertiser balance mutations, the payment/recovery and
rollover jobs, spend reporting, and Admedia integration remain outstanding.

**Scope statement:** the supplied Confluence and Jira content are the functional
sources of truth. This document records their requirements and observed code
status; it does not add business rules. The approved 24-hour Text finalization
window and overspend absorption are decisions already supplied in the
conversation, not new assumptions.

## Requirement checklist

| Ref | Requirement                                                                                                                                                                                                                                                                                                                                               | Source                                       | Status                                                                                                                                                                                                                                    |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| R1  | Collect billing details and save the card at sign-up/verification without capture; admin verification gates campaign creation; rejection is final except for admin reversal.                                                                                                                                                                              | Confluence §1; ADCM-167; PM/TL clarification | **Upstream signup scope:** AVS/CVV auth-only validation and immediate void clarified. Payment creation now enforces verified status; signup/admin writer, card handoff and campaign-creation gate remain unverified/not implemented here. |
| R2  | A line item requires an end date. Lifetime budget is the entered amount; daily budget is amount × inclusive flight days. Daily budgets without an end date are unsupported.                                                                                                                                                                               | Confluence §2; ADCM-170                      | **Implemented locally:** end date is required/non-null on API create/patch and UI create. Daily budget calculation and activation charging are not implemented.                                                                           |
| R3  | Charge only once the first time `status_chain_ok(line_item)` becomes true and `charged_at` is empty: line item and campaign active, approved creative implied by active status, and current campaign-local time within inclusive flight dates. Check relevant state changes and sweep at least every five minutes.                                        | Confluence §2; ADCM-170                      | **Blocked:** activation eligibility evaluator, event triggers, and sweep are not implemented.                                                                                                                                             |
| R4  | Process ready rollovers first, apply available balance up to total budget, charge the card only for the remainder, and debit the applied balance. A zero card amount still consumes balance and marks the line item charged.                                                                                                                              | Confluence §2, §4; ADCM-170/171              | **Blocked:** no charge/rollover service. Schema fields alone do not move money.                                                                                                                                                           |
| R5  | On success, record charged time, applied/card amounts, and total remaining budget; start delivery and lock channel/budget/bid/pacing/flight fields. Keep line-item name and creative attachment changes editable. Fields are also locked during a pending attempt.                                                                                        | Confluence §2; ADCM-170                      | **Partially implemented:** fields and UI/API locks exist for charged/pending line items; no successful charge or delivery transition exists.                                                                                              |
| R6  | Reserve atomically under advertiser serialization: process eligible rollovers, debit balance, and write pending card ledger entry. Charge without holding a DB lock; finalize success or restore reserved balance on decline. Recover pending outcomes from processor without loss or duplication.                                                        | Confluence §2; ADCM-170                      | **Blocked:** reservation, processor call orchestration, balance restoration, recovery job, and serialization are not implemented.                                                                                                         |
| R7  | Enforce one charge per line item under advertiser lock. Send line-item ID plus attempt number as idempotency key; transient retries reuse it, and only an advertiser retry after decline increments the attempt.                                                                                                                                          | Confluence §2; ADCM-170                      | **Blocked:** no charge executor, idempotency handling, or advertiser lock.                                                                                                                                                                |
| R8  | Decline restores reserved balance, leaves `charged_at` empty, prevents delivery, returns the line item to Pending with the specified tooltip, and emails the advertiser. Do not auto-retry declines. Retry by explicit line-item action or a newly saved validated card; new card retries failed, unended flights. An expired flight completes uncharged. | Confluence §2; ADCM-170                      | **Blocked:** decline states/actions, notifications, retry selection, and flight-end handling are not implemented.                                                                                                                         |
| R9  | Retry transient timeouts/processor errors automatically up to three times using the same idempotency key.                                                                                                                                                                                                                                                 | Confluence §2; ADCM-170                      | **Blocked:** no processor integration or retry worker.                                                                                                                                                                                    |
| R10 | Deduct DSP impression spend using `supply_cost / (1 - platform_fee)`; Text spend comes from Admedia reporting, not DSP impressions.                                                                                                                                                                                                                       | Confluence §3; ADCM-167                      | **Blocked:** no complete billing-path spend source or Admedia reporting integration.                                                                                                                                                      |
| R11 | Charged, non-archived items complete when flight end passes regardless of Active/Paused/Pending; `ended_at` is the flight-end instant (start of next day in campaign timezone). Set it once.                                                                                                                                                              | Confluence §4; ADCM-171                      | **Blocked:** no completion/ended-time scheduler or transition.                                                                                                                                                                            |
| R12 | Early archive sets `ended_at` to archive time; Text archive immediately syncs to Admedia and pauses its campaign. Display leaves bidder at next catalog refresh (within five minutes); wins during the gap remain spend. Uncharged archived items do not roll over; later archive preserves an existing completion end time.                              | Confluence §4; ADCM-171                      | **Blocked:** archive timing is not connected to these payment/Admedia/bidder behaviors.                                                                                                                                                   |
| R13 | Rollover only for completed/early-archived, charged, not-yet-rolled items after 24 hours from `ended_at`, when spend is final.                                                                                                                                                                                                                            | Confluence §4; ADCM-171                      | **Blocked:** eligibility and rollover scheduler are not implemented.                                                                                                                                                                      |
| R14 | Recalculate final remaining budget as `MAX(0, total_budget - final_spend)` from the billing reporting path, including spend in the finalization window. Text uses Admedia reporting. Do not use the bidder's pacing counter; ignore spend recorded after rollover.                                                                                        | Confluence §4; ADCM-171                      | **Blocked:** reporting-path spend and finalization are unavailable. The 24-hour Text window is the approved decision for this work.                                                                                                       |
| R15 | Credit remaining budget to advertiser balance, set line-item remaining budget to zero, never make it negative, and record overspend absorbed by ad.com. Record a rollover ledger entry even for zero amount.                                                                                                                                              | Confluence §4; ADCM-171                      | **Blocked:** no rollover operation or ledger writer.                                                                                                                                                                                      |
| R16 | Process rollovers hourly (up to one-hour lag) and immediately before that advertiser's activation charge, but only after the 24-hour window. Use whole cents, rounded half up.                                                                                                                                                                            | Confluence §2, §4; ADCM-170/171              | **Blocked:** no scheduled/immediate processor, money arithmetic, or concurrency control.                                                                                                                                                  |
| R17 | Ledger records every balance/card movement and is billing-history source; entries are not deleted or amount-edited, with only card-charge status mutable. Balance equals sum of balance entries. Card charge records processor reference/status; rollover records overspend.                                                                              | Confluence §5; ADCM-167/170/171              | **Partially implemented:** schema/migration defines payment ledger groundwork; no invariant enforcement, ledger service, history API, or reconciliation exists.                                                                           |
| R18 | For Text line items, alert Admedia after a payment is processed and card charged so Admedia can start the campaign.                                                                                                                                                                                                                                       | Confluence §6; ADCM-167                      | **Blocked:** no payment event or Admedia start-campaign integration.                                                                                                                                                                      |

## Jira acceptance-criteria checklist

### ADCM-170 — charging a credit card

The supplied ADCM-170 material requires all of the following. Its acceptance
criteria text was supplied as a ticket snapshot. The resent snapshot explicitly
identifies R1–R8 and AC1–AC16; the numbered criteria are listed below.

| Criterion | Required outcome                                                                                                   | Current implementation                                                       |
| --------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- |
| AC1       | No balance: charge full $1,000 and set charged_at.                                                                 | Not implemented.                                                             |
| AC2       | $50 balance against $1,000 budget: charge $950; balance zero.                                                      | Not implemented.                                                             |
| AC3       | $1,500 balance against $1,000 budget: no processor request; balance $500; mark charged and record balance applied. | Not implemented.                                                             |
| AC4       | Already charged: no second charge or balance deduction on resume.                                                  | Not implemented.                                                             |
| AC5       | Inactive campaign or future start: no charge until every eligibility condition holds.                              | Not implemented.                                                             |
| AC6       | Decline: restore $50, stay uncharged/non-delivering, Pending with exact tooltip, email advertiser.                 | Not implemented.                                                             |
| AC7       | Concurrent $400 items with $500 balance: total applied $500, card charges $300.                                    | Not implemented.                                                             |
| AC8       | UI/API reject locked fields after charge with clear message.                                                       | Partial: locks exist; targeted tests do not cover every field.               |
| AC9       | Before charge with no pending attempt: channel/budget edits work normally.                                         | Existing edit behavior retained; full criterion not independently exercised. |
| AC10      | Ledger funding sources match applied/card formula.                                                                 | Schema only; no activation writer.                                           |
| AC11      | Future flight becomes charged within five minutes of campaign-local start.                                         | Not implemented.                                                             |
| AC12      | $100 daily for ten inclusive days commits $1,000.                                                                  | Not implemented.                                                             |
| AC13      | Explicit retry/new validated card uses a new attempt number after decline.                                         | Not implemented.                                                             |
| AC14      | Processor success + failed DB finalize: recovery finalizes without a second charge.                                | Not implemented.                                                             |
| AC15      | Transient timeout: up to three retries, backoff, same key, never double charge.                                    | Not implemented.                                                             |
| AC16      | Charged or pending: dates and budget fields locked.                                                                | Partial: API/UI locks exist; exhaustive tests outstanding.                   |

| Check | Jira requirement                                                                                                                                                        | Also in Confluence | Covered in analysis | Applied locally                                                                                                                     |
| ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| ☐     | Charge on first eligible active status chain, only when not previously charged; reevaluate on activation/creative approval and at least every five minutes.             | §2                 | Yes — R3            | No — eligibility triggers/sweep absent.                                                                                             |
| ☐     | Require end date; lifetime total is budget; daily total uses amount × inclusive flight days.                                                                            | §2                 | Yes — R2            | Partial — required end date only; total calculation absent.                                                                         |
| ☐     | Apply available balance first and card-charge only the remainder; no card transaction for zero amount, while recording the charge state.                                | §2                 | Yes — R4            | No — charge/balance logic absent.                                                                                                   |
| ☐     | Before calculating charge, process only ready rollovers; serialize charges and balance changes per advertiser.                                                          | §2; ADCM-171 R8–R9 | Yes — R4/R6         | No — no transaction/row-lock workflow.                                                                                              |
| ☐     | Reserve balance and pending card ledger entry atomically; release lock during processor call; finalize success or restore reservation on decline.                       | §2                 | Yes — R6            | No — ledger writer and processor orchestration absent.                                                                              |
| ☐     | Charge a line item at most once; use line-item ID plus attempt number for idempotency; reuse key on transient retry; increment only for advertiser retry after decline. | §2                 | Yes — R7            | No — idempotency/attempt handling absent.                                                                                           |
| ☐     | On decline, restore balance, keep item uncharged/non-delivering, return to Pending with the specified tooltip, email advertiser, and do not auto-retry decline.         | §2                 | Yes — R8            | No — failure-state flow absent.                                                                                                     |
| ☐     | Retry transient errors automatically up to three times; recover pending results by asking processor what happened, avoiding lost or duplicate charges.                  | §2                 | Yes — R6/R9         | No — retry/recovery absent.                                                                                                         |
| ☐     | Allow explicit retry or retry failed, unended items after a new validated card; an item whose flight ends first completes without a charge.                             | §2                 | Yes — R8            | No — retry and expiry transitions absent.                                                                                           |
| ☐     | Lock channel, budget, bid, pacing, and flight fields during pending charge and after charge; leave name and creative attach/detach editable.                            | §2                 | Yes — R5            | Partial — API/UI locks exist; regression test verifies locked channel/budget and editable name, not every field/creative operation. |

### ADCM-171 — roll over remaining budget

| Check | Jira requirement / AC                                                                                                                                                                                     | Covered in analysis | Applied locally                                  |
| ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ------------------------------------------------ |
| ☐     | R1: only Completed/Archived, charged, not already rolled over.                                                                                                                                            | Yes — R13           | No — rollover eligibility/job absent.            |
| ☐     | R2: set archive end time at archive; completion end time at campaign-local next-day boundary; set once and preserve on later archive.                                                                     | Yes — R11–R12       | No — end-state handling absent.                  |
| ☐     | R3: finalize at 24 hours; use billing-path spend (Admedia for Text), include the window, exclude spend after rollover, not the realtime pacing counter; daily archived items retain full committed total. | Yes — R14           | No — reporting/finalization absent.              |
| ☐     | R4: Text archive syncs immediately and pauses Admedia; Display leaves bidder on next refresh ≤5 minutes; gap wins count as spend.                                                                         | Yes — R12           | No — synchronization/spend attribution absent.   |
| ☐     | R5: cents rounded half up; remaining budget never negative; overspend is platform-absorbed and not card-charged.                                                                                          | Yes — R15–R16       | No — rollover arithmetic absent.                 |
| ☐     | R6: BALANCE_CREDIT, including zero; include raw overspend; set rolled_over_at; available balance reconciles to balance ledger entries.                                                                    | Yes — R15/R17       | Schema only; no ledger operation/reconciliation. |
| ☐     | R7: balance, remaining-budget reset, ledger row, rolled_over_at are atomic in one DB transaction.                                                                                                         | Yes — R15/R17       | No — rollover transaction absent.                |
| ☐     | R8: once-only, same advertiser row lock as charge reserve, recheck under lock, serialize every balance operation.                                                                                         | Yes — R6/R13        | No — lock/idempotency absent.                    |
| ☐     | R9: before activation reserve, process matured rollovers oldest-first in same serialized operation; exclude immature rollovers.                                                                           | Yes — R4/R16        | No — charge reserve/rollover absent.             |
| ☐     | R10: hourly rollover job; at most one-hour lag after 24-hour maturity.                                                                                                                                    | Yes — R16           | No — scheduler absent.                           |
| ☐     | R11: charged, non-archived item completes after flight end in any Active/Paused/Pending state; sweep at least every five minutes; uncharged items unaffected.                                             | Yes — R11           | No — completion sweep absent.                    |
| ☐     | AC1: $200 rollover adds to existing $50; remaining becomes zero; timestamp and $200 ledger row.                                                                                                           | Yes — T16           | No — no rollover execution/test.                 |
| ☐     | AC2: fully spent produces no balance change, but timestamp and $0 ledger row.                                                                                                                             | Yes — T16           | No — no rollover execution/test.                 |
| ☐     | AC3: overspend results in zero remaining, unchanged balance, no card charge, raw overspend recorded.                                                                                                      | Yes — T16           | No — no rollover execution/test.                 |
| ☐     | AC4: repeated rollover does not change balance.                                                                                                                                                           | Yes — T15           | No — no rollover execution/test.                 |
| ☐     | AC5: at 23 hours do nothing; after 24 hours credit.                                                                                                                                                       | Yes — T15           | No — no rollover scheduler/test.                 |
| ☐     | AC6: mature $300 rollover precedes $500 activation; apply $300 and charge $200.                                                                                                                           | Yes — T7/T15        | No — no charge/rollover workflow.                |
| ☐     | AC7: two mature rollovers of $100 and $150 precede $400 activation; charge $150.                                                                                                                          | Yes — T7/T15        | No — no charge/rollover workflow.                |
| ☐     | AC8: a $300 rollover only 2 hours mature is not applied to the $500 activation; full card charge now and later rollover.                                                                                  | Yes — T15           | No — no charge/rollover workflow.                |
| ☐     | AC9: early archived, charged $1,000 item with $400 spend credits $600 after window.                                                                                                                       | Yes — T13/T16       | No — no archive/rollover execution.              |
| ☐     | AC10: archived before charge yields no rollover and no balance change.                                                                                                                                    | Yes — T13/T15       | No — no archive/rollover execution.              |
| ☐     | AC11: archiving active Text item pauses Admedia campaign and prevents further spend.                                                                                                                      | Yes — T18           | No — Admedia sync absent.                        |
| ☐     | AC12: archive after completion/rollover does not produce a second rollover.                                                                                                                               | Yes — T13/T15       | No — no rollover execution.                      |
| ☐     | AC13: archive completed item inside 24-hour window preserves flight-end `ended_at`; window does not restart.                                                                                              | Yes — T13           | No — end-state handling absent.                  |
| ☐     | AC14: charged Paused/Pending item completes at flight end and becomes rollover-eligible after window.                                                                                                     | Yes — T13           | No — completion sweep absent.                    |
| ☐     | AC15: delayed sweep still sets `ended_at` to campaign-local flight boundary, not detection time.                                                                                                          | Yes — T13           | No — completion sweep absent.                    |
| ☐     | AC16: $100 daily × 10 days, $350 spend, archive mid-flight credits $650 after window.                                                                                                                     | Yes — T6/T16        | No — total-budget/rollover arithmetic absent.    |
| ☐     | AC17: balance equals sum of ledger balance entries after arbitrary charges/rollovers.                                                                                                                     | Yes — T17           | No — reconciliation absent.                      |
| ☐     | AC18: if realtime counter differs from billing-path total, rollover uses billing-path total.                                                                                                              | Yes — T14           | No — billing spend source absent.                |

An empty `☐` means the full requirement/criterion has **not** been implemented
and verified. Source-to-analysis coverage is recorded separately in “Covered in
analysis”; “Applied locally” describes the actual code state. Schema fields by
themselves do not count as implementing an acceptance criterion.

## Changes actually applied

The latest approved change additionally checks advertiser verification before
the existing payment-creation flow, including idempotent replay. This uses the
existing auth collection and standard Forbidden error, without adding API
endpoints or signup card-verification operations.

| Change                                                          | Source requirement                                                                        | Files / behavior                                                                                                                                                                                                                                | Verification                                                                                                                          |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Require a line-item end date                                    | Confluence §2; ADCM-170 budget/flight requirement                                         | API create/patch schemas, types, route parsing, and service; UI removes no-end-date option and requires an end date.                                                                                                                            | API line-item E2E includes required-end-date checks; typechecks pass.                                                                 |
| Lock budget-related edits during a pending or successful charge | Confluence §2; ADCM-170 edit-lock requirement                                             | API line-item detail reports `chargedAt`/`chargePending`; service rejects channel, budget, bid, pacing, and flight-field edits while pending/charged. UI disables those fields. Name and creative operations are not included in the lock list. | E2E lock test covers pending/charged rejection and editable name.                                                                     |
| Add payment state/ledger schema groundwork                      | Confluence §2, §4, §5; ADCM-167/170/171 schema dependencies                               | `DspAdvertiser.verified` and `availableBalance`; line-item `chargedAt`, `remainingBudget`, `endedAt`, `rolledOverAt`; payment-ledger model/migration with entry type, status, amount, overspend, idempotency and processor-reference fields.    | Prisma migration applied by test setup to local `admedia_dsp_test`; Prisma reports test DB up to date. No deployment DB was accessed. |
| Correct lock detection for omitted patch values                 | Required editability of line-item name; regression found while implementing ADCM-170 lock | Service ignores optional patch properties whose value is `undefined`, so an allowed name-only edit is not rejected.                                                                                                                             | Targeted API suite: 24/24 passed.                                                                                                     |

The implementation does **not** include automatic saved-card line-item charging,
balance or ledger mutation services, eligibility/recovery/rollover/completion
schedulers, spend collection/finalization, advertiser verification admin
workflow, or Admedia start/pause/reporting integration. Those are explicitly
shown as not applied above and in the traceability table.

## Coverage completeness and remaining source questions

- **Checklist coverage:** Confluence §§1–6, ADCM-170's supplied charge
  requirements, and ADCM-171 R1–R11 / AC1–AC18 are each represented in this
  document. No numbered ADCM-171 requirement or acceptance criterion from the
  supplied ticket snapshot is omitted.
- **Implementation completeness:** payment requirements are **not** fully
  applied. Only the local changes listed above are verified. The remaining
  requirements are outstanding, not silently assumed or reported as done.
- **Evidence limitation:** Jira was not authenticated/live-queried. This
  completeness statement is against the Confluence text and Jira snapshots
  supplied in this conversation, not any later ticket edits or linked content
  that was not provided.
- **PM decision needed:** Confluence §6 says Admedia is alerted when payment is
  processed and the card was charged, while §2 permits a zero card charge when
  available balance covers the total. The supplied sources do not state
  whether a Text line item funded entirely by balance should start in Admedia.
  This document does not invent that behavior.
- **Resolved by resent ADCM-170 R7:** transient failures retry up to three
  times with backoff and the same key. Recovery queries the processor; if it
  has no record, treat the attempt as a decline. The processor lookup contract
  remains a dependency, but terminal no-record behavior is not an open product
  decision.
- **Jira dependency correction:** ADCM-171 notes ADCM-170's reserve-step
  cross-reference should point to ADCM-171 R9 (rollover priority), not R7.
- **Text attribution:** ADCM-171 marks whether Text needs a longer attribution
  window as open. The approved decision for this work is 24 hours; Admedia
  reporting integration remains blocked.

### Requirement gaps, conflicts, and dependencies

- The supplied ADCM-170 text refers to rollover priority using an acceptance
  criterion reference that does not match the rollover criteria in ADCM-171.
  This trace uses the substance of the supplied ticket snapshots and Confluence,
  not inferred criterion numbering.
- ADCM-167's supplied negative-balance note says a card charge would “never
  happen”; Confluence and ADCM-171 explicitly require overspend to be absorbed
  by ad.com and recorded. The later, specific overspend behavior is followed.
- The payment processor interface accepts a one-time Clover `sourceToken`;
  `DspPaymentMethod.providerPaymentMethodId` exists but is attached to an
  existing payment, not an established signup-owned reusable-card handoff.
  Signup owns validation/storage; the reusable-reference handoff is still a
  prerequisite for real automatic activation charges.
- No Admedia spend-reporting API, Text pause/start synchronization, or
  billing-path spend source was found. These block R10–R14 and R18.
- Signup owns advertiser verification. Payment creation now checks the
  database `verified` flag; signup/admin must provide its authoritative writer
  and the saved-card handoff. No verification/admin workflow is added here.
- Test setup automatically applied the payment migration and the repository's
  other migrations to local `admedia_dsp_test`; Prisma status reports that test
  database up to date. Production/deployment database status is unknown.

## High-level workflow

```mermaid
flowchart TD
    A[Advertiser enters billing details and card] --> B[Admin reviews verification]
    B -->|Rejected| C[Rejected; admin-only reversal]
    B -->|Verified| D[Campaign and line item setup]
    D --> E{Eligible: active chain, approved creative, inclusive flight dates?}
    E -->|No| D
    E -->|Yes; charged_at empty| F[Reserve balance and pending ledger under advertiser serialization]
    F --> G[Charge remaining amount with idempotency key]
    G -->|Success| H[Finalize ledger and charged state; begin delivery]
    G -->|Decline| I[Restore balance; Pending; notify; explicit retry only]
    G -->|Transient error| J[Retry up to three times with same key]
    J --> G
    I -->|Retry or validated new card, flight not ended| F
    H --> K[Delivery spend recorded by billing path]
    K --> L{Completed or early archived?}
    L -->|No| K
    L -->|Yes; wait 24h for final spend| M[Recalculate remaining budget]
    M --> N[Ledger credit incl. zero; balance increases; remaining budget becomes zero]
    H --> O[Text: notify Admedia after successful card charge]
```

## Detailed workflow diagrams

### A. Activation charge and payment outcomes

The verified-advertiser guard is implemented in the existing payment API. The
automatic line-item workflow below remains the required design, not a deployed
executor. Its future payment entry must also enforce the same approved guard.

```mermaid
flowchart TD
    A[Trigger: line-item or campaign activation, or creative approval change] --> AV
    B[Eligibility sweep: runs at least every 5 minutes] --> AV
    AV{Advertiser verified?}
    AV -->|No| AN[Do not process payment; signup/verification must complete]
    AV -->|Yes| C
    C{status_chain_ok and charged_at is empty?}
    C -->|No| N[No charge; wait for next relevant change or sweep]
    C -->|Yes| D[Derive total budget: Lifetime amount; Daily amount x inclusive flight days]
    D --> E[Acquire advertiser serialization / balance lock]
    E --> F[Process only matured eligible rollovers, oldest ended_at first]
    F --> G[Calculate applied = MIN(balance, total); charge = MAX(0, total - applied)]
    G --> H[Reserve applied balance; write balance-applied and pending card-charge ledger entries]
    H --> I{Card charge amount is zero?}
    I -->|Yes| S[No processor request]
    I -->|No| J[Release DB lock; call card processor using line-item ID + attempt key]
    J --> K{Processor result}
    K -->|Success| S
    K -->|Decline| L[Mark card ledger failed; restore reserved balance with compensating ledger movement]
    K -->|Transient error| M[Retry automatically up to 3 times with same idempotency key]
    M --> J
    K -->|Outcome unresolved / pending| R[Recovery asks processor for charge outcome]
    R -->|Processor confirms success| S
    R -->|Processor confirms decline| L
    R -->|Confirms not charged; transient failure| RX[Apply transient retry policy]
    RX -->|Retries remain| M
    RX -->|Retry limit reached| XX[Recovery queries processor; no record means decline per ADCM-170 R7]
    XX -->|No processor record| L
    R -->|Still unresolved| RR[Keep pending; recovery must resolve before finalizing]
    S --> T[Finalize success: record charged_at, balance_applied, card_charged; remaining_budget = total]
    T --> U[Begin delivery; lock channel, budget, bid, pacing, flight fields]
    T --> V{Text line item and card was charged?}
    V -->|Yes| W[Alert Admedia so campaign can start]
    V -->|No| X[No card-charge-triggered Admedia alert specified]
    L --> Y[Keep charged_at empty; prevent delivery; return to Pending]
    Y --> Z[Show tooltip: Payment failed, update your card; email advertiser]
    Z --> AA{Advertiser retries before flight ends?}
    AA -->|Explicit Retry payment| AB[Increment attempt number; new attempt key]
    AA -->|Saves new validated card| AC[Increment attempts and retry all failed items whose flights have not ended]
    AA -->|Flight ends first| AD[Complete without charging; no rollover for uncharged item]
    AB --> E
    AC --> E
    U --> AE[Editable: line-item name and creative attach/detach]
    U --> AF[Locked: channel, budget amount/type, bid strategy/amount, pacing, start/end]
    H --> AG[The same budget fields are read-only during pending charge]
```

### B. Delivery end, spend finalization, and rollover

```mermaid
flowchart TD
    A[Charged line item delivers] --> B[Spend recorded by billing path]
    B --> C{End condition}
    C -->|Flight end passes| D{Current status Active, Paused, or Pending and not Archived?}
    D -->|Yes| E[Completion sweep at least every 5 minutes]
    E --> F[Set Completed; ended_at = flight-end instant in campaign timezone]
    D -->|No: already Archived| G[Keep existing archive ended_at]
    C -->|Archived early| H[Set ended_at = archive action time, only if ended_at is NULL]
    H --> I{Channel}
    I -->|Text| J[Immediately sync archive to Admedia and pause campaign]
    I -->|Display| K[Remove from bidder at next catalog refresh, within 5 minutes]
    K --> L[Count wins during refresh gap as spend]
    F --> M
    G --> M
    H --> M
    J --> M
    L --> M
    M{Completed or Archived AND charged_at set AND rolled_over_at NULL?}
    M -->|No| N[No rollover; uncharged archived items are excluded]
    M -->|Yes| O[Wait until ended_at + 24 hours <= now]
    O -->|Not mature| P[Do not credit yet; hourly job will check later]
    O -->|Mature| Q[Read final billing-path spend, including spend recorded in the 24-hour window]
    Q{Channel / reporting source}
    Q -->|Text| R[Read Admedia reporting API]
    Q -->|Display| QB[Read billing-path spend]
    R --> QC[Use billing-path spend; not bidder realtime pacing counter]
    QB --> QC
    QC --> S[Recalculate remaining = MAX(0, total_budget - final_spend); round whole cents half up]
    S --> T[Acquire same advertiser lock; recheck rolled_over_at and serialize balance operation]
    T --> U[One DB transaction: credit positive remainder; reset remaining to zero]
    U --> V[Write BALANCE_CREDIT ledger row even for $0; record raw overspend when present]
    V --> W[Set rolled_over_at; commit balance, remaining, ledger, timestamp atomically]
    W --> X[No second rollover; ignore spend recorded after rollover]
    Y[Hourly rollover job: eligible rows; up to 1-hour lag] --> O
    Z[Activation reserve takes same advertiser lock] --> Z1[Select matured eligible rollovers; oldest ended_at first]
    Z1 --> Z2[Apply ready rollovers before charging; skip immature ones]
    Z2 --> ZA[Calculate activation charge from updated balance in same serialized operation]
```

### C. State and money movement summary

| Event                       | Line-item state/data                                                               | Balance and ledger                                                             | Delivery / external effect                                               |
| --------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| Eligible, not charged       | Pending charge attempt; budget fields read-only during attempt                     | Reserve applied balance; pending card ledger row for remainder                 | No delivery until successful charge                                      |
| Charge succeeds             | Set `charged_at`; record applied/card amounts; set remaining to total              | Finalize card ledger succeeded; no ledger row deleted                          | Delivery begins; Text notification only when card was charged            |
| Charge amount is zero       | Mark charged and set remaining to total despite no card request                    | Consume applied balance; no card transaction                                   | Delivery begins per successful charge rules                              |
| Decline                     | Leave `charged_at` empty; Pending; exact payment-failed tooltip                    | Restore reserved balance; mark card ledger failed                              | No delivery; email advertiser; decline is not auto-retried               |
| Flight end while charged    | Complete even from Active, Paused, or Pending; set flight-boundary `ended_at` once | None until rollover matures                                                    | Delivery ends                                                            |
| Early archive while charged | Archived; set archive-time `ended_at` only if absent                               | None until rollover matures                                                    | Text pauses Admedia immediately; Display removal at next catalog refresh |
| Mature rollover             | Keep completed/archived state; set remaining to zero; set `rolled_over_at` once    | Credit remaining amount, possibly $0; record overspend; all row changes atomic | No spend collected after rollover                                        |

## Detailed workflow and state transitions

1. **Signup and verification**
   1. Advertiser enters credit card, billing name, and billing address.
   2. Save the card without a charge.
   3. Admin verifies or rejects. Rejection is final for the advertiser unless
      an admin reverses it; only verified advertisers may create campaigns.
2. **Eligibility and budget**
   1. Every line item has an end date. Lifetime total is `budget_amount`;
      daily total is `budget_amount × number_of_flight_days`.
   2. Evaluate the active campaign and active line-item chain, creative
      approval, and inclusive start/end dates using the campaign timezone.
   3. Evaluate on relevant activation/approval changes and on a sweep at least
      every five minutes, including future-start items with no triggering event.
   4. Do nothing if ineligible or `charged_at` is already set.
3. **Reserve, charge, and finalize**
   1. Serialize work by advertiser. Under the advertiser balance lock, apply
      only rollovers whose 24-hour window has passed, then reserve available
      balance and write a pending card-charge ledger entry.
   2. Calculate `applied = MIN(available_balance, total_budget)` and
      `charge = MAX(0, total_budget - applied)`. If `charge` is zero, do not
      call the card processor; still consume applied balance and mark charged.
   3. Release the DB lock before calling the processor. Use the line-item ID
      and attempt number for idempotency; transient retries reuse the key.
   4. Success: mark card ledger succeeded, record processor reference and
      `charged_at`, `balance_applied`, `card_charged`, and set
      `remaining_budget = total_budget`. Begin delivery.
   5. Decline: mark card ledger failed, restore reserved balance, leave
      `charged_at` empty, prevent delivery, return to Pending with tooltip
      “Payment failed, update your card”, and email the advertiser. Do not
      automatically retry declines.
   6. Transient processor errors/timeouts: automatically retry up to three
      times using the same idempotency key. A recovery job asks the processor
      to resolve any pending charge before deciding whether to finalize or
      restore; it must not lose or duplicate a charge.
   7. Advertiser may retry a declined line item or save a newly validated
      card, which retries all failed line items whose flights have not ended.
      If flight ends first, complete the line item without charging it.
   8. While pending or charged, lock channel type, budget amount/type, bid
      strategy/amount, pacing, and start/end dates. Keep name and creative
      attach/detach editable.
4. **Delivery**
   1. Deduct each DSP win's `supply_cost / (1 - platform_fee)` from remaining
      budget. `platform_fee` is a fraction.
   2. Text line items use Admedia-reported spend, not DSP impressions.
5. **End, final spend, and rollover**
   1. A charged, non-archived item becomes Completed after its flight end,
      regardless of current Active, Paused, or Pending status. Set `ended_at`
      once to start of the next day in campaign timezone. An early archive uses
      archive time; an item archived after completion retains its original
      `ended_at`. An item archived before charge has nothing to roll over.
   2. Text archive immediately syncs to Admedia and pauses its campaign.
      Display removal is at the next catalog refresh (within five minutes);
      wins in that gap count as spend.
   3. Wait 24 hours after `ended_at`. At that point obtain final spend from the
      billing reporting path, including reports received during that window;
      use Admedia reporting for Text. Do not use the bidder pacing counter and
      do not collect spend recorded after rollover.
   4. For eligible items (Completed or early archived, charged, not already
      rolled over), calculate `remaining_budget = MAX(0, total_budget -
final_spend)`. Round money to whole cents, half up. Overspend is absorbed
      by ad.com and recorded; it never creates another advertiser charge.
   5. Credit remaining budget to available balance, set remaining budget to
      zero, and write a ledger credit even when its amount is zero. The hourly
      job may be up to one hour late. Before an activation charge, process only
      rollovers whose 24-hour window has passed.
6. **Ledger**
   - Record balance-applied, card-charge (pending/succeeded/failed plus
     processor reference), and balance-credit/overspend movements.
   - Never delete an entry or edit its amount; the only mutable field is card
     charge status. Available balance must reconcile to balance entries.
   - Ledger is the source of billing history and support traceability.

## Existing Jira coverage

| Ticket   | Requirement areas represented in supplied snapshot                                                                                                  | Relationship / action                             |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| ADCM-167 | Parent payment requirement and overall payment flow                                                                                                 | Existing parent; no duplicate created.            |
| ADCM-170 | First eligible charge; totals/rounding; balance priority; reserve/finalize; idempotency; serialization; pending recovery; decline/retry; edit locks | Existing child; remains source for charge work.   |
| ADCM-171 | Completion/end time; archive; final spend; eligibility; hourly and pre-charge rollover; overspend                                                   | Existing child; remains source for rollover work. |

Live Jira status and duplicate checks could not be performed because the Jira
connector required authentication. No issue was created or updated.

## Implementation and traceability

| Requirement      | Workflow stage                              | Jira                                       | Code/test evidence                                                                                                                                                                                                                                                                                                         | Result                                                                                               |
| ---------------- | ------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| R1               | Signup/verification and payment eligibility | ADCM-167; PM/TL clarification              | `DspAdvertiser.verified`; `src/modules/payments/payment.service.ts` checks current verified status; `tests/payments.e2e.test.ts` covers unverified denial, verified success and revoked-verification replay denial.                                                                                                        | Payment check implemented/tested; upstream verification/card-storage handoff still required.         |
| R2               | Budget/flight setup                         | ADCM-170                                   | `src/modules/line-items/line-item.schema.ts`, `line-item.types.ts`, `line-item.service.ts`, `line-item.routes.ts`; UI `src/features/line-item/pages/AddLineItem.tsx`, `src/features/line-item/utils/helpers/line-item.helpers.ts`, `src/features/line-item/utils/types/line-item.types.ts`; `tests/line-items.e2e.test.ts` | Required end date enforced; daily total/charge remains blocked.                                      |
| R3–R4, R6–R9     | Eligibility/charge                          | ADCM-170; ADCM-171 for ready rollovers     | Schema fields and ledger model in `prisma/schema.prisma`; no trigger, worker, payment service, lock, retry, recovery, or notification                                                                                                                                                                                      | Not implemented.                                                                                     |
| R5               | Charge state/edit lock                      | ADCM-170                                   | API `src/modules/line-items/line-item.query.ts` and `line-item.service.ts`; UI `src/features/line-item/components/LineItemDetailsForm.tsx`, `src/features/line-item/pages/LineItemDetailPage.tsx`; lock case in `tests/line-items.e2e.test.ts`                                                                             | Pending/charged budget-field lock works locally; successful charge/delivery does not exist.          |
| R10, R14         | Spend/final spend                           | ADCM-167; ADCM-171                         | No billing-path spend source or Admedia reporting integration found                                                                                                                                                                                                                                                        | Not implemented.                                                                                     |
| R11–R13, R15–R16 | Completion/rollover                         | ADCM-171; ADCM-170 for pre-charge ordering | `prisma/schema.prisma` has `endedAt`, `rolledOverAt`, balance and ledger groundwork; no state transition/scheduler/credit path                                                                                                                                                                                             | Not implemented.                                                                                     |
| R17              | Ledger                                      | ADCM-167/170/171                           | `prisma/schema.prisma` and `prisma/migrations/20261013120000_adcm_167_payment_balance_and_line_item_state/migration.sql`                                                                                                                                                                                                   | Schema groundwork; migration applied in local test DB only; no ledger writer/reconciliation/history. |
| R18              | Text Admedia activation                     | ADCM-167                                   | No payment-to-Admedia campaign-start integration found                                                                                                                                                                                                                                                                     | Not implemented.                                                                                     |

The migration is applied in the local test database only. It must still be
reviewed and deployed through the approved database deployment process before
relying on these schema fields in another environment.

## Test plan

No behavior below is claimed passed unless explicitly marked **Executed**.
The repository has no configured frontend unit-test runner; do not add one
without approval. E2E/processor/scheduler tests require their missing
integrations and approved test fixtures.

| Case                                     | Preconditions / data                                                                         | Steps                                                                                                  | Expected result                                                                                                                                              | Evidence/status                                                                                                                                                                                                 |
| ---------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| T1 Required flight end                   | Valid advertiser/campaign; omit `endDate`, then send null                                    | POST and PATCH line item                                                                               | Create rejects missing end; patch rejects null; valid end accepted                                                                                           | **Executed:** API line-item E2E suite.                                                                                                                                                                          |
| T2 Locked fields pending                 | Line item has pending card ledger entry                                                      | Patch each locked budget/channel/bid/pacing/flight field; separately patch name and creatives          | Locked edits rejected; name/creative operations remain editable                                                                                              | **Executed:** lock test verifies channel/budget rejection and name edit; creative edit paths not independently tested.                                                                                          |
| T3 Locked fields charged                 | Line item has `chargedAt` and succeeded card ledger entry                                    | Patch locked fields; patch name                                                                        | Locked edits rejected; name edit succeeds                                                                                                                    | **Executed:** lock test.                                                                                                                                                                                        |
| T4 Eligibility boundary matrix           | Active campaign/item; creative approved; flight start/end in campaign timezone               | Check before start, at start, during flight, at end, after end; vary each active/approval prerequisite | Eligible only when every documented condition holds and both flight dates are inclusive                                                                      | **Not executed:** no eligibility worker/API exists.                                                                                                                                                             |
| T5 Scheduled eligibility                 | Future-dated otherwise eligible item with no state change                                    | Advance through start; observe five-minute sweep                                                       | Exactly one activation attempt occurs once eligible                                                                                                          | **Not executed:** sweep absent.                                                                                                                                                                                 |
| T6 Lifetime/daily calculation            | Lifetime budget and daily budget across inclusive flight dates                               | Calculate expected totals; test unsupported daily/no-end input                                         | Lifetime equals entered amount; daily equals amount × flight days; missing end rejected                                                                      | End-date rejection **Executed**; calculation/charge **not implemented**.                                                                                                                                        |
| T7 Balance/card arithmetic               | Balance less than, equal to, and greater than total; also zero total                         | Trigger charge with controlled processor                                                               | Apply `MIN`; charge remainder with `MAX`; no card call at zero; deduct applied funds and mark charged                                                        | **Not executed:** charge path absent.                                                                                                                                                                           |
| T8 Reserve/finalize success              | Test processor can succeed; controlled advertiser balance                                    | Trigger activation; inspect ledger, balance, line item, and delivery                                   | Pending row reserved first; success finalizes exactly once and remaining budget equals total                                                                 | **Not executed:** processor integration absent.                                                                                                                                                                 |
| T9 Decline/explicit retry                | Processor declines; then retry action/new validated card; test flight-ended case             | Trigger decline; inspect restoration/state/email; retry; end flight before success                     | Restore balance, keep uncharged, Pending + exact tooltip/email; no automatic decline retry; retry only eligible failed items; ended item completes uncharged | **Not executed:** decline/retry/notification flow absent.                                                                                                                                                       |
| T10 Transient retry/idempotency/recovery | Processor simulator supports timeout and lookup                                              | Timeout up to retry limit; simulate unresolved pending result; replay same request                     | At most three automatic retries with same attempt key; recovery resolves without duplicate or lost charge                                                    | **Not executed:** worker/integration absent.                                                                                                                                                                    |
| T11 Concurrent advertiser charges        | Two eligible items for same advertiser and sufficient/limited balance                        | Start both simultaneously                                                                              | Serialized balance reservation; funds cannot be applied twice; each item charged at most once                                                                | **Not executed:** locking absent.                                                                                                                                                                               |
| T12 DSP spend arithmetic                 | Known supply cost and fractional platform fee                                                | Record a win at representative values                                                                  | Deduct `supply_cost / (1-platform_fee)` from remaining budget                                                                                                | **Not executed:** billing spend path not verified here.                                                                                                                                                         |
| T13 Completion/archive timestamps        | Charged item in each Active/Paused/Pending state; campaign timezone; early and later archive | Advance past flight end; archive before/after completion                                               | Complete at next-day boundary; set `ended_at` once; early archive uses archive time; later archive preserves earlier end                                     | **Not executed:** completion/rollover scheduler absent.                                                                                                                                                         |
| T14 Final spend source/window            | Display billing report; Text Admedia report; spend both within and after 24h                 | Record spend before and after the window; compare bidder pacing counter                                | Include billing-path reports within 24h; use Admedia for Text; exclude bidder counter and post-rollover spend                                                | **Not executed:** sources absent; 24h Text window is approved.                                                                                                                                                  |
| T15 Rollover eligibility and timing      | Completed/archived items, charged/un-charged and rolled/unrolled; 24h boundary               | Run hourly job before/at/after window; activate another item for same advertiser                       | Only eligible items credit; hourly lag ≤1h; pre-charge job applies only mature rollovers                                                                     | **Not executed:** jobs absent.                                                                                                                                                                                  |
| T16 Rollover amount/overspend/rounding   | Spend below/equal/above total; fractional-cent values                                        | Process rollover; inspect balance, remaining budget, ledger and overspend                              | `MAX(0,total-spend)`; half-up whole cents; never negative; overspend absorbed/recorded; zero credit ledger row present                                       | **Not executed:** rollover service absent.                                                                                                                                                                      |
| T17 Ledger integrity/reconciliation      | Successful, failed, applied-balance, and rollover movements                                  | Inspect history, edit/delete attempts, reconcile available balance                                     | Every movement represented; immutable amounts/entries; only card status mutable; balance equals balance ledger sum                                           | **Not executed:** ledger service/invariants/history absent.                                                                                                                                                     |
| T18 Text activation/archive integration  | Admedia test environment and confirmed reporting/start/pause contracts                       | Charge Text item; archive Text item; collect Admedia reports                                           | Start only after card charge success; archive sync pauses campaign; reporting supplies final spend                                                           | **Not executed:** integration absent.                                                                                                                                                                           |
| T19 Regression                           | Existing API/UI behavior; all affected line-item paths                                       | Run API line-item E2E, API/UI typecheck, targeted lint/format                                          | Existing flows preserved outside required end-date and edit-lock changes                                                                                     | API line-item E2E **Executed: 24/24 passed**; both typechecks **passed**; UI targeted ESLint **passed**. Whole-repository format checks fail on unrelated files; API ESLint unavailable (`@eslint/js` missing). |

### Executed validation record

- Following the PM/TL clarification: `npm test -- tests/payments.e2e.test.ts
tests/cors.e2e.test.ts tests/line-items.e2e.test.ts` — **36/36 passed**.
  Payment tests verify unverified creation is denied before a provider call or
  payment record, verified creation still works, and verification is re-read
  before accepting an idempotent replay. Existing decline, unknown-outcome,
  history and billing-address behavior remain covered by the same suite.
- Latest API typecheck passed; diagnostics for the modified payment service
  and test reported no errors. No real Clover pre-auth, void, charge, or AVS/CVV
  validation was performed.
- API: `npm test -- tests/line-items.e2e.test.ts` — **24/24 passed** after
  correcting the edit-lock check to ignore own properties whose value is
  `undefined`.
- API and UI: `npm run typecheck` — **passed**.
- UI: ESLint run on the five modified line-item files — **passed**.
- API ESLint cannot load the repository config because installed dependencies
  lack `@eslint/js`.
- `npm run format:check` in both repositories reports pre-existing formatting
  warnings in many untouched files; targeted Prettier checks for changed files
  passed.
- The E2E setup applied migrations to local `admedia_dsp_test`; no deployment
  database was accessed. No payment processor, scheduler, Admedia, or browser
  end-to-end behavior was exercised.

## Open questions

- Signup/TL: where is the saved reusable payment-method reference and which
  process writes `DspAdvertiser.verified`? What is the card replacement signal?
- Payment/TL: what lookup contract resolves a processor timeout using the
  idempotency key when the charge ID was not returned? ADCM-170 R7 specifies
  that no processor record is treated as a decline.
- Which Admedia endpoints/events provide campaign start, pause, and billing
  reporting spend? The 24-hour Text finalization window is already approved;
  this question is about integration contracts, not changing that decision.
- Signup/TL: provide implementation evidence for AVS/CVV dashboard rules,
  auth-only validation, immediate void and verification-state writes. These
  are upstream, not payment-time checks.
- Which deployment environment and rollout process should be used to apply the
  payment schema migration?

## Open blockers and recommended follow-up

1. Obtain signup's verified-state and reusable-card handoff contract. The
   validation method and ownership are clarified; automatic saved-card payment
   still requires that reference and supported charge contract.
2. Confirm the billing-path spend source and Admedia reporting, campaign-start,
   and pause contracts. The approved 24-hour Text finalization window is used
   here; a longer attribution window would require an explicit product change.
3. Confirm upstream verified-state writer and rollout for existing advertisers.
   Payment creation now denies unverified advertisers; it does not implement
   verification administration or auto-mark anyone verified.
4. Review and deploy the migration only through the approved database process;
   local test-database migration status does not establish deployment status.
5. Authenticate Jira access to verify current issue status and add/update
   implementation/testing subtasks only if existing tickets do not already
   cover the approved work.

These are blockers/recommendations, not implemented business rules. No optional
behavior has been added.
