Align timer state key with rules engine (timer_ends_at). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
81 lines
2.6 KiB
PHP
81 lines
2.6 KiB
PHP
<?php
|
|
declare( strict_types=1 );
|
|
|
|
namespace StreamGoals\Overlay;
|
|
|
|
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
|
final class WpdbDataSource implements OverlayDataSource {
|
|
|
|
private function t( string $name ): string {
|
|
global $wpdb;
|
|
return $wpdb->prefix . 'sg_' . $name;
|
|
}
|
|
|
|
public function activeGoal(): ?array {
|
|
global $wpdb;
|
|
$row = $wpdb->get_row( "SELECT * FROM {$this->t('goals')} WHERE status = 'active' ORDER BY id DESC LIMIT 1", ARRAY_A );
|
|
return $row ?: null;
|
|
}
|
|
|
|
public function raisedMinor( array $goal ): int {
|
|
global $wpdb;
|
|
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
|
|
$sum = $wpdb->get_var( $wpdb->prepare(
|
|
"SELECT COALESCE(SUM($col),0) FROM {$this->t('donations')} WHERE goal_id = %d AND status = 'completed'",
|
|
(int) $goal['id']
|
|
) );
|
|
return (int) $sum;
|
|
}
|
|
|
|
public function stateValue( int $goalId, string $key ): ?string {
|
|
global $wpdb;
|
|
$v = $wpdb->get_var( $wpdb->prepare( "SELECT svalue FROM {$this->t('state')} WHERE goal_id = %d AND skey = %s", $goalId, $key ) );
|
|
return null === $v ? null : (string) $v;
|
|
}
|
|
|
|
public function counter( int $goalId ): array {
|
|
global $wpdb;
|
|
$rows = $wpdb->get_results( $wpdb->prepare(
|
|
"SELECT skey, svalue FROM {$this->t('state')} WHERE goal_id = %d AND skey LIKE %s",
|
|
$goalId,
|
|
$wpdb->esc_like( 'counter' ) . '%'
|
|
), ARRAY_A );
|
|
$total = 0;
|
|
foreach ( (array) $rows as $r ) {
|
|
if ( preg_match( '/carry|remainder/i', (string) $r['skey'] ) || ! is_numeric( $r['svalue'] ) ) {
|
|
continue;
|
|
}
|
|
$total += (int) $r['svalue'];
|
|
}
|
|
$label = '';
|
|
$rules = $wpdb->get_col( $wpdb->prepare(
|
|
"SELECT config FROM {$this->t('rules')} WHERE goal_id = %d AND type = 'counter' AND enabled = 1 ORDER BY sort, id",
|
|
$goalId
|
|
) );
|
|
foreach ( (array) $rules as $cfg ) {
|
|
$d = json_decode( (string) $cfg, true );
|
|
if ( is_array( $d ) && ! empty( $d['label'] ) ) {
|
|
$label = (string) $d['label'];
|
|
break;
|
|
}
|
|
}
|
|
return array( 'label' => $label, 'value' => $total );
|
|
}
|
|
|
|
public function donations( ?int $sinceId, int $limit ): array {
|
|
global $wpdb;
|
|
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
|
$where = "status = 'completed' AND moderation = 'approved'";
|
|
if ( null === $sinceId ) {
|
|
$rows = $wpdb->get_results( "SELECT $cols FROM {$this->t('donations')} WHERE $where ORDER BY id DESC LIMIT 1", ARRAY_A );
|
|
} else {
|
|
$rows = $wpdb->get_results( $wpdb->prepare(
|
|
"SELECT $cols FROM {$this->t('donations')} WHERE $where AND id > %d ORDER BY id ASC LIMIT %d",
|
|
$sinceId,
|
|
$limit
|
|
), ARRAY_A );
|
|
}
|
|
return (array) $rows;
|
|
}
|
|
}
|