Files
wp-donations/includes/Admin/GoalsPage.php
T
shadowdaoandClaude Sonnet 5.5 fb200594ce
Test and Release / test (push) Successful in 1m26s
Test and Release / release (push) Successful in 5s
Admin tables: scroll containers and phone cards; Alerts list flags missing media
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:59:20 -08:00

464 lines
31 KiB
PHP

<?php
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 {
private const STATUSES = array( 'active' => 'Active', 'paused' => 'Paused', 'complete' => 'Complete' );
public static function render(): void {
$view = Admin::get_str( 'view' );
$id = Admin::get_int( 'goal' );
if ( in_array( $view, array( 'new', 'edit' ), true ) ) {
self::renderForm( 'edit' === $view ? $id : 0 );
} elseif ( 'rules' === $view && $id ) {
self::renderRules( $id );
} elseif ( 'tiers' === $view && $id ) {
self::renderTiers( $id );
} else {
self::renderList();
}
}
/* ------------------------------------------------------------------ list */
private static function renderList(): void {
Admin::open( 'Goals' );
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();
return;
}
echo Admin::tableOpen( array( 'Goal', 'Status', 'Raised', 'Dates', 'Actions' ), 'Goals' );
foreach ( $goals as $g ) {
$gid = (int) $g['id'];
$cur = Format::currency( $g['currency'] );
$raised = Store::goals()->raised_minor( $gid );
$target = (int) $g['target_minor'];
$pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0;
echo '<tr>' . Admin::td( 'Goal' ) . '<strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' &middot; <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
echo Admin::td( 'Status' ) . '<span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
echo Admin::td( 'Raised' ) . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
echo Admin::td( 'Dates' ) . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td>' . Admin::td( 'Actions', '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' );
echo '<button class="button">' . esc_html( $lbl ) . '</button></form> ';
}
}
if ( 'complete' !== $g['status'] ) {
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => 'complete' ), 'sg-inline' );
echo '<button class="button">Mark complete</button></form> ';
}
Admin::form( 'sg_goal_delete', array( 'goal_id' => $gid ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this goal and its rules? This cannot be undone.">Delete</button></form>';
echo '</td></tr>';
}
echo Admin::tableClose();
Admin::close();
}
private static function dateLabel( ?string $utc, string $prefix ): string {
return $utc ? $prefix . ': ' . get_date_from_gmt( $utc, 'Y-m-d H:i' ) : $prefix . ': no date';
}
/* ------------------------------------------------------------------ form */
private static function renderForm( int $id ): void {
$g = $id ? Store::goals()->find( $id ) : null;
if ( $id && ! $g ) {
Admin::open( 'Goal not found' );
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
Admin::close();
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>';
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>';
echo '<tr><th scope="row"><label for="sg_end">Ends</label></th><td><input type="datetime-local" id="sg_end" name="ends_at" value="' . esc_attr( $fmt( $g['ends_at'] ?? null ) ) . '"> <span class="description">Optional. Donations stop after this time.</span></td></tr>';
echo '<tr><th scope="row">Fees</th><td><label><input type="checkbox" name="counts_fees" value="1"' . checked( ! empty( $g['counts_fees'] ), true, false ) . '> Count fees covered by donors towards the goal</label><p class="description">Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.</p></td></tr>';
echo '<tr><th scope="row">End at target</th><td><label><input type="checkbox" name="close_at_target" value="1"' . checked( ! empty( $g['close_at_target'] ), true, false ) . '> Close this goal to donations when the target is reached</label><p class="description">When the raised total reaches or goes over the target, the goal is marked complete and the donation page stops taking donations to it. Donations already in checkout still complete. You can reopen it with &quot;Reopen&quot; (raise the target first if you want more donations: a reopened goal that is still at or over its target closes again after the next donation).</p></td></tr>';
echo '</table><p><button class="button button-primary">' . ( $g ? 'Save goal' : 'Create goal' ) . '</button> <a class="button" href="' . esc_url( Admin::url() ) . '">Cancel</a></p></form>';
Admin::close();
}
/** 'Y-m-d\TH:i' in the site time zone -> UTC 'Y-m-d H:i:s', or null when empty/invalid. */
private static function toUtc( string $local ): ?string {
if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $local ) ) {
return null;
}
$utc = get_gmt_from_date( str_replace( 'T', ' ', $local ) . ':00' );
return $utc ?: null;
}
public static function handleSave(): void {
Admin::guard( 'sg_goal_save' );
$post = Admin::post_raw();
$id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
$back = Admin::url( Admin::HOME, $id ? array( 'view' => 'edit', 'goal' => $id ) : array( 'view' => 'new' ) );
$old = $id ? Store::goals()->find( $id ) : null;
if ( $id && ! $old ) {
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
}
$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 ( ! $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 );
$endRaw = Input::text( $post['ends_at'] ?? '', 20 );
$start = '' === $startRaw ? null : self::toUtc( $startRaw );
$end = '' === $endRaw ? null : self::toUtc( $endRaw );
if ( ( '' !== $startRaw && null === $start ) || ( '' !== $endRaw && null === $end ) ) {
Admin::redirect( $back, 'error', 'That date is not valid.' );
}
if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) {
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 {
$data['currency'] = $cur;
$data['status'] = 'active';
$id = Store::goals()->create( $data );
if ( $id <= 0 ) {
Admin::redirect( $back, 'error', 'The goal could not be saved.' );
}
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $id ) ), 'success', 'Goal created. Add rules below if you want a timer or counter.' );
}
Admin::redirect( Admin::url(), 'success', 'Goal saved.' );
}
public static function handleStatus(): void {
Admin::guard( 'sg_goal_status' );
$post = Admin::post_raw();
$id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
$status = isset( $post['status'] ) && is_string( $post['status'] ) ? $post['status'] : '';
if ( ! $id || ! isset( self::STATUSES[ $status ] ) || ! Store::goals()->find( $id ) ) {
Admin::redirect( Admin::url(), 'error', 'Could not change that goal.' );
}
Store::goals()->update( $id, array( 'status' => $status ) );
Admin::redirect( Admin::url(), 'success', 'Goal is now ' . strtolower( self::STATUSES[ $status ] ) . '.' );
}
public static function handleDelete(): void {
Admin::guard( 'sg_goal_delete' );
$id = isset( $_POST['goal_id'] ) ? absint( wp_unslash( $_POST['goal_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification
if ( ! $id || ! Store::goals()->find( $id ) ) {
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
}
if ( ! Store::deleteGoal( $id ) ) {
Admin::redirect( Admin::url(), 'error', 'This goal has donations, so it cannot be deleted. Mark it complete instead.' );
}
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 Admin::tableOpen( array( '#', 'Unlock', 'Target', 'Status', 'Actions' ), 'Tiers' );
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>' . Admin::td( '#' ) . (int) ( $i + 1 ) . '</td>' . Admin::td( 'Unlock' ) . '<strong>' . esc_html( $t['title'] ) . '</strong>';
if ( '' !== $t['description'] ) {
echo '<br><span class="description">' . esc_html( $t['description'] ) . '</span>';
}
echo '</td>' . Admin::td( 'Target' ) . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . '</td>';
echo Admin::td( 'Status' ) . '<span class="sg-badge sg-' . ( 'reached' === $status ? 'complete' : ( 'current' === $status ? 'active' : 'paused' ) ) . '">' . esc_html( $label ) . '</span></td>' . Admin::td( 'Actions', '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 Admin::tableClose();
}
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 {
$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'] );
$rules = Store::rules( $goalId );
Admin::open( 'Rules for "' . (string) $g['title'] . '"' );
echo '<p><a href="' . esc_url( Admin::url() ) . '">&larr; Back to goals</a></p>';
echo '<p class="sg-lead">Rules decide what each donation does besides filling the progress bar: add time to a subathon timer, bump a counter, or fire a bonus alert.</p>';
$editId = Admin::get_int( 'rule' );
$editRule = $editId ? Store::rule( $editId, $goalId ) : null;
echo '<div class="sg-card"><h2>Current rules</h2>';
if ( ! $rules ) {
echo '<p>No rules yet. The goal bar works without any rules.</p>';
} else {
echo Admin::tableOpen( array( 'Rule', 'What it does', 'Actions' ), 'Rules' );
foreach ( $rules as $r ) {
$rid = (int) $r['id'];
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '">' . Admin::td( 'Rule' ) . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
try {
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
} catch ( \Throwable $e ) {
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
}
echo Admin::td( 'What it does' ) . esc_html( $summary ) . '</td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
Admin::form( 'sg_rule_delete', array( 'goal_id' => $goalId, 'rule_id' => $rid ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this rule?">Delete</button></form></td></tr>';
}
echo Admin::tableClose();
}
echo '</div>';
// Live preview of saved, enabled rules.
$data = array(
'currency' => $cur,
'exp' => Money::exponent( $cur ),
'rules' => array_values( array_map( static fn( $r ) => array( 'type' => $r['type'], 'config' => $r['config'] ), array_filter( $rules, static fn( $r ) => (bool) $r['enabled'] ) ) ),
);
echo '<div class="sg-card"><h2>What would a donation do?</h2><label>Donation amount (' . esc_html( $cur ) . ') <input type="text" id="sg-preview-amount" class="small-text" inputmode="decimal" value="' . esc_attr( 0 === $data['exp'] ? '2500' : '25.00' ) . '"></label>';
echo '<ul id="sg-preview-out" class="sg-preview-list" aria-live="polite"></ul>';
echo '<p class="description">Based on your enabled rules, for a single donation on its own. Carry-over from earlier donations and total limits are not included.</p>';
echo '<script type="application/json" id="sg-rules-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
self::renderRuleForm( $goalId, $cur, $editRule );
Admin::close();
}
private static function renderRuleForm( int $goalId, string $cur, ?array $edit ): void {
$type = $edit ? (string) $edit['type'] : 'add_time';
$vals = $edit ? RuleConfig::toForm( $type, $edit['config'], $cur ) : array();
$v = static fn( string $t, string $k, string $d = '' ): string => esc_attr( (string) ( $type === $t && isset( $vals[ $k ] ) ? $vals[ $k ] : $d ) );
$basisOpts = static function ( string $t ) use ( $type, $vals ): string {
$cur = $type === $t ? ( $vals['basis'] ?? 'base' ) : 'base';
return '<select name="rule[' . $t . '][basis]"><option value="base"' . selected( $cur, 'base', false ) . '>The amount the donor chose (recommended)</option><option value="total"' . selected( $cur, 'total', false ) . '>The amount including covered fees</option></select>';
};
echo '<div class="sg-card" id="sg-rule-form"><h2>' . ( $edit ? 'Edit rule' : 'Add a rule' ) . '</h2>';
Admin::form( 'sg_rule_save', array( 'goal_id' => $goalId, 'rule_id' => $edit ? (int) $edit['id'] : 0 ), 'sg-rule-form' );
if ( $edit ) {
echo '<input type="hidden" name="type" value="' . esc_attr( $type ) . '"><p><strong>' . esc_html( RuleConfig::TYPES[ $type ] ?? $type ) . '</strong></p>';
} else {
echo '<p><label>Type <select name="type" id="sg-rule-type">';
foreach ( RuleConfig::TYPES as $k => $l ) {
echo '<option value="' . esc_attr( $k ) . '">' . esc_html( $l ) . '</option>';
}
echo '</select></label></p>';
}
// add_time
echo '<div class="sg-rule-group" data-type="add_time"' . ( 'add_time' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" name="rule[add_time][time_amount]" class="small-text" data-f="time_amount" value="' . $v( 'add_time', 'time_amount', '1' ) . '">';
echo ' <select name="rule[add_time][time_unit]" data-f="time_unit">';
foreach ( array( 'seconds', 'minutes', 'hours' ) as $u ) {
echo '<option value="' . esc_attr( $u ) . '"' . selected( 'add_time' === $type ? ( $vals['time_unit'] ?? 'minutes' ) : 'minutes', $u, false ) . '>' . esc_html( $u ) . '</option>';
}
echo '</select> to the timer for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" name="rule[add_time][unit_amount]" class="small-text" data-f="unit_amount" value="' . $v( 'add_time', 'unit_amount', 0 === Money::exponent( $cur ) ? '100' : '1.00' ) . '"> donated.</p>';
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' || ( $vals['max_timer_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
echo '<p><label>Most minutes one donation can add <input type="number" min="1" class="small-text" name="rule[add_time][cap_minutes]" data-f="cap_minutes" value="' . $v( 'add_time', 'cap_minutes' ) . '"></label></p>';
echo '<p><label>Most minutes this rule can add in total <input type="number" min="1" class="small-text" name="rule[add_time][max_total_minutes]" data-f="max_total_minutes" value="' . $v( 'add_time', 'max_total_minutes' ) . '"></label></p>';
echo '<p><label>Longest the timer can ever get (minutes) <input type="number" min="1" class="small-text" name="rule[add_time][max_timer_minutes]" data-f="max_timer_minutes" value="' . $v( 'add_time', 'max_timer_minutes' ) . '"></label> <span class="description">Leave empty for no limit. For example, 1440 means the clock never shows more than 24 hours.</span></p>';
echo '<p><label>Count ' . $basisOpts( 'add_time' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped parts
// counter
echo '<div class="sg-rule-group" data-type="counter"' . ( 'counter' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" class="small-text" name="rule[counter][step]" data-f="step" value="' . $v( 'counter', 'step', '1' ) . '"> to the counter for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[counter][unit_amount]" data-f="unit_amount" value="' . $v( 'counter', 'unit_amount', 0 === Money::exponent( $cur ) ? '1000' : '10.00' ) . '"> donated.</p>';
echo '<p><label>Counter name (shown on the overlay) <input type="text" maxlength="40" name="rule[counter][label]" data-f="label" placeholder="Pies thrown" value="' . $v( 'counter', 'label' ) . '"></label></p>';
echo '<p><label><input type="checkbox" name="rule[counter][carry_over]" value="1" data-f="carry_over"' . checked( 'counter' === $type ? ! empty( $vals['carry_over'] ) : true, true, false ) . '> Carry leftovers to the next donation (so two $5 donations count as one $10)</label></p>';
echo '<details><summary>Advanced</summary><p><label>Count ' . $basisOpts( 'counter' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput
// bonus
echo '<div class="sg-rule-group" data-type="bonus"' . ( 'bonus' === $type ? '' : ' hidden' ) . '><p>Trigger a bonus when a single donation is at least ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[bonus][min_amount]" data-f="min_amount" value="' . $v( 'bonus', 'min_amount', 0 === Money::exponent( $cur ) ? '5000' : '50.00' ) . '">.</p>';
echo '<p><label>Bonus name <input type="text" maxlength="40" name="rule[bonus][event]" data-f="event" value="' . $v( 'bonus', 'event', 'big_donation' ) . '"></label> <span class="description">Letters, numbers, _ and - only.</span></p>';
echo '<details><summary>Advanced</summary><p><label>Count ' . $basisOpts( 'bonus' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput
echo '<p class="sg-form-preview" id="sg-form-preview" aria-live="polite"></p>';
echo '<p><button class="button button-primary">' . ( $edit ? 'Save rule' : 'Add rule' ) . '</button>';
if ( $edit ) {
echo ' <a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId ) ) ) . '">Cancel</a>';
}
echo '</p></form></div>';
}
public static function handleRuleSave(): void {
Admin::guard( 'sg_rule_save' );
$post = Admin::post_raw();
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
$ruleId = isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0;
$g = $goalId ? Store::goals()->find( $goalId ) : null;
$back = Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId ) );
if ( ! $g ) {
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
}
$type = isset( $post['type'] ) && is_string( $post['type'] ) ? $post['type'] : '';
if ( ! isset( RuleConfig::TYPES[ $type ] ) ) {
Admin::redirect( $back, 'error', 'Please choose a rule type.' );
}
$existing = null;
if ( $ruleId ) {
$existing = Store::rule( $ruleId, $goalId );
if ( ! $existing || $existing['type'] !== $type ) {
Admin::redirect( $back, 'error', 'That rule no longer exists.' );
}
}
$input = isset( $post['rule'][ $type ] ) && is_array( $post['rule'][ $type ] ) ? $post['rule'][ $type ] : array();
$res = RuleConfig::sanitize( $type, $input, Format::currency( $g['currency'] ) );
if ( null === $res['config'] ) {
Admin::redirect( $back . ( $ruleId ? '&rule=' . $ruleId : '' ), 'error', implode( ' ', $res['errors'] ) );
}
Store::saveRule( $goalId, $type, $res['config'], $existing ? $ruleId : null );
Admin::redirect( $back, 'success', 'Rule saved: ' . RuleConfig::summary( $type, $res['config'], Format::currency( $g['currency'] ) ) . '.' );
}
public static function handleRuleToggle(): void {
Admin::guard( 'sg_rule_toggle' );
$post = Admin::post_raw();
$gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
Store::setRuleEnabled( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid, ! empty( $post['enabled'] ) );
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule updated.' );
}
public static function handleRuleDelete(): void {
Admin::guard( 'sg_rule_delete' );
$post = Admin::post_raw();
$gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
Store::deleteRule( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid );
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule deleted.' );
}
}