# Metered Billing

## Objective

Charge for measured usage without surprising anyone at invoice time.

Idempotent usage recording, defined aggregation into billable quantities, correction handling, and a running estimate the customer can see.

## Before You Begin

This feature is being added to an application that already exists and already
works. Do not scaffold a new project, and do not assume a blank slate.

Inspect the codebase first and establish:

- The existing application structure and where code of this kind already lives.
- The framework and version in use.
- The existing design system — colours, spacing, typography, and component conventions.
- Existing UI components you can reuse instead of writing new ones.
- The existing database structure, if this feature needs to persist anything.
- The existing authentication and authorization system, if this feature is user-scoped.
- Dependencies already installed, so you don't add a library that duplicates one.
- The existing test setup and conventions.

Only start writing code once you understand the above. If the application
already implements part of this feature, extend it rather than replacing it.

## Implementation Instructions

1. Record each usage event with a caller-supplied immutable ID and reject repeats. Retried requests and re-delivered queue messages will otherwise be billed twice.
2. Define the aggregation window, the unit, the rounding direction and the included allowance in one place, and apply them identically to the estimate and the invoice.
3. Show a running cost estimate in the app, labelled as an estimate, with the period it covers and the time it was last updated.
4. Handle usage that arrives after its window closed and usage that is later reversed. Decide whether it lands in the closed period or the current one, and be consistent.
5. Plan-cap enforcement, race-safe counting against a limit, and the blocked-at-limit upgrade prompt are owned by Usage Limits. Metering measures; it does not gate. Extend Usage Limits rather than adding a second enforcement path.

## UI and UX Requirements

Match the application's existing design system exactly. Reuse its components,
spacing, and typography. This feature should look like it was always there.

## Responsive Requirements

Works on mobile, tablet, and desktop. Touch targets are large enough to hit on a
phone, and nothing overflows horizontally at 320px.

## Accessibility Requirements

- Fully keyboard navigable.
- Correct semantic elements and ARIA roles.
- Visible focus states.
- Meets WCAG AA contrast.
- Dynamic changes are announced to screen readers.
- Respects prefers-reduced-motion.

## Edge Cases

- Clock skew between reporting services will place events in the wrong window. Bill by the event's own timestamp, not arrival time, and define how late an event may be.
- A reversed or refunded unit of usage needs a negative entry, not the deletion of the original event.
- Rounding per event and rounding per period give different totals. Pick one, state it, and never apply both.
- The estimate will not exactly match the final invoice once tax, discounts and provider rounding are applied. Say so next to the number rather than being caught out by it.
- Usage recorded against a subscription that changed plan mid-period must be priced against the plan in force when it occurred.
- A burst of events must not be dropped silently under load. Queue them durably; unbilled usage is lost revenue and over-billed usage is a refund.

## Testing

Exercise the feature end to end in the running application. Cover every edge case
above, then run the existing test suite and confirm nothing regressed.

## Acceptance Criteria

- [ ] Replaying the same usage event ID does not increase the billed quantity.
- [ ] Window, unit, rounding and allowance definitions are shared by the estimate and the invoice calculation.
- [ ] The customer can see current-period usage and an estimated cost, explicitly labelled as an estimate.
- [ ] Late and reversed usage are represented as entries, and the rule for which period they affect is documented.
- [ ] Usage is priced against the plan in force at the moment it occurred.
- [ ] Event ingestion is durable under bursts, with no silent drops.
- [ ] The feature matches the existing design system.
- [ ] No existing functionality is broken.

## Adaptation Rules

- Match the existing design system. Do not introduce a new colour palette,
  spacing scale, or component library.
- Reuse existing components and utilities wherever they fit.
- Follow the naming, file layout, and code style already present.
- Do not upgrade, replace, or remove existing dependencies to make this
  feature fit. Adapt the feature to the app, not the app to the feature.
- Do not break existing functionality. If a change is genuinely required in
  existing code, make the smallest one that works and say so.
- If something in these instructions conflicts with how the application is
  built, follow the application and explain the deviation.

## Final Verification

Before you report the work as done:

1. Re-read the acceptance criteria above and check each one against what you
   actually built.
2. Run the application and exercise the feature end to end.
3. Run the existing test suite and confirm you have broken nothing.
4. Check the feature on mobile, tablet, and desktop widths.
5. Check keyboard navigation and focus handling.
6. Summarize what changed: files added, files modified, and anything you
   deliberately did differently because of how this application is built.

If any acceptance criterion is unmet, fix it before reporting completion.
