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

+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;
}
}