# 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; 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.