Add goals repository and configurable rules engine

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 08:44:52 -08:00
1 parent 939193f258
commit 7155396312
19 files changed
+882

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
use StreamGoals\Rules\Donation;
/** $wpdb-backed access to sg_donations. Requires live WordPress. */
final class DonationRepository {
private const STATUSES = array( 'pending', 'completed', 'refunded', 'reversed' );
private \wpdb $db;
public function __construct( ?\wpdb $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
private function table(): string {
return $this->db->prefix . 'sg_donations';
}
/** @return int|null new id, or null on failure (e.g. duplicate capture id). */
public function insert( array $d ): ?int {
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation' );
$row = array_intersect_key( $d, array_flip( $allowed ) );
$row += array( 'status' => 'pending', 'moderation' => 'approved', 'fee_minor' => 0 );
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
$ok = $this->db->insert( $this->table(), $row );
return $ok ? (int) $this->db->insert_id : null;
}
public function find( int $id ): ?array {
return $this->one( $this->db->prepare( "SELECT * FROM {$this->table()} WHERE id = %d", $id ) );
}
public function findByCaptureId( string $captureId ): ?array {
return $this->one( $this->db->prepare( "SELECT * FROM {$this->table()} WHERE paypal_capture_id = %s", $captureId ) );
}
public function findByOrderId( string $orderId ): ?array {
return $this->one( $this->db->prepare( "SELECT * FROM {$this->table()} WHERE paypal_order_id = %s ORDER BY id DESC LIMIT 1", $orderId ) );
}
public function updateStatus( int $id, string $status, ?string $captureId = null ): bool {
if ( ! in_array( $status, self::STATUSES, true ) ) {
return false;
}
$data = array( 'status' => $status );
if ( null !== $captureId ) {
$data['paypal_capture_id'] = $captureId;
}
return false !== $this->db->update( $this->table(), $data, array( 'id' => $id ) );
}
/**
* Public-safe feed of completed + approved donations. Real name is never returned for
* anonymous donors.
*
* @return array<int,array{id:int,name:string,amount_minor:int,currency:string,message:string,created_at:string}>
*/
public function recentApproved( ?int $goalId = null, int $limit = 10 ): array {
$limit = max( 1, min( 100, $limit ) );
$where = "status = 'completed' AND moderation = 'approved'";
$args = array();
if ( null !== $goalId ) {
$where .= ' AND goal_id = %d';
$args[] = $goalId;
}
$args[] = $limit;
$rows = $this->db->get_results(
$this->db->prepare( "SELECT id, base_minor, currency, donor_name, is_anonymous, message, created_at FROM {$this->table()} WHERE {$where} ORDER BY id DESC LIMIT %d", ...$args ),
ARRAY_A
);
$out = array();
foreach ( (array) $rows as $r ) {
$anon = ! empty( $r['is_anonymous'] ) || '' === trim( (string) $r['donor_name'] );
$out[] = array(
'id' => (int) $r['id'],
'name' => $anon ? 'Anonymous' : (string) $r['donor_name'],
'amount_minor' => (int) $r['base_minor'],
'currency' => (string) $r['currency'],
'message' => (string) $r['message'],
'created_at' => (string) $r['created_at'],
);
}
return $out;
}
/** Convert a DB row to the rules engine value object. */
public static function toDonation( array $r ): Donation {
return new Donation( (int) $r['id'], (int) $r['goal_id'], (int) $r['base_minor'], (int) $r['fee_minor'], (int) $r['total_minor'], (string) $r['currency'], (string) $r['status'] );
}
private function one( string $sql ): ?array {
$row = $this->db->get_row( $sql, ARRAY_A );
return $row ?: null;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */
final class GoalRepository {
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' );
private \wpdb $db;
public function __construct( ?\wpdb $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
private function table(): string {
return $this->db->prefix . 'sg_goals';
}
/** @return int new goal id */
public function create( array $data ): int {
$row = array_intersect_key( $data, self::FIELDS );
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 );
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
$this->db->insert( $this->table(), $row );
return (int) $this->db->insert_id;
}
public function find( int $id ): ?array {
$row = $this->db->get_row( $this->db->prepare( "SELECT * FROM {$this->table()} WHERE id = %d", $id ), ARRAY_A );
return $row ?: null;
}
/** @return array[] */
public function all( ?string $status = null ): array {
$t = $this->table();
$sql = null === $status
? "SELECT * FROM {$t} ORDER BY id DESC"
: $this->db->prepare( "SELECT * FROM {$t} WHERE status = %s ORDER BY id DESC", $status );
return (array) $this->db->get_results( $sql, ARRAY_A );
}
public function update( int $id, array $data ): bool {
$row = array_intersect_key( $data, self::FIELDS );
if ( ! $row ) {
return false;
}
return false !== $this->db->update( $this->table(), $row, array( 'id' => $id ) );
}
public function delete( int $id ): bool {
return false !== $this->db->delete( $this->table(), array( 'id' => $id ), array( '%d' ) );
}
/**
* Sum of completed donations (refunded/reversed/pending excluded), using total_minor when the
* goal counts fees, else base_minor.
*/
public function raised_minor( int $goalId ): int {
$goal = $this->find( $goalId );
if ( ! $goal ) {
return 0;
}
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input
$d = $this->db->prefix . 'sg_donations';
$sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) );
return (int) $sum;
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
use StreamGoals\Rules\StateRepository;
/** $wpdb-backed sg_state access (goal_id, skey, svalue). Requires live WordPress. */
final class StateStore implements StateRepository {
private \wpdb $db;
public function __construct( ?\wpdb $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
public function getInt( int $goalId, string $key, int $default = 0 ): int {
$t = $this->db->prefix . 'sg_state';
$v = $this->db->get_var( $this->db->prepare( "SELECT svalue FROM {$t} WHERE goal_id = %d AND skey = %s", $goalId, $key ) );
return null === $v ? $default : (int) $v;
}
public function setInt( int $goalId, string $key, int $value ): void {
$t = $this->db->prefix . 'sg_state';
$this->db->query(
$this->db->prepare(
"INSERT INTO {$t} (goal_id, skey, svalue, updated_at) VALUES (%d, %s, %s, %s)
ON DUPLICATE KEY UPDATE svalue = VALUES(svalue), updated_at = VALUES(updated_at)",
$goalId,
$key,
(string) $value,
gmdate( 'Y-m-d H:i:s' )
)
);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/**
* Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor).
* cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds
* this rule may ever add (net of reversals). The timer is an absolute ends_at timestamp.
*/
final class AddTimeRule {
public function __construct(
public readonly int $secondsPerUnit,
public readonly int $unitMinor,
public readonly ?int $capPerDonation = null,
public readonly ?int $maxTotal = null,
public readonly string $basis = 'base'
) {
if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) {
throw new \InvalidArgumentException( 'Invalid add_time config.' );
}
}
public static function fromConfig( array $c ): self {
return new self(
(int) ( $c['seconds_per_unit'] ?? 0 ),
(int) ( $c['unit_minor'] ?? 0 ),
isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null,
isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null,
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
);
}
/** @return array{delta:int, ends_at:int, added_total:int} */
public function apply( Donation $d, int $endsAt, int $addedTotal, int $now ): array {
$delta = intdiv( $d->amountFor( $this->basis ) * $this->secondsPerUnit, $this->unitMinor );
if ( null !== $this->capPerDonation ) {
$delta = min( $delta, max( 0, $this->capPerDonation ) );
}
if ( null !== $this->maxTotal ) {
$delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) );
}
$delta = max( 0, $delta );
if ( 0 === $delta ) {
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
}
// Expired (or never started) timers restart from now.
return array(
'delta' => $delta,
'ends_at' => max( $endsAt, $now ) + $delta,
'added_total' => $addedTotal + $delta,
);
}
/** @return array{ends_at:int, added_total:int} Never reduces below now; expired timers are untouched. */
public function reverse( int $delta, int $endsAt, int $addedTotal, int $now ): array {
if ( $endsAt > $now ) {
$endsAt = max( $now, $endsAt - $delta );
}
return array( 'ends_at' => $endsAt, 'added_total' => max( 0, $addedTotal - $delta ) );
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** Emits a named event when a single donation meets min_minor. */
final class BonusRule {
public function __construct(
public readonly int $minMinor,
public readonly string $event,
public readonly string $basis = 'base'
) {
if ( $minMinor <= 0 || '' === $event ) {
throw new \InvalidArgumentException( 'Invalid bonus config.' );
}
}
public static function fromConfig( array $c ): self {
return new self(
(int) ( $c['min_minor'] ?? 0 ),
(string) ( $c['event'] ?? 'bonus' ),
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
);
}
/** @return int 1 if the bonus triggers, else 0. */
public function apply( Donation $d ): int {
return $d->amountFor( $this->basis ) >= $this->minMinor ? 1 : 0;
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** Counts `step` per `per_minor`, optionally carrying the remainder to the next donation. */
final class CounterRule {
public function __construct(
public readonly int $step,
public readonly int $perMinor,
public readonly bool $carryOver = true,
public readonly string $basis = 'base'
) {
if ( $perMinor <= 0 || $step < 0 ) {
throw new \InvalidArgumentException( 'Invalid counter config.' );
}
}
public static function fromConfig( array $c ): self {
return new self(
(int) ( $c['step'] ?? 1 ),
(int) ( $c['per_minor'] ?? 0 ),
(bool) ( $c['carry_over'] ?? true ),
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
);
}
/** @return array{delta:int, counter:int, carry:int} */
public function apply( Donation $d, int $counter, int $carry ): array {
$pool = ( $this->carryOver ? $carry : 0 ) + $d->amountFor( $this->basis );
$delta = intdiv( $pool, $this->perMinor ) * $this->step;
return array(
'delta' => $delta,
'counter' => $counter + $delta,
'carry' => $this->carryOver ? $pool % $this->perMinor : 0,
);
}
/** @return array{counter:int, carry:int} Counter floors at 0; carry is rolled back by the donation amount. */
public function reverse( Donation $d, int $delta, int $counter, int $carry ): array {
$carry = $this->carryOver
? ( ( $carry - $d->amountFor( $this->basis ) ) % $this->perMinor + $this->perMinor ) % $this->perMinor
: 0;
return array( 'counter' => max( 0, $counter - $delta ), 'carry' => $carry );
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** Immutable donation value object consumed by the rules engine (no WordPress dependency). */
final class Donation {
public function __construct(
public readonly int $id,
public readonly int $goalId,
public readonly int $baseMinor,
public readonly int $feeMinor,
public readonly int $totalMinor,
public readonly string $currency,
public readonly string $status = 'completed'
) {}
/** Amount a rule should measure: 'base' (default) or 'total' (base + fee cover). */
public function amountFor( string $basis ): int {
return 'total' === $basis ? $this->totalMinor : $this->baseMinor;
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/**
* Applies/reverses donations against a goal's enabled rules. Idempotent per (rule_id, donation_id):
* the event row is recorded first, and state is only touched if that insert was new.
*
* Known limitation: state updates are read-modify-write without a lock; concurrent captures for
* the same goal could race. Wrap calls in a goal-level lock if that matters.
*/
final class Engine {
/** @var callable(string,RuleDef,Donation,bool):void|null ($event, $rule, $donation, $reversed) */
private $onBonus;
/** @var callable():int */
private $clock;
public function __construct(
private readonly RuleStore $rules,
private readonly EventStore $events,
private readonly StateRepository $state,
?callable $clock = null,
?callable $onBonus = null
) {
$this->clock = $clock ?? static fn(): int => time();
$this->onBonus = $onBonus;
}
public function applyDonation( Donation $d ): void {
foreach ( $this->rules->enabledForGoal( $d->goalId ) as $def ) {
try {
$this->applyRule( $def, $d );
} catch ( \InvalidArgumentException ) {
continue; // Misconfigured rule must not block the others.
}
}
}
public function reverseDonation( Donation $d ): void {
foreach ( $this->rules->enabledForGoal( $d->goalId ) as $def ) {
if ( ! $def->reverseOnRefund() ) {
continue;
}
try {
$this->reverseRule( $def, $d );
} catch ( \InvalidArgumentException ) {
continue;
}
}
}
private function applyRule( RuleDef $def, Donation $d ): void {
$g = $d->goalId;
switch ( $def->type ) {
case 'add_time':
$rule = AddTimeRule::fromConfig( $def->config );
$k = "timer_added:{$def->id}";
$r = $rule->apply( $d, $this->state->getInt( $g, 'timer_ends_at' ), $this->state->getInt( $g, $k ), ( $this->clock )() );
if ( ! $this->events->record( $def->id, $d->id, $r['delta'] ) ) {
return;
}
if ( $r['delta'] > 0 ) {
$this->state->setInt( $g, 'timer_ends_at', $r['ends_at'] );
$this->state->setInt( $g, $k, $r['added_total'] );
}
return;
case 'counter':
$rule = CounterRule::fromConfig( $def->config );
$r = $rule->apply( $d, $this->state->getInt( $g, "counter:{$def->id}" ), $this->state->getInt( $g, "carry:{$def->id}" ) );
if ( ! $this->events->record( $def->id, $d->id, $r['delta'] ) ) {
return;
}
$this->state->setInt( $g, "counter:{$def->id}", $r['counter'] );
$this->state->setInt( $g, "carry:{$def->id}", $r['carry'] );
return;
case 'bonus':
$rule = BonusRule::fromConfig( $def->config );
$fired = $rule->apply( $d );
if ( ! $this->events->record( $def->id, $d->id, $fired ) ) {
return;
}
if ( $fired && $this->onBonus ) {
( $this->onBonus )( $rule->event, $def, $d, false );
}
return;
}
}
private function reverseRule( RuleDef $def, Donation $d ): void {
$g = $d->goalId;
$delta = $this->events->markReversed( $def->id, $d->id );
if ( null === $delta ) {
return; // Never applied, or already reversed.
}
switch ( $def->type ) {
case 'add_time':
$k = "timer_added:{$def->id}";
$r = AddTimeRule::fromConfig( $def->config )->reverse( $delta, $this->state->getInt( $g, 'timer_ends_at' ), $this->state->getInt( $g, $k ), ( $this->clock )() );
if ( $delta > 0 ) {
$this->state->setInt( $g, 'timer_ends_at', $r['ends_at'] );
$this->state->setInt( $g, $k, $r['added_total'] );
}
return;
case 'counter':
$r = CounterRule::fromConfig( $def->config )->reverse( $d, $delta, $this->state->getInt( $g, "counter:{$def->id}" ), $this->state->getInt( $g, "carry:{$def->id}" ) );
$this->state->setInt( $g, "counter:{$def->id}", $r['counter'] );
$this->state->setInt( $g, "carry:{$def->id}", $r['carry'] );
return;
case 'bonus':
if ( $delta > 0 && $this->onBonus ) {
( $this->onBonus )( BonusRule::fromConfig( $def->config )->event, $def, $d, true );
}
return;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** Persistence for sg_rule_events; UNIQUE(rule_id, donation_id) provides idempotency. */
interface EventStore {
/** Insert the event. Returns false if (rule, donation) already exists (replay). */
public function record( int $ruleId, int $donationId, int $delta ): bool;
/** Atomically flag as reversed. Returns the original delta, or null if absent/already reversed. */
public function markReversed( int $ruleId, int $donationId ): ?int;
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** A stored rule row: id, goal, type (add_time|counter|bonus) and decoded config. */
final class RuleDef {
public function __construct(
public readonly int $id,
public readonly int $goalId,
public readonly string $type,
public readonly array $config
) {}
/** Per-rule "reverse on refund" flag; defaults to true. */
public function reverseOnRefund(): bool {
return (bool) ( $this->config['reverse_on_refund'] ?? true );
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
interface RuleStore {
/** @return RuleDef[] enabled rules for the goal, ordered by sort. */
public function enabledForGoal( int $goalId ): array;
}
+11
View File
@@ -0,0 +1,11 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** Integer key/value state per goal (sg_state). */
interface StateRepository {
public function getInt( int $goalId, string $key, int $default = 0 ): int;
public function setInt( int $goalId, string $key, int $value ): void;
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** $wpdb-backed EventStore over sg_rule_events. Requires live WordPress. */
final class WpEventStore implements EventStore {
private \wpdb $db;
public function __construct( ?\wpdb $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
public function record( int $ruleId, int $donationId, int $delta ): bool {
$t = $this->db->prefix . 'sg_rule_events';
$n = $this->db->query(
$this->db->prepare(
"INSERT IGNORE INTO {$t} (rule_id, donation_id, delta, reversed, created_at) VALUES (%d, %d, %d, 0, %s)",
$ruleId,
$donationId,
$delta,
gmdate( 'Y-m-d H:i:s' )
)
);
return 1 === $n;
}
public function markReversed( int $ruleId, int $donationId ): ?int {
$t = $this->db->prefix . 'sg_rule_events';
$n = $this->db->query(
$this->db->prepare( "UPDATE {$t} SET reversed = 1 WHERE rule_id = %d AND donation_id = %d AND reversed = 0", $ruleId, $donationId )
);
if ( 1 !== $n ) {
return null;
}
$delta = $this->db->get_var( $this->db->prepare( "SELECT delta FROM {$t} WHERE rule_id = %d AND donation_id = %d", $ruleId, $donationId ) );
return null === $delta ? null : (int) $delta;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rules;
/** $wpdb-backed RuleStore over sg_rules. Requires live WordPress. */
final class WpRuleStore implements RuleStore {
private \wpdb $db;
public function __construct( ?\wpdb $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
public function enabledForGoal( int $goalId ): array {
$t = $this->db->prefix . 'sg_rules';
$rows = $this->db->get_results(
$this->db->prepare( "SELECT id, goal_id, type, config FROM {$t} WHERE goal_id = %d AND enabled = 1 ORDER BY sort ASC, id ASC", $goalId ),
ARRAY_A
);
$out = array();
foreach ( (array) $rows as $r ) {
$cfg = json_decode( (string) $r['config'], true );
$out[] = new RuleDef( (int) $r['id'], (int) $r['goal_id'], (string) $r['type'], is_array( $cfg ) ? $cfg : array() );
}
return $out;
}
}