diff --git a/includes/Core/DonationRepository.php b/includes/Core/DonationRepository.php new file mode 100644 index 0000000..3d1a898 --- /dev/null +++ b/includes/Core/DonationRepository.php @@ -0,0 +1,99 @@ +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 + */ + 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; + } +} diff --git a/includes/Core/GoalRepository.php b/includes/Core/GoalRepository.php new file mode 100644 index 0000000..e93d036 --- /dev/null +++ b/includes/Core/GoalRepository.php @@ -0,0 +1,70 @@ + '%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; + } +} diff --git a/includes/Core/StateStore.php b/includes/Core/StateStore.php new file mode 100644 index 0000000..1b8b5b3 --- /dev/null +++ b/includes/Core/StateStore.php @@ -0,0 +1,36 @@ +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' ) + ) + ); + } +} diff --git a/includes/Rules/AddTimeRule.php b/includes/Rules/AddTimeRule.php new file mode 100644 index 0000000..9b37991 --- /dev/null +++ b/includes/Rules/AddTimeRule.php @@ -0,0 +1,63 @@ +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 ) ); + } +} diff --git a/includes/Rules/BonusRule.php b/includes/Rules/BonusRule.php new file mode 100644 index 0000000..993c47a --- /dev/null +++ b/includes/Rules/BonusRule.php @@ -0,0 +1,31 @@ +amountFor( $this->basis ) >= $this->minMinor ? 1 : 0; + } +} diff --git a/includes/Rules/CounterRule.php b/includes/Rules/CounterRule.php new file mode 100644 index 0000000..fadd719 --- /dev/null +++ b/includes/Rules/CounterRule.php @@ -0,0 +1,47 @@ +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 ); + } +} diff --git a/includes/Rules/Donation.php b/includes/Rules/Donation.php new file mode 100644 index 0000000..4bd47d6 --- /dev/null +++ b/includes/Rules/Donation.php @@ -0,0 +1,23 @@ +totalMinor : $this->baseMinor; + } +} diff --git a/includes/Rules/Engine.php b/includes/Rules/Engine.php new file mode 100644 index 0000000..bc1b378 --- /dev/null +++ b/includes/Rules/Engine.php @@ -0,0 +1,118 @@ +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; + } + } +} diff --git a/includes/Rules/EventStore.php b/includes/Rules/EventStore.php new file mode 100644 index 0000000..ba518c8 --- /dev/null +++ b/includes/Rules/EventStore.php @@ -0,0 +1,13 @@ +config['reverse_on_refund'] ?? true ); + } +} diff --git a/includes/Rules/RuleStore.php b/includes/Rules/RuleStore.php new file mode 100644 index 0000000..6933be4 --- /dev/null +++ b/includes/Rules/RuleStore.php @@ -0,0 +1,9 @@ +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; + } +} diff --git a/includes/Rules/WpRuleStore.php b/includes/Rules/WpRuleStore.php new file mode 100644 index 0000000..f62137d --- /dev/null +++ b/includes/Rules/WpRuleStore.php @@ -0,0 +1,28 @@ +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; + } +} diff --git a/tests/Unit/FakeEventStore.php b/tests/Unit/FakeEventStore.php new file mode 100644 index 0000000..a927d1a --- /dev/null +++ b/tests/Unit/FakeEventStore.php @@ -0,0 +1,26 @@ + [delta, reversed] + public function record( int $ruleId, int $donationId, int $delta ): bool { + $k = "$ruleId:$donationId"; + if ( isset( $this->events[ $k ] ) ) { + return false; + } + $this->events[ $k ] = array( $delta, false ); + return true; + } + public function markReversed( int $ruleId, int $donationId ): ?int { + $k = "$ruleId:$donationId"; + if ( ! isset( $this->events[ $k ] ) || $this->events[ $k ][1] ) { + return null; + } + $this->events[ $k ][1] = true; + return $this->events[ $k ][0]; + } +} diff --git a/tests/Unit/FakeRuleStore.php b/tests/Unit/FakeRuleStore.php new file mode 100644 index 0000000..60a98d1 --- /dev/null +++ b/tests/Unit/FakeRuleStore.php @@ -0,0 +1,13 @@ +rules, static fn( $r ) => $r->goalId === $goalId ) ); + } +} diff --git a/tests/Unit/FakeStateRepository.php b/tests/Unit/FakeStateRepository.php new file mode 100644 index 0000000..ff67ecc --- /dev/null +++ b/tests/Unit/FakeStateRepository.php @@ -0,0 +1,16 @@ +data[ "$goalId:$key" ] ?? $default; + } + public function setInt( int $goalId, string $key, int $value ): void { + $this->data[ "$goalId:$key" ] = $value; + } +} diff --git a/tests/Unit/RulesEngineTest.php b/tests/Unit/RulesEngineTest.php new file mode 100644 index 0000000..1c47641 --- /dev/null +++ b/tests/Unit/RulesEngineTest.php @@ -0,0 +1,137 @@ +state = new FakeStateRepository(); + $this->events = new FakeEventStore(); + return new Engine( + new FakeRuleStore( $rules ), + $this->events, + $this->state, + fn(): int => $this->now, + function ( string $e, RuleDef $r, Donation $d, bool $rev ): void { + $this->fired[] = array( $e, $d->id, $rev ); + } + ); + } + + private function d( int $id, int $base, string $cur = 'USD' ): Donation { + return new Donation( $id, 1, $base, 0, $base, $cur ); + } + + private function timer( array $extra = array() ): RuleDef { + return new RuleDef( 1, 1, 'add_time', $extra + array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ); + } + + private function counter( array $extra = array() ): RuleDef { + return new RuleDef( 2, 1, 'counter', $extra + array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true ) ); + } + + public function test_apply_persists_timer_counter_and_events(): void { + $e = $this->engine( array( $this->timer(), $this->counter() ) ); + $e->applyDonation( $this->d( 10, 2500 ) ); + $this->assertSame( 1000 + 1500, $this->state->getInt( 1, 'timer_ends_at' ) ); + $this->assertSame( 2, $this->state->getInt( 1, 'counter:2' ) ); + $this->assertSame( 500, $this->state->getInt( 1, 'carry:2' ) ); + $this->assertSame( 1500, $this->events->events['1:10'][0] ); + } + + public function test_replay_is_idempotent(): void { + $e = $this->engine( array( $this->timer(), $this->counter() ) ); + $d = $this->d( 10, 2500 ); + $e->applyDonation( $d ); + $snapshot = $this->state->data; + $e->applyDonation( $d ); + $e->applyDonation( $d ); + $this->assertSame( $snapshot, $this->state->data ); + } + + public function test_expired_timer_restarts_from_now(): void { + $e = $this->engine( array( $this->timer() ) ); + $this->state->setInt( 1, 'timer_ends_at', 10 ); + $e->applyDonation( $this->d( 10, 100 ) ); + $this->assertSame( 1060, $this->state->getInt( 1, 'timer_ends_at' ) ); + } + + public function test_running_timer_extends(): void { + $e = $this->engine( array( $this->timer() ) ); + $this->state->setInt( 1, 'timer_ends_at', 5000 ); + $e->applyDonation( $this->d( 10, 100 ) ); + $this->assertSame( 5060, $this->state->getInt( 1, 'timer_ends_at' ) ); + } + + public function test_max_total_across_donations(): void { + $e = $this->engine( array( $this->timer( array( 'max_total_seconds' => 100 ) ) ) ); + $e->applyDonation( $this->d( 1, 100 ) ); + $e->applyDonation( $this->d( 2, 100 ) ); + $this->assertSame( 1000 + 100, $this->state->getInt( 1, 'timer_ends_at' ) ); + } + + public function test_reversal_undoes_and_is_not_double_applied(): void { + $e = $this->engine( array( $this->timer(), $this->counter() ) ); + $d = $this->d( 10, 2500 ); + $e->applyDonation( $d ); + $e->reverseDonation( $d ); + $e->reverseDonation( $d ); + $this->assertSame( 1000, $this->state->getInt( 1, 'timer_ends_at' ) ); + $this->assertSame( 0, $this->state->getInt( 1, 'counter:2' ) ); + $this->assertSame( 0, $this->state->getInt( 1, 'carry:2' ) ); + } + + public function test_reversal_never_below_floor(): void { + $e = $this->engine( array( $this->timer(), $this->counter() ) ); + $d = $this->d( 10, 2500 ); + $e->applyDonation( $d ); + $this->state->setInt( 1, 'counter:2', 1 ); // already lower than the delta + $this->now = 5000; // timer long expired + $e->reverseDonation( $d ); + $this->assertSame( 0, $this->state->getInt( 1, 'counter:2' ) ); + $this->assertSame( 2500, $this->state->getInt( 1, 'timer_ends_at' ) ); // untouched, not pushed below + } + + public function test_reverse_on_refund_false_is_honored(): void { + $e = $this->engine( array( $this->counter( array( 'reverse_on_refund' => false ) ) ) ); + $d = $this->d( 10, 2000 ); + $e->applyDonation( $d ); + $e->reverseDonation( $d ); + $this->assertSame( 2, $this->state->getInt( 1, 'counter:2' ) ); + } + + public function test_reverse_unapplied_donation_is_noop(): void { + $e = $this->engine( array( $this->counter() ) ); + $this->state->setInt( 1, 'counter:2', 5 ); + $e->reverseDonation( $this->d( 99, 5000 ) ); + $this->assertSame( 5, $this->state->getInt( 1, 'counter:2' ) ); + } + + public function test_bonus_fires_once_and_zero_decimal_currency(): void { + $bonus = new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 5000, 'event' => 'big_donation' ) ); + $e = $this->engine( array( $bonus, $this->counter( array( 'per_minor' => 1000 ) ) ) ); + $d = $this->d( 7, 6000, 'JPY' ); + $e->applyDonation( $d ); + $e->applyDonation( $d ); + $this->assertSame( array( array( 'big_donation', 7, false ) ), $this->fired ); + $this->assertSame( 6, $this->state->getInt( 1, 'counter:2' ) ); + } + + public function test_bad_config_does_not_block_other_rules(): void { + $bad = new RuleDef( 9, 1, 'add_time', array( 'seconds_per_unit' => 1, 'unit_minor' => 0 ) ); + $e = $this->engine( array( $bad, $this->counter() ) ); + $e->applyDonation( $this->d( 1, 1000 ) ); + $this->assertSame( 1, $this->state->getInt( 1, 'counter:2' ) ); + } +} diff --git a/tests/Unit/RulesPureTest.php b/tests/Unit/RulesPureTest.php new file mode 100644 index 0000000..e466f0a --- /dev/null +++ b/tests/Unit/RulesPureTest.php @@ -0,0 +1,82 @@ +apply( $this->d( 2500 ), 0, 0 ); + $this->assertSame( array( 2, 2, 500 ), array( $a['delta'], $a['counter'], $a['carry'] ) ); + $b = $r->apply( $this->d( 500 ), $a['counter'], $a['carry'] ); + $this->assertSame( array( 1, 3, 0 ), array( $b['delta'], $b['counter'], $b['carry'] ) ); + } + + public function test_counter_without_carry_discards_remainder(): void { + $a = ( new CounterRule( 1, 1000, false ) )->apply( $this->d( 2500 ), 0, 700 ); + $this->assertSame( array( 2, 0 ), array( $a['delta'], $a['carry'] ) ); + } + + public function test_counter_reverse_floors_at_zero_and_rolls_carry(): void { + $r = new CounterRule( 1, 1000 ); + $x = $r->reverse( $this->d( 2500 ), 2, 1, 500 ); + $this->assertSame( array( 0, 0 ), array( $x['counter'], $x['carry'] ) ); + } + + public function test_add_time_proportional_and_caps(): void { + $r = new AddTimeRule( 60, 100, 300, 400 ); + $this->assertSame( 150, ( new AddTimeRule( 60, 100 ) )->apply( $this->d( 250 ), 0, 0, 1000 )['delta'] ); + $this->assertSame( 300, $r->apply( $this->d( 10000 ), 0, 0, 1000 )['delta'] ); // per-donation cap + $this->assertSame( 100, $r->apply( $this->d( 10000 ), 0, 300, 1000 )['delta'] ); // total cap + $this->assertSame( 0, $r->apply( $this->d( 10000 ), 0, 400, 1000 )['delta'] ); + } + + public function test_add_time_expired_starts_from_now_and_running_extends(): void { + $r = new AddTimeRule( 60, 100 ); + $this->assertSame( 1000 + 120, $r->apply( $this->d( 200 ), 500, 0, 1000 )['ends_at'] ); + $this->assertSame( 2000 + 120, $r->apply( $this->d( 200 ), 2000, 0, 1000 )['ends_at'] ); + } + + public function test_add_time_reverse_floors_at_now(): void { + $r = new AddTimeRule( 60, 100 ); + $this->assertSame( 1000, $r->reverse( 500, 1200, 500, 1000 )['ends_at'] ); + $this->assertSame( 500, $r->reverse( 100, 500, 100, 1000 )['ends_at'] ); // expired: untouched + } + + public function test_basis_base_vs_total(): void { + $d = $this->d( 1000, 100 ); + $this->assertSame( 600, ( new AddTimeRule( 60, 100, null, null, 'base' ) )->apply( $d, 0, 0, 0 )['delta'] ); + $this->assertSame( 660, ( new AddTimeRule( 60, 100, null, null, 'total' ) )->apply( $d, 0, 0, 0 )['delta'] ); + $this->assertSame( 1, ( new CounterRule( 1, 1100, true, 'total' ) )->apply( $d, 0, 0 )['delta'] ); + $this->assertSame( 0, ( new CounterRule( 1, 1100, true, 'base' ) )->apply( $d, 0, 0 )['delta'] ); + } + + public function test_zero_decimal_currency(): void { + // 500 JPY = 500 minor; 1 minute per 100 yen. + $d = $this->d( 500, 0, 'JPY' ); + $this->assertSame( 300, ( new AddTimeRule( 60, 100 ) )->apply( $d, 0, 0, 0 )['delta'] ); + $this->assertSame( 5, ( new CounterRule( 1, 100 ) )->apply( $d, 0, 0 )['delta'] ); + } + + public function test_bonus_threshold(): void { + $r = new BonusRule( 5000, 'big_donation' ); + $this->assertSame( 0, $r->apply( $this->d( 4999 ) ) ); + $this->assertSame( 1, $r->apply( $this->d( 5000 ) ) ); + } + + public function test_invalid_config_throws(): void { + $this->expectException( \InvalidArgumentException::class ); + AddTimeRule::fromConfig( array( 'seconds_per_unit' => 1, 'unit_minor' => 0 ) ); + } +}