From 5ea1e1d27371941587130d23f09118d80bd1b914 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 15 Nov 2026 12:53:07 -0800 Subject: [PATCH] End-at-target goals (auto-close when target reached) and fit-to-window rewards menu overlay - Core\GoalTargetPolicy; atomic close in the capture path; friendly 'goal reached' message - In-flight checkouts still capture; new orders for a closed goal are refused - Rewards menu overlay: card hugs content, text scales to the window, resize-aware, scroll only as a last resort Co-Authored-By: Claude Sonnet 5.5 --- assets/overlay/overlay.css | 4 +- assets/overlay/overlay.js | 52 +++++++++++++---- includes/Admin/GoalsPage.php | 5 +- includes/Core/GoalRepository.php | 23 +++++++- includes/Core/GoalTargetPolicy.php | 34 ++++++++++++ includes/PayPal/DonationStore.php | 22 ++++++++ includes/PayPal/OrderValidator.php | 3 + includes/Rest/DonateController.php | 6 ++ tests/Unit/GoalTargetPolicyTest.php | 86 +++++++++++++++++++++++++++++ 9 files changed, 216 insertions(+), 19 deletions(-) create mode 100644 includes/Core/GoalTargetPolicy.php create mode 100644 tests/Unit/GoalTargetPolicyTest.php diff --git a/assets/overlay/overlay.css b/assets/overlay/overlay.css index f96c25b..24e7f94 100644 --- a/assets/overlay/overlay.css +++ b/assets/overlay/overlay.css @@ -38,8 +38,8 @@ body.sg-offline #sg-root{opacity:.6} @media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}} .sg-w-actions #sg-root{align-items:flex-start} .sg-w-actions #sg-root:empty{display:none} -.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden} -.sg-menu-view{flex:1;min-height:0;overflow:hidden} +.sg-menu{height:auto;display:flex;flex-direction:column;overflow:hidden;font-size:calc(1em * var(--sg-menu-scale,1))} +.sg-menu-view{flex:none;min-height:0;overflow:hidden} .sg-menu-list{list-style:none;margin:0;padding:0} .sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere} .sg-menu-item b{color:var(--sg-accent2);font-weight:800} diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index 72c93e4..bd87960 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -146,14 +146,50 @@ } // ---- actions (reward menu) ---- - // Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration). - var actionsSig = null; + // Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the + // LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and + // re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll. + var actionsSig = null, menuEls = null, fitTimer = 0; + var MENU_MIN = 0.5, MENU_MAX = 1.8; + function fitMenu() { + if (!menuEls) return; + var card = menuEls.card, view = menuEls.view, track = menuEls.track, ul = menuEls.ul; + // reset any previous scroll fallback + track.classList.remove('sg-scrolling'); + while (track.children.length > 1) track.removeChild(track.lastChild); + view.style.height = ''; + var cs = getComputedStyle(root); + var inner = root.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom); + if (inner <= 0) return; + function fits(scale) { + card.style.setProperty('--sg-menu-scale', String(scale)); + return card.offsetHeight <= inner; + } + var lo = MENU_MIN, hi = MENU_MAX, best = null; + if (fits(hi)) { best = hi; } + else if (!fits(lo)) { best = null; } + else { for (var i = 0; i < 9; i++) { var mid = (lo + hi) / 2; if (fits(mid)) { lo = mid; } else { hi = mid; } } best = lo; } + if (best !== null) { card.style.setProperty('--sg-menu-scale', String(best)); return; } + // Even the smallest size overflows: use the smallest and scroll gently inside the window. + card.style.setProperty('--sg-menu-scale', String(MENU_MIN)); + var chrome = card.offsetHeight - view.offsetHeight; + view.style.height = Math.max(40, inner - chrome) + 'px'; + var dup = ul.cloneNode(true); + dup.setAttribute('aria-hidden', 'true'); + track.appendChild(dup); + track.style.setProperty('--sg-scroll-s', Math.max(8, menuEls.count * 3) + 's'); + track.classList.add('sg-scrolling'); + } + function scheduleFit() { clearTimeout(fitTimer); fitTimer = setTimeout(fitMenu, 120); } + window.addEventListener('resize', scheduleFit); + if (typeof ResizeObserver === 'function') { try { new ResizeObserver(scheduleFit).observe(document.documentElement); } catch (e) { /* resize event is the fallback */ } } function renderActions(d) { var list = Array.isArray(d.actions) ? d.actions : []; var sig = JSON.stringify(list); if (sig === actionsSig) return; actionsSig = sig; root.textContent = ''; + menuEls = null; if (!d.active || !list.length) return; var card = el('div', 'sg-card sg-menu'); var view = el('div', 'sg-menu-view'); @@ -171,16 +207,8 @@ view.appendChild(track); card.appendChild(view); root.appendChild(card); - // Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll. - requestAnimationFrame(function () { - if (ul.scrollHeight > view.clientHeight + 2) { - var dup = ul.cloneNode(true); - dup.setAttribute('aria-hidden', 'true'); - track.appendChild(dup); - track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's'); - track.classList.add('sg-scrolling'); - } - }); + menuEls = { card: card, view: view, track: track, ul: ul, count: list.length }; + requestAnimationFrame(fitMenu); } // ---- polling ---- diff --git a/includes/Admin/GoalsPage.php b/includes/Admin/GoalsPage.php index fb415fd..f9ea020 100644 --- a/includes/Admin/GoalsPage.php +++ b/includes/Admin/GoalsPage.php @@ -43,7 +43,7 @@ final class GoalsPage { $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 . '%)
'; + 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 '; @@ -90,6 +90,7 @@ final class GoalsPage { echo ' Optional. Your site time zone. Empty = starts immediately.'; echo ' Optional. Donations stop after this time.'; echo 'Fees

Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.

'; + echo 'End at target

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 "Reopen" (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).

'; echo '

Cancel

'; Admin::close(); } @@ -131,7 +132,7 @@ final class GoalsPage { 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 ); + $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 ( $id ) { Store::goals()->update( $id, $data ); } else { diff --git a/includes/Core/GoalRepository.php b/includes/Core/GoalRepository.php index e93d036..32dc2b6 100644 --- a/includes/Core/GoalRepository.php +++ b/includes/Core/GoalRepository.php @@ -6,7 +6,7 @@ namespace StreamGoals\Core; /** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */ final class GoalRepository { - private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' ); + private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d', 'close_at_target' => '%d' ); private \wpdb $db; @@ -21,7 +21,7 @@ final class GoalRepository { /** @return int new goal id */ public function create( array $data ): int { $row = array_intersect_key( $data, self::FIELDS ); - $row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 ); + $row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0, 'close_at_target' => 0 ); $row['created_at'] = gmdate( 'Y-m-d H:i:s' ); $this->db->insert( $this->table(), $row ); return (int) $this->db->insert_id; @@ -62,9 +62,26 @@ final class GoalRepository { if ( ! $goal ) { return 0; } - $col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input + $col = GoalTargetPolicy::amountColumn( $goal ); // whitelisted, not user input $d = $this->db->prefix . 'sg_donations'; $sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) ); return (int) $sum; } + + /** + * "End at target": if the goal is active, flagged close_at_target and its raised total has reached the + * target, set it to 'complete'. The UPDATE is conditional on status = 'active', so concurrent callers + * change it once. Idempotent and cheap (one SELECT for non-flagged goals). Returns true if THIS call closed it. + */ + public function closeIfTargetReached( int $goalId ): bool { + $goal = $this->find( $goalId ); + if ( ! $goal || empty( $goal['close_at_target'] ) || 'active' !== $goal['status'] ) { + return false; + } + if ( ! GoalTargetPolicy::shouldClose( $goal, $this->raised_minor( $goalId ) ) ) { + return false; + } + $n = $this->db->query( $this->db->prepare( "UPDATE {$this->table()} SET status = 'complete' WHERE id = %d AND status = 'active' AND close_at_target = 1", $goalId ) ); + return 1 === $n; + } } diff --git a/includes/Core/GoalTargetPolicy.php b/includes/Core/GoalTargetPolicy.php new file mode 100644 index 0000000..7536db6 --- /dev/null +++ b/includes/Core/GoalTargetPolicy.php @@ -0,0 +1,34 @@ + 0 + && $raisedMinor >= (int) $goal['target_minor']; + } + + /** True for a goal that is closed to donors because it reached its target (flag on + complete). */ + public static function isClosedAtTarget( array $goal ): bool { + return ! empty( $goal['close_at_target'] ) && 'complete' === ( $goal['status'] ?? '' ); + } + + /** Checkbox value from a raw form field: 1 when ticked, else 0. */ + public static function flagFromPost( mixed $raw ): int { + if ( is_array( $raw ) || null === $raw ) { + return 0; + } + return in_array( strtolower( trim( (string) $raw ) ), array( '1', 'on', 'true', 'yes' ), true ) ? 1 : 0; + } +} diff --git a/includes/PayPal/DonationStore.php b/includes/PayPal/DonationStore.php index 68f2299..dea7dbe 100644 --- a/includes/PayPal/DonationStore.php +++ b/includes/PayPal/DonationStore.php @@ -93,6 +93,28 @@ final class DonationStore { } catch ( \Throwable $e ) { error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions } + self::close_goal_if_target_reached( $id ); + } + + /** + * "End at target": runs after the donation is already completed and counted, so it can never refuse or + * undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active'). + */ + public static function close_goal_if_target_reached( int $donationId ): void { + try { + $row = self::find( $donationId ); + if ( $row && (int) $row->goal_id > 0 ) { + ( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id ); + } + } catch ( \Throwable $e ) { + error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions + } + } + + /** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */ + public static function reached_goals(): array { + global $wpdb; + return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A ); } private static function call_engine( string $method, int $id ): void { diff --git a/includes/PayPal/OrderValidator.php b/includes/PayPal/OrderValidator.php index dd2440a..0b224c4 100644 --- a/includes/PayPal/OrderValidator.php +++ b/includes/PayPal/OrderValidator.php @@ -84,6 +84,9 @@ final class OrderValidator { * @throws ValidationException */ public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array { + if ( 'complete' === ( $goal['status'] ?? '' ) ) { + throw new ValidationException( 'goal_inactive', 'This goal is closed and no longer accepting donations. Thank you for your support!', 409 ); + } if ( ! self::goalIsOpen( $goal, $nowTs ) ) { throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 ); } diff --git a/includes/Rest/DonateController.php b/includes/Rest/DonateController.php index c714035..d831878 100644 --- a/includes/Rest/DonateController.php +++ b/includes/Rest/DonateController.php @@ -3,6 +3,7 @@ declare( strict_types=1 ); namespace StreamGoals\Rest; +use StreamGoals\Core\GoalTargetPolicy; use StreamGoals\Core\Money; use StreamGoals\Core\Settings; use StreamGoals\PayPal\CaptureFinalizer; @@ -170,6 +171,11 @@ final class DonateController { ); } if ( ! $goals ) { + $reached = $pinned ? DonationStore::goal( $pinned ) : null; + $reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals(); + if ( $reached ) { + return '

' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '

'; + } return '

' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '

'; } diff --git a/tests/Unit/GoalTargetPolicyTest.php b/tests/Unit/GoalTargetPolicyTest.php new file mode 100644 index 0000000..e23bab5 --- /dev/null +++ b/tests/Unit/GoalTargetPolicyTest.php @@ -0,0 +1,86 @@ + 3, 'currency' => 'USD', 'status' => 'active', 'target_minor' => 10000, 'close_at_target' => 1, 'counts_fees' => 0, 'starts_at' => null, 'ends_at' => null ), $o ); + } + + public function test_below_equal_and_over_target(): void { + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal(), 9999 ) ); + $this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 10000 ) ); + $this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 25000 ) ); + } + + public function test_flag_off_or_missing_never_closes(): void { + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'close_at_target' => 0 ) ), 99999 ) ); + $g = $this->goal(); + unset( $g['close_at_target'] ); + $this->assertFalse( GoalTargetPolicy::shouldClose( $g, 99999 ) ); + } + + public function test_only_active_goals_are_closed(): void { + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'complete' ) ), 20000 ) ); + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'paused' ) ), 20000 ) ); + } + + public function test_target_zero_never_closes(): void { + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 0 ) ); + $this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 500 ) ); + } + + public function test_base_vs_total_basis(): void { + $this->assertSame( 'base_minor', GoalTargetPolicy::amountColumn( $this->goal() ) ); + $this->assertSame( 'total_minor', GoalTargetPolicy::amountColumn( $this->goal( array( 'counts_fees' => 1 ) ) ) ); + } + + public function test_closed_at_target_detection_and_pause_is_not_closed(): void { + $this->assertTrue( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete' ) ) ) ); + $this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'paused' ) ) ) ); + $this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete', 'close_at_target' => 0 ) ) ) ); + } + + public function test_checkbox_parsing(): void { + $this->assertSame( 1, GoalTargetPolicy::flagFromPost( '1' ) ); + $this->assertSame( 1, GoalTargetPolicy::flagFromPost( 'on' ) ); + $this->assertSame( 0, GoalTargetPolicy::flagFromPost( null ) ); + $this->assertSame( 0, GoalTargetPolicy::flagFromPost( '' ) ); + $this->assertSame( 0, GoalTargetPolicy::flagFromPost( '0' ) ); + $this->assertSame( 0, GoalTargetPolicy::flagFromPost( array( '1' ) ) ); + } + + public function test_new_orders_for_a_closed_goal_get_a_friendly_409(): void { + try { + OrderValidator::validate( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'complete' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 ); + $this->fail( 'expected refusal' ); + } catch ( ValidationException $e ) { + $this->assertSame( 'goal_inactive', $e->errorCode ); + $this->assertSame( 409, $e->status ); + $this->assertStringContainsString( 'Thank you', $e->getMessage() ); + } + } + + public function test_paused_goal_keeps_generic_message(): void { + try { + OrderValidator::quote( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'paused' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 ); + $this->fail( 'expected refusal' ); + } catch ( ValidationException $e ) { + $this->assertSame( 'This goal is not accepting donations.', $e->getMessage() ); + } + } + + public function test_goal_open_for_active_flagged_goal(): void { + $this->assertTrue( OrderValidator::goalIsOpen( $this->goal(), 1800000000 ) ); + $this->assertFalse( OrderValidator::goalIsOpen( $this->goal( array( 'status' => 'complete' ) ), 1800000000 ) ); + } +}