Files
wp-donations/docs/ARCHITECTURE.md
T
2026-11-15 12:33:50 -08:00

76 lines
6.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# StreamGoals Donate — Architecture Contract
Target: WordPress 7.x, PHP 8.1+. Single streamer per install. Built/deployed from Gitea (zip artifact, no runtime Composer).
Namespace `StreamGoals\`, PSR-4 rooted at `includes/`. Text domain `streamgoals-donate`. Table prefix `{$wpdb->prefix}sg_`.
## Ground rules
- **Money is integer minor units** (cents) plus an ISO-4217 currency. Never floats. Zero-decimal currencies (JPY) handled via `Core\Money`.
- **Pure logic has no WordPress dependency** (`Core\Money`, `Core\FeeCalculator`, `Rules\*`) so it is unit-testable with plain PHPUnit.
- WordPress-touching code (DB, REST, admin) sits behind small classes; escape all output, check capabilities (`manage_options`), nonces on admin posts.
- Public endpoints are rate-limited and never expose the real name of an anonymous donor.
## Directory ownership (to avoid merge conflicts between agents)
| Path | Owner |
|---|---|
| `includes/Core/*`, `streamgoals-donate.php`, `docs/ARCHITECTURE.md` | Foundation (done first) |
| `includes/PayPal/*`, `includes/Rest/DonateController.php`, `includes/Rest/WebhookController.php`, `assets/donate/*` | Agent 1: PayPal + donate flow |
| `includes/Rules/*`, `includes/Core/GoalRepository.php` consumers, `tests/Unit/Rules*` | Agent 2: Goals + rules engine |
| `includes/Overlay/*`, `includes/Rest/OverlayController.php`, `assets/overlay/*` | Agent 3: Overlays |
| `includes/Admin/*`, `assets/admin/*` | Later phase (wizard/admin UI) |
## Database (created by `Core\Installer`, version in option `sg_db_version`)
- `sg_goals`: id, title, target_minor, currency, status(active|paused|complete), starts_at, ends_at NULL, counts_fees TINYINT(0 = base amount only), created_at
- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), created_at
- `sg_rules`: id, goal_id, type(add_time|counter|bonus), config JSON, enabled, sort
- `sg_rule_events`: id, rule_id, donation_id, delta (seconds or count), reversed TINYINT, created_at — UNIQUE(rule_id, donation_id) for idempotency
- `sg_state`: goal_id, key, value — timer `ends_at`, counter totals, carry-over remainders
- Options: `sg_settings` (paypal mode/client_id/secret, fee rates, moderation, anonymity policy, overlay token)
## Core interfaces (all in `includes/Core`)
```php
Money::fromDecimalString(string $amount, string $currency): Money; // "10.50" -> 1050
FeeCalculator::grossUp(int $baseMinor, FeeRates $rates): int; // total so recipient nets base
// total = ceil((base + fixed) / (1 - pct)) — rates configurable, default US 3.49% + 49c
```
Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is recorded and on refund):
```php
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
```
Rule `config` examples (`max_total_seconds` caps what one rule has added over time; `max_timer_seconds` caps how long the timer can ever get, null = uncapped):
```json
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"max_timer_seconds":null,"basis":"base"}
{"type":"counter","step":1,"per_minor":1000,"carry_over":true,"basis":"base","label":"Pies"}
{"type":"bonus","min_minor":5000,"event":"big_donation"}
```
## Public REST (namespace `streamgoals/v1`)
- `POST /orders` (create order; server computes total incl. optional fee cover), `POST /orders/{id}/capture`
- `POST /webhook` (PayPal signature verified; deduped by capture id)
- `GET /overlay/{token}/{widget}` — ETag'd JSON, polled every 2–3 s; widgets: `goal`, `timer`, `counter`, `alerts`
## Fee cover
A toggle on the donate form (default **off**). Form shows exact total before payment. Goal counts **base** amount by default (`counts_fees` per goal).
## Defaults
Currency USD (configurable per goal). Sandbox mode is the default until the owner switches to Live.
## Donation actions ("rewards") — contract
Streamers attach on-stream actions to dollar amounts (e.g. $5 = "Eat an every-flavor bean", $25 = "25 pushups").
Tables (Installer, DB_VERSION 2):
- `sg_actions`: id, goal_id (0 = applies to every goal), title VARCHAR(120), description VARCHAR(255), amount_minor BIGINT UNSIGNED,
mode VARCHAR(8) `exact` (donation base amount == amount) | `every` (each whole multiple of amount: times = floor(base/amount)),
enabled TINYINT, sort INT, created_at.
- `sg_action_events`: id, donation_id, action_id, times INT, title VARCHAR(120) (snapshot at trigger time), status `queued`|`done`,
created_at, done_at NULL. UNIQUE(donation_id, action_id) so a replayed capture/webhook never double-queues.
PHP (namespace `StreamGoals\Actions`):
- `Matcher::match(int $baseMinor, array $actions): array` — PURE. `$actions` = rows with keys id, title, amount_minor, mode.
Returns `[ ['action_id'=>int,'title'=>string,'times'=>int], ... ]`; a donation may trigger several actions (e.g. $25 matches "every $5" x5 and exact "$25"). amount_minor <= 0 never matches.
- `ActionRepository` ($wpdb): `enabledForGoal(int $goalId): array` (enabled rows where goal_id IN (0,$goalId), ORDER BY sort, amount_minor), CRUD for admin,
`recordEvents(int $donationId, array $matches): void` (INSERT IGNORE, idempotent), `queued(int $limit): array`, `markDone(int $eventId): bool`.
- `Recorder::forDonation(int $donationId): void` — called after a donation becomes `completed` (same place the rules engine is applied); matches on the donation's BASE amount (not fee cover) using the goal's enabled actions and records events. Never throws.
Public/overlay: the donate form shows each enabled action as a button (amount + title); the overlay has a new `actions` widget (the menu for the active goal) and alert payloads gain `actions`: `[ {title, times} ]` read from sg_action_events (anonymous donors' actions are still shown; names stay masked).
Amounts must be >= Settings::effectiveMin().