Files
wp-donations/includes/PayPal/DonationStore.php
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

196 lines
8.2 KiB
PHP

<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/** $wpdb access for sg_donations / sg_goals used by the donate flow. WordPress-only. */
final class DonationStore {
private static function t( string $name ): string {
global $wpdb;
return $wpdb->prefix . 'sg_' . $name;
}
public static function goal( int $id ): ?array {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'goals' ) . ' WHERE id = %d', $id ), ARRAY_A );
return $row ?: null;
}
/** @return array[] */
public static function active_goals(): array {
global $wpdb;
$rows = $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'active' ORDER BY id ASC", ARRAY_A );
$now = time();
return array_values( array_filter( (array) $rows, static fn( array $g ): bool => OrderValidator::goalIsOpen( $g, $now ) ) );
}
public static function find( int $id ): ?object {
global $wpdb;
return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id = %d', $id ) ) ?: null;
}
public static function find_by_order( string $orderId ): ?object {
global $wpdb;
return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_order_id = %s ORDER BY id DESC LIMIT 1', $orderId ) ) ?: null;
}
public static function find_by_capture( string $captureId ): ?object {
global $wpdb;
if ( '' === $captureId ) {
return null;
}
return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE paypal_capture_id = %s', $captureId ) ) ?: null;
}
/** @param array $v Output of OrderValidator::validate(). @return int Donation id (0 on failure). */
public static function insert_pending( array $v ): int {
global $wpdb;
$ok = $wpdb->insert(
self::t( 'donations' ),
array(
'goal_id' => $v['goal_id'],
'paypal_order_id' => '',
'base_minor' => $v['base_minor'],
'fee_minor' => $v['fee_minor'],
'total_minor' => $v['total_minor'],
'currency' => $v['currency'],
'donor_name' => $v['donor_name'],
'is_anonymous' => $v['is_anonymous'] ? 1 : 0,
'message' => $v['message'],
'status' => 'pending',
'moderation' => $v['moderation'],
'moderation_flags' => (string) ( $v['moderation_flags'] ?? '' ),
'created_at' => gmdate( 'Y-m-d H:i:s' ),
),
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' )
);
return $ok ? (int) $wpdb->insert_id : 0;
}
public static function set_order_id( int $id, string $orderId ): void {
global $wpdb;
$wpdb->update( self::t( 'donations' ), array( 'paypal_order_id' => $orderId ), array( 'id' => $id ), array( '%s' ), array( '%d' ) );
}
public static function delete( int $id ): void {
global $wpdb;
$wpdb->delete( self::t( 'donations' ), array( 'id' => $id ), array( '%d' ) );
}
/** Atomic pending -> completed. True only for the single caller that wins the transition. */
public static function mark_completed( int $id, string $captureId ): bool {
global $wpdb;
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET status = 'completed', paypal_capture_id = %s WHERE id = %d AND status = 'pending'", $captureId, $id ) );
return 1 === $n;
}
/**
* Remember the PayPal capture id of a capture that is not final yet (PENDING / under review). Only touches a
* still-pending row that has no capture id; never changes the status. This is the "PayPal took the money" evidence
* that keeps Maintenance::purge_abandoned away and lets the COMPLETED webhook find the row by capture id.
*/
public static function record_capture_id( int $id, string $captureId ): bool {
global $wpdb;
if ( '' === $captureId ) {
return false;
}
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET paypal_capture_id = %s WHERE id = %d AND status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '')", $captureId, $id ) );
return 1 === $n;
}
/**
* Run every side effect of a completed donation (rules/timer/counter, rewards, tiers, end-at-target) and, only if ALL of
* them finished without error, stamp sg_donations.effects_applied_at. Never throws. Every step is idempotent, so this is
* also what Maintenance::reconcile_effects() replays for a donation whose request died after mark_completed().
*
* @return bool True when the donation is (now) marked as fully applied.
*/
public static function notify_applied( int $id ): bool {
$ok = self::call_engine( 'applyDonation', $id );
// Donation actions (rewards). Not under the goal lock: events are idempotent via a UNIQUE key. Never throws.
if ( ! \StreamGoals\Actions\Recorder::forDonation( $id ) ) {
$ok = false;
}
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) {
$ok = false;
}
if ( ! self::close_goal_if_target_reached( $id ) ) {
$ok = false;
}
return $ok && self::mark_effects_applied( $id );
}
/** Stamp "side effects applied" once. Only a completed row with a NULL stamp is touched (first stamp wins). */
public static function mark_effects_applied( int $id ): bool {
global $wpdb;
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET effects_applied_at = %s WHERE id = %d AND status = 'completed' AND effects_applied_at IS NULL", gmdate( 'Y-m-d H:i:s' ), $id ) );
return false !== $n;
}
/**
* Completed donations whose side effects were never confirmed: completed, effects_applied_at NULL, a real goal
* (test rows use goal_id 0), created between $notBefore and $notAfter (UTC 'Y-m-d H:i:s'; the lower bound keeps a
* permanently failing row from being retried forever, the upper bound leaves in-flight requests alone). Oldest first.
*
* @return int[]
*/
public static function unapplied_completed_ids( string $notAfter, string $notBefore, int $limit ): array {
global $wpdb;
$ids = $wpdb->get_col( $wpdb->prepare(
'SELECT id FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0 AND created_at < %s AND created_at >= %s ORDER BY id ASC LIMIT %d",
$notAfter,
$notBefore,
max( 1, $limit )
) );
return array_map( 'intval', (array) $ids );
}
/**
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
*
* @return bool False when the check failed.
*/
public static function close_goal_if_target_reached( int $donationId ): bool {
try {
$row = self::find( $donationId );
if ( $row && (int) $row->goal_id > 0 ) {
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
}
return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return false;
}
}
/** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */
public static function reached_goals(): array {
global $wpdb;
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
}
private static function call_engine( string $method, int $id ): bool {
$row = self::find( $id );
if ( ! $row ) {
return false; // vanished row: nothing to apply, and never claim success
}
try {
$donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row );
\StreamGoals\Rules\Engine::withGoalLock(
$donation->goalId,
static function () use ( $method, $donation ): void {
\StreamGoals\Rules\Engine::default()->$method( $donation );
}
);
return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return false;
}
}
}