2026-11-15 10:41:29 -08:00
<? php
declare ( strict_types = 1 );
namespace StreamGoals\Core ;
/**
* Daily housekeeping: removes checkouts that were started but never paid.
*
* Only rows that never received a PayPal capture id are purged, and only after a week, so a slow payment
* that PayPal finalizes later through the webhook is never discarded.
*/
final class Maintenance {
public const HOOK = 'sg_purge_abandoned' ;
public const MAX_AGE_DAYS = 7 ;
2026-11-15 17:07:32 -08:00
/** Reconcile "completed but side effects lost" donations (see reconcile_effects()). */
public const RECONCILE_HOOK = 'sg_reconcile_effects' ;
public const RECONCILE_SCHEDULE = 'sg_five_minutes' ;
/** A donation must be this old before it is replayed, so a request still applying its effects is left alone. */
public const RECONCILE_MIN_AGE = 120 ;
/** Older donations are not retried (a row that can never succeed must not be replayed forever). */
public const RECONCILE_MAX_AGE_DAYS = 30 ;
public const RECONCILE_BATCH = 25 ;
2026-11-15 10:41:29 -08:00
public static function register () : void {
add_action ( self :: HOOK , array ( self :: class , 'purge_abandoned' ) );
if ( ! wp_next_scheduled ( self :: HOOK ) ) {
wp_schedule_event ( time () + HOUR_IN_SECONDS , 'daily' , self :: HOOK );
}
2026-11-15 17:07:32 -08:00
add_filter ( 'cron_schedules' , array ( self :: class , 'cron_schedules' ) );
add_action ( self :: RECONCILE_HOOK , array ( self :: class , 'reconcile_effects' ) );
if ( ! wp_next_scheduled ( self :: RECONCILE_HOOK ) ) {
wp_schedule_event ( time () + 300 , self :: RECONCILE_SCHEDULE , self :: RECONCILE_HOOK );
}
}
/** @param array $schedules @return array */
public static function cron_schedules ( $schedules ) : array {
$schedules = is_array ( $schedules ) ? $schedules : array ();
$schedules [ self :: RECONCILE_SCHEDULE ] = array ( 'interval' => 300 , 'display' => 'Every five minutes (StreamGoals)' );
return $schedules ;
2026-11-15 10:41:29 -08:00
}
public static function unschedule () : void {
wp_clear_scheduled_hook ( self :: HOOK );
2026-11-15 17:07:32 -08:00
wp_clear_scheduled_hook ( self :: RECONCILE_HOOK );
}
/**
* Replays the side effects (rules/timer/counter, rewards, tiers, end-at-target) of completed donations whose request
* died before DonationStore::notify_applied() could stamp effects_applied_at. Safe by construction: every effect is
* idempotent per (rule, donation) / (donation, action) / tier, and the donation row itself is never touched here.
* Single-flight through a MySQL named lock so overlapping cron runs do not pile up.
*
* @return int Donations whose effects were confirmed applied by this run.
*/
public static function reconcile_effects () : int {
global $wpdb ;
$locked = $wpdb && 1 === ( int ) $wpdb -> get_var ( $wpdb -> prepare ( 'SELECT GET_LOCK(%s, 0)' , 'sg_reconcile_effects' ) );
if ( ! $locked ) {
return 0 ;
}
try {
return self :: reconcile (
time (),
array ( \StreamGoals\PayPal\DonationStore :: class , 'unapplied_completed_ids' ),
array ( \StreamGoals\PayPal\DonationStore :: class , 'notify_applied' )
);
} catch ( \Throwable $e ) {
error_log ( 'StreamGoals: reconcile failed: ' . $e -> getMessage () ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return 0 ;
} finally {
$wpdb -> get_var ( $wpdb -> prepare ( 'SELECT RELEASE_LOCK(%s)' , 'sg_reconcile_effects' ) );
}
}
/**
* Pure orchestration (unit-tested).
*
* @param callable $find fn(string $notAfter, string $notBefore, int $limit): int[]
* @param callable $apply fn(int $donationId): bool true once the donation is stamped as applied
*/
public static function reconcile ( int $now , callable $find , callable $apply ) : int {
$notAfter = gmdate ( 'Y-m-d H:i:s' , $now - self :: RECONCILE_MIN_AGE );
$notBefore = gmdate ( 'Y-m-d H:i:s' , $now - self :: RECONCILE_MAX_AGE_DAYS * 86400 );
$done = 0 ;
foreach ( ( array ) $find ( $notAfter , $notBefore , self :: RECONCILE_BATCH ) as $id ) {
try {
if ( $apply ( ( int ) $id ) ) {
++ $done ;
}
} catch ( \Throwable $e ) {
error_log ( 'StreamGoals: reconcile of donation ' . ( int ) $id . ' failed: ' . $e -> getMessage () ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
}
return $done ;
2026-11-15 10:41:29 -08:00
}
2026-11-15 14:07:44 -08:00
/**
* The single definition of "abandoned checkout", mirrored by the DELETE below (MaintenancePurgeTest checks both).
* Never purgeable: not pending, younger than MAX_AGE_DAYS, a test row (goal_id 0), or ANY row carrying PayPal capture
* evidence (a capture id, even from a PENDING/under-review capture: PayPal may still finalize it by webhook).
*
* @param array|object $row status, goal_id, paypal_capture_id, created_at (UTC 'Y-m-d H:i:s')
*/
public static function isPurgeable ( array | object $row , int $now ) : bool {
$r = ( array ) $row ;
if ( 'pending' !== ( string ) ( $r [ 'status' ] ?? '' ) || ( int ) ( $r [ 'goal_id' ] ?? 0 ) <= 0 ) {
return false ;
}
if ( '' !== trim ( ( string ) ( $r [ 'paypal_capture_id' ] ?? '' ) ) ) {
return false ;
}
$created = strtotime ( ( string ) ( $r [ 'created_at' ] ?? '' ) . ' UTC' );
return false !== $created && $created < $now - self :: MAX_AGE_DAYS * DAY_IN_SECONDS ;
}
2026-11-15 10:41:29 -08:00
/** @return int Number of rows removed. */
public static function purge_abandoned () : int {
global $wpdb ;
$table = $wpdb -> prefix . 'sg_donations' ;
$cutoff = gmdate ( 'Y-m-d H:i:s' , time () - self :: MAX_AGE_DAYS * DAY_IN_SECONDS );
$n = $wpdb -> query (
$wpdb -> prepare (
"DELETE FROM { $table } WHERE status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '') AND goal_id > 0 AND created_at < %s" , // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$cutoff
)
);
return ( int ) $n ;
}
}