'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 '
Add new goal
';
echo 'Overlays and the donation form use your newest active 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.
';
$goals = Store::goals()->all();
$tierCounts = $goals ? ( new TierRepository() )->countsByGoal() : array();
if ( ! $goals ) {
echo '';
Admin::close();
return;
}
echo 'Goal Status Raised Dates Actions ';
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 '' . esc_html( (string) $g['title'] ) . ' ID ' . $gid . ' · [streamgoals_donate goal="' . $gid . '"] ';
echo '' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . ' ';
echo '' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)
' . ( ! empty( $g['close_at_target'] ) ? 'Closes at target ' : '' ) . ' ';
echo '' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . ' ' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . ' ';
echo 'Edit ';
echo 'Rules ';
$nt = $tierCounts[ $gid ] ?? 0;
echo 'Tiers' . ( $nt > 0 ? ' (' . (int) $nt . ')' : '' ) . ' ';
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 '' . esc_html( $lbl ) . ' ';
}
}
if ( 'complete' !== $g['status'] ) {
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => 'complete' ), 'sg-inline' );
echo 'Mark complete ';
}
Admin::form( 'sg_goal_delete', array( 'goal_id' => $gid ), 'sg-inline sg-confirm' );
echo 'Delete ';
echo ' ';
}
echo '
';
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 'Back to goals
';
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 '' . ( $g ? 'Save goal' : 'Create goal' ) . ' Cancel
';
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 'Back to goals
';
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 '← Back to goals
';
echo '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.
';
echo 'Your tiers ';
echo '
Raised so far: ' . esc_html( Format::money( $raised, $cur ) ) . ' . 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 ) ) . '.
';
if ( ! $tiers ) {
echo '
No tiers yet. This goal works as a single target until you add one.
';
} else {
echo '
# Unlock Target Status Actions ';
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 '' . (int) ( $i + 1 ) . ' ' . esc_html( $t['title'] ) . ' ';
if ( '' !== $t['description'] ) {
echo '' . esc_html( $t['description'] ) . ' ';
}
echo '' . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . ' ';
echo '' . esc_html( $label ) . ' ';
echo 'Edit ';
Admin::form( 'sg_tier_delete', array( 'goal_id' => $goalId, 'tier_id' => $tid ), 'sg-inline sg-confirm' );
echo 'Delete ';
}
echo '
';
}
echo '
';
$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 '';
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 'Back to goals
';
Admin::close();
return;
}
$cur = Format::currency( $g['currency'] );
$rules = Store::rules( $goalId );
Admin::open( 'Rules for "' . (string) $g['title'] . '"' );
echo '← Back to goals
';
echo '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.
';
$editId = Admin::get_int( 'rule' );
$editRule = $editId ? Store::rule( $editId, $goalId ) : null;
echo 'Current rules ';
if ( ! $rules ) {
echo '
No rules yet. The goal bar works without any rules.
';
} else {
echo '
Rule What it does Actions ';
foreach ( $rules as $r ) {
$rid = (int) $r['id'];
echo '' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' (off) ' ) . ' ';
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 '' . esc_html( $summary ) . ' ';
echo 'Edit ';
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . ' ';
Admin::form( 'sg_rule_delete', array( 'goal_id' => $goalId, 'rule_id' => $rid ), 'sg-inline sg-confirm' );
echo 'Delete ';
}
echo '
';
}
echo '
';
// 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 'What would a donation do? Donation amount (' . esc_html( $cur ) . ') ';
echo '
';
echo '
Based on your enabled rules, for a single donation on its own. Carry-over from earlier donations and total limits are not included.
';
echo '
';
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 'The amount the donor chose (recommended) The amount including covered fees ';
};
echo '';
}
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.' );
}
}