Tiered goals: ordered milestones with unlocks, tier-aware goal bar, TIER UNLOCKED alerts, next-unlock line
Test and Release / test (push) Successful in 1m21s
Test and Release / release (push) Successful in 4s

- Tiers\TierPolicy (pure), TierRepository (atomic reached marking), Tiers\Recorder hooked before close-at-target
- Admin tiers screen; goal target derived from the final tier
- Overlay goal widget shows Tier N of M and fills within the tier; alert pill; donate form 'Next unlock'
- Installer DB_VERSION 4 (sg_goal_tiers)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 13:09:18 -08:00
1 parent 39840a20d7
commit 4c379a0245
20 files changed
+1089 -14

No files matched your search

+2
View File
@@ -25,6 +25,8 @@ final class Admin {
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
'sg_tier_save' => array( GoalsPage::class, 'handleTierSave' ),
'sg_tier_delete' => array( GoalsPage::class, 'handleTierDelete' ),
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
+139 -2
View File
@@ -4,6 +4,9 @@ declare( strict_types=1 );
namespace StreamGoals\Admin;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\Tiers\TierPolicy;
use StreamGoals\Tiers\TierRepository;
/** Goals list/create/edit/status/delete, plus the per-goal rules editor. */
final class GoalsPage {
@@ -17,6 +20,8 @@ final class GoalsPage {
self::renderForm( 'edit' === $view ? $id : 0 );
} elseif ( 'rules' === $view && $id ) {
self::renderRules( $id );
} elseif ( 'tiers' === $view && $id ) {
self::renderTiers( $id );
} else {
self::renderList();
}
@@ -29,6 +34,7 @@ final class GoalsPage {
echo '<p><a class="page-title-action" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Add new goal</a></p>';
echo '<p class="description">Overlays and the donation form use your newest <strong>active</strong> goal(s). Pause a goal to stop accepting donations; mark it complete when you are done. A goal that has donations cannot be deleted (complete it instead), so your records stay intact.</p>';
$goals = Store::goals()->all();
$tierCounts = $goals ? ( new TierRepository() )->countsByGoal() : array();
if ( ! $goals ) {
echo '<div class="sg-card"><p>No goals yet. <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Create your first goal</a> or run the <a href="' . esc_url( SetupPage::url( 2 ) ) . '">setup guide</a>.</p></div>';
Admin::close();
@@ -47,6 +53,8 @@ final class GoalsPage {
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
$nt = $tierCounts[ $gid ] ?? 0;
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $gid ) ) ) . '">Tiers' . ( $nt > 0 ? ' (' . (int) $nt . ')' : '' ) . '</a> ';
foreach ( array( 'active' => array( 'paused', 'Pause' ), 'paused' => array( 'active', 'Resume' ), 'complete' => array( 'active', 'Reopen' ) ) as $from => [ $to, $lbl ] ) {
if ( $g['status'] === $from ) {
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => $to ), 'sg-inline' );
@@ -80,11 +88,16 @@ final class GoalsPage {
return;
}
$cur = $g ? Format::currency( $g['currency'] ) : Admin::currency();
$tiered = $id && (bool) ( new TierRepository() )->forGoal( $id );
Admin::open( $g ? 'Edit goal' : 'New goal' );
Admin::form( 'sg_goal_save', array( 'goal_id' => $id ) );
echo '<table class="form-table" role="presentation">';
echo '<tr><th scope="row"><label for="sg_title">Title</label></th><td><input type="text" required maxlength="190" id="sg_title" name="title" class="regular-text" value="' . esc_attr( (string) ( $g['title'] ?? '' ) ) . '"></td></tr>';
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
if ( $tiered ) {
echo '<tr><th scope="row">Target (' . esc_html( $cur ) . ')</th><td><strong>' . esc_html( Format::money( (int) $g['target_minor'], $cur ) ) . '</strong> <span class="description">Set automatically from your highest tier. To change it, <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $id ) ) ) . '">edit the tiers</a>.</span></td></tr>';
} else {
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
}
echo '<tr><th scope="row">Currency</th><td><strong>' . esc_html( $cur ) . '</strong> <span class="description">One currency is used across the whole site. Change it in <a href="' . esc_url( Admin::url( 'streamgoals-settings' ) ) . '">Settings</a> (applies to new goals only).</span></td></tr>';
$fmt = static fn( ?string $utc ): string => $utc ? get_date_from_gmt( $utc, 'Y-m-d\TH:i' ) : '';
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
@@ -116,10 +129,12 @@ final class GoalsPage {
$cur = $old ? Format::currency( $old['currency'] ) : Admin::currency();
$title = Input::text( $post['title'] ?? '', 190 );
$tgt = Input::amountToMinor( $post['target'] ?? '', $cur );
// A goal with tiers has a derived target (its highest tier): never taken from the form.
$tiered = $id && ( new TierRepository() )->forGoal( $id );
if ( '' === $title ) {
Admin::redirect( $back, 'error', 'Please give the goal a title.' );
}
if ( null === $tgt || $tgt <= 0 ) {
if ( ! $tiered && ( null === $tgt || $tgt <= 0 ) ) {
Admin::redirect( $back, 'error', 'Please enter a target greater than zero, for example 250.00.' );
}
$startRaw = Input::text( $post['starts_at'] ?? '', 20 );
@@ -133,6 +148,9 @@ final class GoalsPage {
Admin::redirect( $back, 'error', 'The end must be after the start.' );
}
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
if ( $tiered ) {
unset( $data['target_minor'] );
}
if ( $id ) {
Store::goals()->update( $id, $data );
} else {
@@ -171,6 +189,125 @@ final class GoalsPage {
Admin::redirect( Admin::url(), 'success', 'Goal deleted.' );
}
/* ----------------------------------------------------------------- tiers */
private static function tiersUrl( int $goalId, array $extra = array() ): string {
return Admin::url( Admin::HOME, array_merge( array( 'view' => 'tiers', 'goal' => $goalId ), $extra ) );
}
private static function renderTiers( int $goalId ): void {
$g = Store::goals()->find( $goalId );
if ( ! $g ) {
Admin::open( 'Goal not found' );
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
Admin::close();
return;
}
$cur = Format::currency( $g['currency'] );
$repo = new TierRepository();
$tiers = $repo->forGoal( $goalId );
$raised = Store::goals()->raised_minor( $goalId );
Admin::open( 'Tiers for "' . (string) $g['title'] . '"' );
echo '<p><a href="' . esc_url( Admin::url() ) . '">&larr; Back to goals</a></p>';
echo '<p class="sg-lead">Tiers turn one goal into a ladder of milestones. Each tier has a target and something you unlock or give away. When your total reaches a tier\'s target, that tier unlocks and the goal bar moves on to the next one. The goal\'s final target is your highest tier.</p>';
echo '<div class="sg-card"><h2>Your tiers</h2>';
echo '<p class="description">Raised so far: <strong>' . esc_html( Format::money( $raised, $cur ) ) . '</strong>. Targets are cumulative totals, not extra amounts: a tier at ' . esc_html( Format::money( 25000, $cur ) ) . ' unlocks when the goal total reaches ' . esc_html( Format::money( 25000, $cur ) ) . '.</p>';
if ( ! $tiers ) {
echo '<p>No tiers yet. This goal works as a single target until you add one.</p>';
} else {
echo '<table class="widefat striped sg-table"><thead><tr><th>#</th><th>Unlock</th><th>Target</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
foreach ( TierPolicy::sorted( $tiers ) as $i => $t ) {
$tid = (int) $t['id'];
$status = TierPolicy::status( $tiers, $t );
$label = 'reached' === $status ? 'Reached on ' . get_date_from_gmt( (string) $t['reached_at'], 'Y-m-d H:i' ) : ( 'current' === $status ? 'Current' : 'Upcoming' );
echo '<tr><td>' . (int) ( $i + 1 ) . '</td><td><strong>' . esc_html( $t['title'] ) . '</strong>';
if ( '' !== $t['description'] ) {
echo '<br><span class="description">' . esc_html( $t['description'] ) . '</span>';
}
echo '</td><td>' . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . '</td>';
echo '<td><span class="sg-badge sg-' . ( 'reached' === $status ? 'complete' : ( 'current' === $status ? 'active' : 'paused' ) ) . '">' . esc_html( $label ) . '</span></td><td class="sg-actions">';
echo '<a class="button" href="' . esc_url( self::tiersUrl( $goalId, array( 'tier' => $tid ) ) ) . '#sg-tier-form">Edit</a> ';
Admin::form( 'sg_tier_delete', array( 'goal_id' => $goalId, 'tier_id' => $tid ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this tier?">Delete</button></form></td></tr>';
}
echo '</tbody></table>';
}
echo '</div>';
$editId = Admin::get_int( 'tier' );
$edit = $editId ? $repo->find( $editId ) : null;
if ( $edit && (int) $edit['goal_id'] !== $goalId ) {
$edit = null;
}
$locked = $edit && TierPolicy::isReached( $edit );
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
echo '<div class="sg-card" id="sg-tier-form"><h2>' . ( $edit ? 'Edit tier' : 'Add a tier' ) . '</h2>';
Admin::form( 'sg_tier_save', array( 'goal_id' => $goalId, 'tier_id' => $edit ? (int) $edit['id'] : 0 ) );
echo '<table class="form-table" role="presentation">';
echo '<tr><th scope="row"><label for="sg_t_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" ' . ( $locked ? 'disabled' : 'required' ) . ' inputmode="decimal" id="sg_t_target" name="target" class="small-text" value="' . esc_attr( $edit ? Format::decimal( (int) $edit['target_minor'], $cur ) : '' ) . '">';
echo '<p class="description">' . ( $locked ? 'This tier has been reached, so its target is locked. You can still change its name and description.' : 'When your total reaches this amount, this tier unlocks and the goal bar moves on to the next one. Must be above what has been raised so far (' . esc_html( Format::money( $raised, $cur ) ) . ') and at least ' . esc_html( Format::money( $min, $cur ) ) . '.' ) . '</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_t_title">Item or unlock</label></th><td><input type="text" required maxlength="120" id="sg_t_title" name="title" class="regular-text" value="' . esc_attr( $edit ? (string) $edit['title'] : '' ) . '"><p class="description">What viewers get when this tier is reached, for example "New microphone". Up to 120 characters. Shown on your overlay and the donation form.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_t_desc">Description</label></th><td><input type="text" maxlength="255" id="sg_t_desc" name="description" class="large-text" value="' . esc_attr( $edit ? (string) $edit['description'] : '' ) . '"><p class="description">Optional. A short note, up to 255 characters.</p></td></tr>';
echo '</table><p><button class="button button-primary">' . ( $edit ? 'Save tier' : 'Add tier' ) . '</button>';
if ( $edit ) {
echo ' <a class="button" href="' . esc_url( self::tiersUrl( $goalId ) ) . '">Cancel</a>';
}
echo '</p></form></div>';
Admin::close();
}
public static function handleTierSave(): void {
Admin::guard( 'sg_tier_save' );
$post = Admin::post_raw();
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
$tierId = isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0;
$g = $goalId ? Store::goals()->find( $goalId ) : null;
if ( ! $g ) {
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
}
$back = self::tiersUrl( $goalId, $tierId ? array( 'tier' => $tierId ) : array() );
$cur = Format::currency( $g['currency'] );
$repo = new TierRepository();
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
$res = TierPolicy::validate(
$repo->forGoal( $goalId ),
$tierId ?: null,
Input::amountToMinor( $post['target'] ?? '', $cur ),
Input::text( $post['title'] ?? '', 200 ),
Input::text( $post['description'] ?? '', 400 ),
Store::goals()->raised_minor( $goalId ),
$min,
Format::money( $min, $cur )
);
if ( null === $res['data'] ) {
Admin::redirect( $back, 'error', (string) $res['error'] );
}
if ( $tierId ) {
$repo->update( $tierId, $goalId, $res['data'] );
} elseif ( $repo->create( $goalId, $res['data'] ) <= 0 ) {
Admin::redirect( $back, 'error', 'The tier could not be saved. Another tier may already have that target.' );
}
$repo->syncGoalTarget( $goalId );
$msg = 'Tier saved. The goal target is now ' . Format::money( TierPolicy::derivedGoalTarget( $repo->forGoal( $goalId ) ), $cur ) . '.';
if ( 'complete' === ( $g['status'] ?? '' ) ) {
$msg .= ' This goal is marked complete; use "Reopen" on the goals list if you want donations to continue.';
}
Admin::redirect( self::tiersUrl( $goalId ), 'success', $msg );
}
public static function handleTierDelete(): void {
Admin::guard( 'sg_tier_delete' );
$post = Admin::post_raw();
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
if ( $goalId && Store::goals()->find( $goalId ) ) {
$repo = new TierRepository();
$repo->delete( isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0, $goalId );
$repo->syncGoalTarget( $goalId ); // no-op when the last tier was removed: the goal keeps its current target (editable again)
}
Admin::redirect( self::tiersUrl( $goalId ), 'success', 'Tier deleted.' );
}
/* ----------------------------------------------------------------- rules */
private static function renderRules( int $goalId ): void {
+1
View File
@@ -87,6 +87,7 @@ final class Store {
self::deleteRule( (int) $r['id'], $goalId );
}
$wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) );
$wpdb->delete( self::t( 'goal_tiers' ), array( 'goal_id' => $goalId ), array( '%d' ) );
return self::goals()->delete( $goalId );
}
+15 -1
View File
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '3';
public const DB_VERSION = '4';
public static function activate(): void {
self::install_schema();
@@ -143,6 +143,20 @@ final class Installer {
KEY goal_enabled (goal_id,enabled)
) $c;" );
dbDelta( "CREATE TABLE {$p}goal_tiers (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
goal_id BIGINT UNSIGNED NOT NULL,
target_minor BIGINT UNSIGNED NOT NULL,
title VARCHAR(120) NOT NULL,
description VARCHAR(255) NOT NULL DEFAULT '',
reached_at DATETIME NULL,
reached_donation_id BIGINT UNSIGNED NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY goal_target (goal_id,target_minor),
KEY reached_donation (reached_donation_id)
) $c;" );
update_option( 'sg_db_version', self::DB_VERSION );
}
}
+4 -1
View File
@@ -31,7 +31,8 @@ final class OverlayService {
$gid = $goal ? (int) $goal['id'] : 0;
switch ( $widget ) {
case 'goal':
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0 );
$tiers = ( $gid && $this->source instanceof TiersSource ) ? $this->source->tiersFor( $gid ) : array();
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0, $tiers ?: null );
case 'timer':
return Payloads::timer(
$gid ? $this->source->stateValue( $gid, 'timer_ends_at' ) : null,
@@ -55,9 +56,11 @@ final class OverlayService {
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
$bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array();
$actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $ids ) : array();
$tiers = ( ( $recent || null !== $since ) && $ids && $this->source instanceof TiersSource ) ? $this->source->tiersReachedFor( $ids ) : array();
foreach ( $rows as $i => $r ) {
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
$rows[ $i ]['tiers'] = $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array();
}
$mediaFor = null;
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
+64 -1
View File
@@ -4,6 +4,7 @@ declare( strict_types=1 );
namespace StreamGoals\Overlay;
use StreamGoals\Core\Money;
use StreamGoals\Tiers\TierPolicy;
/**
* Pure, WordPress-free payload builders. Everything returned here is public-safe.
@@ -31,7 +32,10 @@ final class Payloads {
return max( 0, min( 100, intdiv( max( 0, $raised ) * 100, $target ) ) );
}
public static function goal( ?array $goal, int $raised ): array {
/**
* @param array<int,array<string,mixed>>|null $tiers Raw sg_goal_tiers rows; null/empty = an ordinary (untiered) goal, payload unchanged.
*/
public static function goal( ?array $goal, int $raised, ?array $tiers = null ): array {
if ( null === $goal ) {
return array( 'active' => false, 'title' => '', 'raised_minor' => 0, 'target_minor' => 0, 'percent' => 0,
'currency' => 'USD', 'raised_display' => '', 'target_display' => '' );
@@ -39,6 +43,9 @@ final class Payloads {
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
$target = max( 0, (int) ( $goal['target_minor'] ?? 0 ) );
$raised = max( 0, $raised );
if ( $tiers ) {
return self::tieredGoal( $goal, $raised, $cur, $tiers );
}
return array(
'active' => true,
'title' => (string) ( $goal['title'] ?? '' ),
@@ -51,6 +58,40 @@ final class Payloads {
);
}
/**
* Tiered goal: raised stays cumulative; target/percent describe the CURRENT tier (percent is within the tier).
* When every tier is reached the bar is full at the top tier's target.
*/
private static function tieredGoal( array $goal, int $raised, string $cur, array $tiers ): array {
$sorted = TierPolicy::sorted( $tiers );
$current = TierPolicy::currentTier( $sorted );
$all = null === $current;
$target = $all ? TierPolicy::derivedGoalTarget( $sorted ) : max( 0, (int) $current['target_minor'] );
$floor = TierPolicy::floorMinor( $sorted );
return array(
'active' => true,
'title' => (string) ( $goal['title'] ?? '' ),
'raised_minor' => $raised,
'target_minor' => $target,
'percent' => TierPolicy::percentFor( $sorted, $raised ),
'currency' => $cur,
'raised_display' => self::money( $raised, $cur ),
'target_display' => self::money( $target, $cur ),
'tiers' => array(
'count' => count( $sorted ),
'index' => TierPolicy::currentIndex( $sorted ),
'current' => $all ? null : array(
'title' => self::text( $current['title'] ?? '', 120 ),
'description' => self::text( $current['description'] ?? '', 255 ),
'target_minor' => $target,
'target_display' => self::money( $target, $cur ),
'floor_minor' => $floor,
),
'all_reached' => $all,
),
);
}
/**
* @param string|null $endsAt sg_state `timer_ends_at` (epoch seconds, or a UTC datetime string).
* @param string|null $pausedRemaining sg_state `paused_remaining` seconds; non-null means paused.
@@ -132,6 +173,7 @@ final class Payloads {
'message' => (string) ( $r['message'] ?? '' ),
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
'actions' => self::actionEvents( $r['actions'] ?? array() ),
'tiers' => self::tierEvents( $r['tiers'] ?? array() ),
'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null,
);
}
@@ -200,6 +242,27 @@ final class Payloads {
return $out;
}
/**
* Tiers a donation unlocked, for the "TIER UNLOCKED" pill: [ {title} ]. At most 5, titles capped at 80 chars, blanks dropped.
*
* @param mixed $events
* @return array<int,array{title:string}>
*/
public static function tierEvents( mixed $events ): array {
$out = array();
foreach ( is_array( $events ) ? $events : array() as $e ) {
$title = self::text( is_array( $e ) ? ( $e['title'] ?? '' ) : '', 80 );
if ( '' === $title ) {
continue;
}
$out[] = array( 'title' => $title );
if ( count( $out ) >= 5 ) {
break;
}
}
return $out;
}
/**
* The on-stream reward menu for the active goal. Empty list means "render nothing".
*
+23
View File
@@ -0,0 +1,23 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** Optional capability: goal tiers (milestones). Sources without it behave as if no goal had tiers. */
interface TiersSource {
/**
* Tiers of a goal ordered by target ascending. Rows with keys id, target_minor, title, description, reached_at.
*
* @return array<int,array<string,mixed>>
*/
public function tiersFor( int $goalId ): array;
/**
* Tiers unlocked by each donation, ONE lookup for the whole page: donation id => [ {title} ].
*
* @param int[] $donationIds
* @return array<int,array<int,array<string,mixed>>>
*/
public function tiersReachedFor( array $donationIds ): array;
}
+9 -1
View File
@@ -4,7 +4,7 @@ declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
/** @var array<int,?array{url:string,mime:string}> */
private array $attachments = array();
@@ -120,6 +120,14 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
return $out;
}
public function tiersFor( int $goalId ): array {
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->forGoal( $goalId );
}
public function tiersReachedFor( array $donationIds ): array {
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->reachedByDonation( $donationIds );
}
public function alertDefs(): array {
return ( new \StreamGoals\Alerts\DefRepository( $GLOBALS['wpdb'] ) )->enabled();
}
+7
View File
@@ -93,6 +93,13 @@ final class DonationStore {
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
// 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.
try {
\StreamGoals\Tiers\Recorder::forDonation( $id );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: tier unlock failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
self::close_goal_if_target_reached( $id );
}
+25 -1
View File
@@ -162,7 +162,8 @@ final class DonateController {
if ( $pinned && (int) $g['id'] !== $pinned ) {
continue;
}
$goals[] = array(
$next = self::next_unlock( $g );
$goals[] = ( null === $next ? array() : array( 'nextUnlock' => $next ) ) + array(
'id' => (int) $g['id'],
'title' => (string) $g['title'],
'currency' => strtoupper( (string) $g['currency'] ),
@@ -206,6 +207,8 @@ final class DonateController {
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
/* translators: %s: formatted amount, e.g. $5.00 */
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
/* translators: 1: item/unlock title, 2: formatted amount still needed, e.g. $106.00 */
'nextUnlock' => __( 'Next unlock: %1$s — %2$s to go', 'streamgoals-donate' ),
'actionsHint' => __( 'Pick a reward, or enter your own amount below.', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
@@ -222,6 +225,27 @@ final class DonateController {
/* ------------------------------------------------------------- Helpers */
/**
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
* Null for goals without tiers or with every tier reached. Computed when the page renders.
*
* @return array{title:string,remaining_minor:int}|null
*/
private static function next_unlock( array $goal ): ?array {
try {
global $wpdb;
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( (int) $goal['id'] );
$cur = $tiers ? \StreamGoals\Tiers\TierPolicy::currentTier( $tiers ) : null;
if ( null === $cur ) {
return null;
}
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( (int) $goal['id'] );
return array( 'title' => (string) $cur['title'], 'remaining_minor' => max( 1, (int) $cur['target_minor'] - $raised ) );
} catch ( \Throwable $e ) {
return null;
}
}
/**
* Enabled actions per goal id (rows with goal_id 0 apply to every goal), at or above the effective minimum.
* Public-safe fields only. One query; reads sg_actions directly.
+33
View File
@@ -0,0 +1,33 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tiers;
/** Unlocks the tiers a completed donation reaches. Runs BEFORE the "end at target" check. */
final class Recorder {
/**
* Never throws. Idempotent (atomic UPDATE ... WHERE reached_at IS NULL per tier). Test donations (goal_id 0) are skipped.
*
* @return int[] ids of the tiers this call unlocked.
*/
public static function forDonation( int $donationId ): array {
try {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) || (int) $row['goal_id'] <= 0 ) {
return array();
}
$goalId = (int) $row['goal_id'];
$repo = new TierRepository( $wpdb );
if ( ! $repo->forGoal( $goalId ) ) {
return array();
}
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( $goalId );
return $repo->markReached( $goalId, $raised, $donationId );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return array();
}
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tiers;
/**
* Pure rules for goal tiers (milestones). No WordPress / database access.
* A tier row is an array with keys: id, target_minor, title, description, reached_at (null|string), reached_donation_id.
*/
final class TierPolicy {
public const TITLE_MAX = 120;
public const DESC_MAX = 255;
/** Tiers ordered by target ascending (ties by id). Non-array entries are dropped. @return array[] */
public static function sorted( array $tiers ): array {
$tiers = array_values( array_filter( $tiers, 'is_array' ) );
usort(
$tiers,
static fn( array $a, array $b ): int => ( (int) $a['target_minor'] <=> (int) $b['target_minor'] ) ?: ( (int) ( $a['id'] ?? 0 ) <=> (int) ( $b['id'] ?? 0 ) )
);
return $tiers;
}
public static function isReached( array $tier ): bool {
return ! empty( $tier['reached_at'] );
}
/** The first tier (by target) that is not reached yet, or null (no tiers, or all reached). */
public static function currentTier( array $tiers ): ?array {
foreach ( self::sorted( $tiers ) as $t ) {
if ( ! self::isReached( $t ) ) {
return $t;
}
}
return null;
}
/** True when there is at least one tier and every tier is reached. */
public static function allReached( array $tiers ): bool {
return $tiers && null === self::currentTier( $tiers );
}
/** 1-based position of the current tier; when all are reached, the count; 0 without tiers. */
public static function currentIndex( array $tiers ): int {
$sorted = self::sorted( $tiers );
foreach ( $sorted as $i => $t ) {
if ( ! self::isReached( $t ) ) {
return $i + 1;
}
}
return count( $sorted );
}
/** Start of the current tier's range: the previous tier's target (0 for the first / when none is current). */
public static function floorMinor( array $tiers ): int {
$prev = 0;
foreach ( self::sorted( $tiers ) as $t ) {
if ( ! self::isReached( $t ) ) {
return $prev;
}
$prev = (int) $t['target_minor'];
}
return $prev; // all reached: the top tier's target
}
/** Progress inside a tier, 0..100 (clamped). Below the floor = 0, at or above the target = 100. */
public static function percent( int $raised, int $floor, int $target ): int {
if ( $target <= $floor ) {
return $raised >= $target && $target > 0 ? 100 : 0;
}
$p = intdiv( ( $raised - $floor ) * 100, $target - $floor );
return max( 0, min( 100, $p ) );
}
/** Percent within the current tier for the given tiers and raised total (100 when all reached, 0 without tiers). */
public static function percentFor( array $tiers, int $raised ): int {
$cur = self::currentTier( $tiers );
if ( null === $cur ) {
return $tiers ? 100 : 0;
}
return self::percent( $raised, self::floorMinor( $tiers ), (int) $cur['target_minor'] );
}
/** Money still needed to reach the current tier (0 when none). */
public static function remainingMinor( array $tiers, int $raised ): int {
$cur = self::currentTier( $tiers );
return null === $cur ? 0 : max( 0, (int) $cur['target_minor'] - $raised );
}
/** Every unreached tier whose target is at or below the raised total, in target order. A big donation can unlock several. @return array[] */
public static function newlyReached( array $tiers, int $raised ): array {
$out = array();
foreach ( self::sorted( $tiers ) as $t ) {
if ( ! self::isReached( $t ) && (int) $t['target_minor'] <= $raised ) {
$out[] = $t;
}
}
return $out;
}
/** The goal's target when it has tiers: the highest tier target (0 when no tiers). */
public static function derivedGoalTarget( array $tiers ): int {
$max = 0;
foreach ( $tiers as $t ) {
$max = max( $max, (int) ( $t['target_minor'] ?? 0 ) );
}
return $max;
}
/**
* Validate a tier form submission.
*
* @param array $tiers All tiers of the goal (including the one being edited).
* @param int|null $editId Tier id when editing, null when adding.
* @param int|null $target Parsed target in minor units (null = not a valid amount).
* @param int $raised Goal raised total (minor units).
* @param int $minMinor Settings::effectiveMin().
* @return array{data:?array{target_minor:int,title:string,description:string},error:?string}
*/
public static function validate( array $tiers, ?int $editId, ?int $target, string $title, string $description, int $raised, int $minMinor, string $minLabel = '' ): array {
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
$title = trim( $title );
$desc = trim( $description );
if ( '' === $title ) {
return $fail( 'Please name what unlocks at this tier, for example "New microphone".' );
}
if ( self::len( $title ) > self::TITLE_MAX ) {
return $fail( 'The title can be at most ' . self::TITLE_MAX . ' characters.' );
}
if ( self::len( $desc ) > self::DESC_MAX ) {
return $fail( 'The description can be at most ' . self::DESC_MAX . ' characters.' );
}
$existing = null;
if ( null !== $editId ) {
foreach ( $tiers as $t ) {
if ( (int) ( $t['id'] ?? 0 ) === $editId ) {
$existing = $t;
}
}
if ( null === $existing ) {
return $fail( 'That tier no longer exists.' );
}
}
if ( null !== $existing && self::isReached( $existing ) ) {
// Reached tiers: the target is locked, only the text can change.
return array( 'data' => array( 'target_minor' => (int) $existing['target_minor'], 'title' => $title, 'description' => $desc ), 'error' => null );
}
if ( null === $target || $target <= 0 ) {
return $fail( 'Please enter a target greater than zero, for example 250.00.' );
}
if ( $target < $minMinor ) {
return $fail( 'The target must be at least the minimum donation' . ( '' !== $minLabel ? ' (' . $minLabel . ')' : '' ) . '.' );
}
foreach ( $tiers as $t ) {
if ( (int) ( $t['id'] ?? 0 ) !== (int) $editId && (int) $t['target_minor'] === $target ) {
return $fail( 'Another tier already has that target. Each tier needs its own amount.' );
}
}
$unchanged = null !== $existing && (int) $existing['target_minor'] === $target;
if ( ! $unchanged && $target <= $raised ) {
return $fail( 'This goal has already raised more than that, so the tier would unlock instantly. Choose a target above the current total.' );
}
return array( 'data' => array( 'target_minor' => $target, 'title' => $title, 'description' => $desc ), 'error' => null );
}
/** Display status of a tier given the sorted list: 'reached' | 'current' | 'upcoming'. */
public static function status( array $tiers, array $tier ): string {
if ( self::isReached( $tier ) ) {
return 'reached';
}
$cur = self::currentTier( $tiers );
return $cur && (int) $cur['id'] === (int) $tier['id'] ? 'current' : 'upcoming';
}
private static function len( string $s ): int {
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tiers;
/** $wpdb access to sg_goal_tiers (and keeping sg_goals.target_minor in step). */
final class TierRepository {
private object $db;
public function __construct( ?object $db = null ) {
$this->db = $db ?? $GLOBALS['wpdb'];
}
private function t( string $name ): string {
return $this->db->prefix . 'sg_' . $name;
}
/** @return array{id:int,goal_id:int,target_minor:int,title:string,description:string,reached_at:?string,reached_donation_id:?int,created_at:string} */
private static function cast( array $r ): array {
return array(
'id' => (int) ( $r['id'] ?? 0 ),
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
'target_minor' => (int) ( $r['target_minor'] ?? 0 ),
'title' => (string) ( $r['title'] ?? '' ),
'description' => (string) ( $r['description'] ?? '' ),
'reached_at' => isset( $r['reached_at'] ) && '' !== (string) $r['reached_at'] ? (string) $r['reached_at'] : null,
'reached_donation_id' => isset( $r['reached_donation_id'] ) && null !== $r['reached_donation_id'] ? (int) $r['reached_donation_id'] : null,
'created_at' => (string) ( $r['created_at'] ?? '' ),
);
}
/** Tiers of a goal ordered by target ascending. @return array[] */
public function forGoal( int $goalId ): array {
$rows = $this->db->get_results(
$this->db->prepare( 'SELECT * FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d ORDER BY target_minor ASC, id ASC', $goalId ),
ARRAY_A
);
return array_map( array( self::class, 'cast' ), (array) $rows );
}
public function find( int $id ): ?array {
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t( 'goal_tiers' ) . ' WHERE id = %d', $id ), ARRAY_A );
return $row ? self::cast( $row ) : null;
}
/** Tier counts per goal id (one query) for the goals list. @return array<int,int> */
public function countsByGoal(): array {
$rows = $this->db->get_results( 'SELECT goal_id, COUNT(*) AS n FROM ' . $this->t( 'goal_tiers' ) . ' GROUP BY goal_id', ARRAY_A );
$out = array();
foreach ( (array) $rows as $r ) {
$out[ (int) $r['goal_id'] ] = (int) $r['n'];
}
return $out;
}
/** @param array{target_minor:int,title:string,description:string} $d @return int new id (0 on failure, e.g. duplicate target) */
public function create( int $goalId, array $d ): int {
$ok = $this->db->insert(
$this->t( 'goal_tiers' ),
array(
'goal_id' => $goalId,
'target_minor' => (int) $d['target_minor'],
'title' => (string) $d['title'],
'description' => (string) $d['description'],
'created_at' => gmdate( 'Y-m-d H:i:s' ),
),
array( '%d', '%d', '%s', '%s', '%s' )
);
return $ok ? (int) $this->db->insert_id : 0;
}
public function update( int $id, int $goalId, array $d ): void {
$this->db->update(
$this->t( 'goal_tiers' ),
array( 'target_minor' => (int) $d['target_minor'], 'title' => (string) $d['title'], 'description' => (string) $d['description'] ),
array( 'id' => $id, 'goal_id' => $goalId ),
array( '%d', '%s', '%s' ),
array( '%d', '%d' )
);
}
public function delete( int $id, int $goalId ): void {
$this->db->delete( $this->t( 'goal_tiers' ), array( 'id' => $id, 'goal_id' => $goalId ), array( '%d', '%d' ) );
}
/**
* Mark every unreached tier of the goal with target <= $raised as reached by $donationId. One atomic
* UPDATE per tier (WHERE reached_at IS NULL): replays and concurrent callers cannot re-mark a tier.
*
* @return int[] ids of the tiers THIS call marked.
*/
public function markReached( int $goalId, int $raised, int $donationId ): array {
$marked = array();
if ( $goalId <= 0 || $donationId <= 0 ) {
return $marked;
}
$now = gmdate( 'Y-m-d H:i:s' );
foreach ( TierPolicy::newlyReached( $this->forGoal( $goalId ), $raised ) as $tier ) {
$n = $this->db->query(
$this->db->prepare(
'UPDATE ' . $this->t( 'goal_tiers' ) . ' SET reached_at = %s, reached_donation_id = %d WHERE id = %d AND reached_at IS NULL',
$now,
$donationId,
(int) $tier['id']
)
);
if ( 1 === (int) $n ) {
$marked[] = (int) $tier['id'];
}
}
return $marked;
}
/**
* Tiers unlocked by each donation, one query for the whole page: donation id => [ {title}, ... ] in target order.
*
* @param int[] $donationIds
* @return array<int,array<int,array{title:string}>>
*/
public function reachedByDonation( array $donationIds ): array {
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
if ( ! $ids ) {
return array();
}
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
$rows = $this->db->get_results(
$this->db->prepare( 'SELECT reached_donation_id, title FROM ' . $this->t( 'goal_tiers' ) . " WHERE reached_donation_id IN ($in) ORDER BY target_minor ASC, id ASC", ...$ids ),
ARRAY_A
);
$out = array();
foreach ( (array) $rows as $r ) {
$out[ (int) $r['reached_donation_id'] ][] = array( 'title' => (string) $r['title'] );
}
return $out;
}
/**
* Keep sg_goals.target_minor equal to the highest tier target. Leaves the goal untouched when it has no tiers.
*
* @return bool true when the goal row was set from tiers.
*/
public function syncGoalTarget( int $goalId ): bool {
$max = $this->db->get_var( $this->db->prepare( 'SELECT MAX(target_minor) FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d', $goalId ) );
if ( null === $max || (int) $max <= 0 ) {
return false;
}
$this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'goals' ) . ' SET target_minor = %d WHERE id = %d', (int) $max, $goalId ) );
return true;
}
}