Files
wp-donations/docs/ARCHITECTURE.md
T
shadowdaoandClaude Sonnet 5.5 353f7ca5be
Test and Release / test (push) Successful in 1m28s
Test and Release / release (push) Successful in 7s
Hold donations with flagged donor names for moderation; reconcile lost side effects (schema v6)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 17:07:32 -08:00

109 lines
12 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), moderation_flags, effects_applied_at NULL (v6), 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; refunds/chargebacks are NOT tracked - nothing calls reverseDonation, and refunds done in PayPal are not reflected in goal totals, timers, counters or tiers):
```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().
## Schema v3 (Installer, DB_VERSION 3)
- `sg_goals.close_at_target` TINYINT: when 1, the goal is closed to donors as soon as its raised total reaches or exceeds the target (status becomes `complete`, same as the manual "Complete" action).
- `sg_alert_defs` — owner-defined alert presentations (media from the WordPress Media Library; attachment ids, never raw URLs):
id, goal_id (0 = all goals), trigger_type `amount` | `reward`, min_minor (for `amount`: applies when the donation BASE amount >= min_minor; the highest matching min_minor wins),
action_id (for `reward`: applies when that reward triggered; a reward definition wins over an amount definition), title (admin label),
visual_id + visual_type (`image` | `video` | '' none), sound_id (audio attachment, 0 none), volume 0-100, duration_ms (how long an image/GIF stays; videos play to the end, capped),
message (template with {name} {amount} {reward}; '' = default text), enabled, sort, created_at.
## Goal tiers (milestones) — contract (Installer DB_VERSION 4)
A goal may have ordered TIERS; each is a cumulative target with an item/unlock (e.g. $100 "Giveaway", $250 "New microphone", $500 "24-hour stream").
- `sg_goal_tiers`: id, goal_id, target_minor (cumulative raised total needed), title VARCHAR(120) (the item/unlock), description VARCHAR(255), reached_at DATETIME NULL,
reached_donation_id BIGINT UNSIGNED NULL, created_at; UNIQUE(goal_id, target_minor). Tier order = target_minor ascending.
- A goal WITH tiers keeps `sg_goals.target_minor` equal to its HIGHEST tier target (maintained automatically when tiers change; the goal form shows the target as derived/read-only). So "end at target" closes the goal when the FINAL tier is reached, and everything that reads goal target keeps working.
- Raised total for tiers uses the same basis as the goal (`GoalRepository::raised_minor`, base vs total per counts_fees).
- Reaching a tier: after a donation is completed (same finalize path as rules/actions, BEFORE the close-at-target check, never throwing, idempotent): for every tier of the goal with reached_at IS NULL and target_minor <= raised, set reached_at=NOW and reached_donation_id=that donation with `UPDATE ... WHERE id=? AND reached_at IS NULL` (a big donation can unlock several tiers at once; all get its id).
- "Current tier" = the first tier (by target) with reached_at IS NULL. Goal bar progress for a tiered goal = (raised - floor) / (target - floor) clamped 0..1, where floor = previous tier's target (0 for the first); the cumulative raised and the current tier target are still displayed.
- Reached tiers: title/description editable, target locked; a new tier's target must be above the goal's current raised total and unique.
- Overlay `goal` payload for a tiered goal adds `tiers: {count, index (1-based current), current:{title,description,target_minor,target_display,floor_minor}|null, all_reached}`; untiered goals are unchanged. Alert payloads gain `tiers: [{title}]` = tiers whose reached_donation_id is that donation, shown as a "TIER UNLOCKED: title" pill.
## Schema v6 (Installer, DB_VERSION 6): donor-name flagging + effects reconciliation
Only our own `sg_donations` table changes (two columns, added by dbDelta):
- `moderation_flags VARCHAR(16) NOT NULL DEFAULT ''`: why a row is held. `''` (legacy/approved), `message`, `name` or `name,message`. Display only (`Admin\Format::flaggedLabel`); `moderation` stays the single source of truth for visibility. A held row with `''` flags is shown as "Message" (before v6 only messages were held).
- `effects_applied_at DATETIME NULL`: set (UTC) once ALL side effects of a completed donation finished without error.
### Donor-name flagging
`OrderValidator::validate` runs the streamer's `ProfanityFilter` over `donor_name` (non-anonymous only; anonymous names are blanked first and never stored). `ProfanityFilter::matches()` shares the scan with `filter()`. The filter has a single mode, MASK: the stored name is already masked (`f***`), exactly like messages. A tripped name sets `moderation='pending'` and `moderation_flags` includes `name`, independent of the `moderate_messages` setting; a non-empty message with `moderate_messages` on adds `message`. The donation completes and counts for goal/timer/counter/rewards/tiers as usual (moderation never gates those).
Alerts: `Overlay\Payloads::alerts` (and `WpdbDataSource`, `DonationRepository::recentApproved`) only emit `completed` + `approved` rows, so a held donation emits NO alert at all (the whole alert is held, same as a held message). It is never shown as "Anonymous". After Approve the alert shows the masked name; Reject = never shown.
### Reconciliation of "completed but side effects lost"
`DonationStore::notify_applied($id): bool` runs engine (rules/timer/counter), `Actions\Recorder`, `Tiers\Recorder` (before the close check), then end-at-target, and only if every step succeeded calls `mark_effects_applied` (`UPDATE ... WHERE effects_applied_at IS NULL`). `CaptureFinalizer` is unchanged: `mark_completed` stays the atomic single-winner pending->completed step and both the capture endpoint and the webhook call `notify_applied` only for the winner, so a replay never re-runs it inline.
`Maintenance::reconcile_effects` (cron `sg_reconcile_effects`, every 5 min, single-flight via `GET_LOCK`) selects up to 25 `status='completed' AND effects_applied_at IS NULL AND goal_id>0` rows created more than 2 minutes and less than 30 days ago and calls `notify_applied` again. Replay safety: rules via `sg_rule_events` UNIQUE(rule_id,donation_id) (event inserted first, state only touched if new, under the goal lock); rewards via `INSERT IGNORE` on UNIQUE(donation_id,action_id); tiers via `UPDATE ... WHERE reached_at IS NULL`; close-at-target via `UPDATE ... WHERE status='active'`.
Upgrade: `Installer::maybe_upgrade` passes the stored version to `install_schema`; when it is < 6 (or absent) it backfills `effects_applied_at` for every already-completed row BEFORE writing `sg_db_version`, so history is never replayed and a failed backfill is retried on the next load. Known gap (unchanged): in `Engine::applyRule` the event row is recorded before state is updated, so a death between those two statements loses that single rule's effect and a replay skips it.