Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 fa4feddd35 Fix info tip closing itself when a hover precedes the click
Test and Release / test (push) Successful in 1m13s
Test and Release / release (push) Successful in 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 10:45:52 -08:00
shadowdaoandClaude Sonnet 5.5 e22675f54b Donate form: custom-amount label, visible minimum, fee-cover info icon; hard 1.00 floor; purge abandoned checkouts; drop refund filters; soften personal-account wording
Test and Release / test (push) Successful in 3m9s
Test and Release / release (push) Successful in 8s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 10:41:29 -08:00
13 changed files with 178 additions and 15 deletions

No files matched your search

+6
View File
@@ -11,3 +11,9 @@
.sg-donate .sg-msg.sg-error{color:#b32d2e}
.sg-donate .sg-msg.sg-ok{color:#1a7f37}
.sg-donate .sg-buttons[data-disabled=true]{opacity:.45;pointer-events:none}
.sg-donate label.sg-sub{font-weight:400;margin:.2rem 0 .25rem}
.sg-donate .sg-hint{font-size:.85em;opacity:.75;margin-top:.25rem}
.sg-donate .sg-cover{display:flex;align-items:center;gap:.5rem}
.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px}
.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4}
+28 -6
View File
@@ -54,10 +54,12 @@
try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: cur }).format(v); }
catch (e) { return v.toFixed(exp) + ' ' + cur; }
}
// Preset buttons, minus any below the minimum donation (values are whole currency units, or minor units for zero-decimal).
function presets(exp) {
var base = exp === 0 ? [500, 1000, 2500, 5000] : [5, 10, 25, 50];
return base;
return base.filter(function (p) { return (exp === 0 ? p : p * 100) >= (C.minMinor || 0); });
}
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
function init(root) {
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
@@ -68,7 +70,8 @@
var goalSel = el('select', { id: uid + '-goal' });
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', 'aria-describedby': uid + '-total' });
var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', placeholder: T.customPlaceholder || 'Other amount', 'aria-describedby': uid + '-hint ' + uid + '-total' });
var hint = el('div', { 'class': 'sg-hint', id: uid + '-hint' });
var presetBox = el('div', { 'class': 'sg-presets' });
var name = el('input', { type: 'text', id: uid + '-name', maxlength: '100', autocomplete: 'nickname' });
var anon = el('input', { type: 'checkbox', id: uid + '-anon' });
@@ -79,7 +82,7 @@
var buttons = el('div', { 'class': 'sg-buttons' });
if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); }
root.appendChild(row([el('label', { 'for': uid + '-amt', text: T.amount }), presetBox, amount]));
root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint]));
var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]);
var anonRow = row([el('label', { 'class': 'sg-inline', 'for': uid + '-anon' }, [anon, document.createTextNode(T.anonymous)])]);
if (C.policy === 'force_anonymous') { anon.checked = true; anon.disabled = true; nameRow.hidden = true; }
@@ -87,7 +90,21 @@
root.appendChild(nameRow);
root.appendChild(anonRow);
root.appendChild(row([el('label', { 'for': uid + '-msg', text: T.message }), msg]));
root.appendChild(row([el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)])]));
var tip = el('div', { 'class': 'sg-tip', id: uid + '-tip', role: 'note', text: T.coverInfo || '' });
tip.hidden = true;
var info = el('button', { type: 'button', 'class': 'sg-info', 'aria-label': T.coverInfoLabel || 'What does this mean?', 'aria-expanded': 'false', 'aria-controls': uid + '-tip', text: 'i' });
var pinnedOpen = false;
function showTip(open) { tip.hidden = !open; info.setAttribute('aria-expanded', String(open)); }
// Click toggles a "pinned" state independent of hover (a tap fires hover first, so reading tip.hidden would undo itself).
info.addEventListener('click', function () { pinnedOpen = !pinnedOpen; showTip(pinnedOpen); });
info.addEventListener('mouseenter', function () { showTip(true); });
info.addEventListener('mouseleave', function () { if (!pinnedOpen) { showTip(false); } });
info.addEventListener('blur', function () { pinnedOpen = false; showTip(false); });
info.addEventListener('keydown', function (e) { if (e.key === 'Escape') { pinnedOpen = false; showTip(false); } });
root.appendChild(row([
el('div', { 'class': 'sg-cover' }, [el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)]), info]),
tip
]));
root.appendChild(row([total]));
root.appendChild(buttons);
root.appendChild(status);
@@ -99,6 +116,7 @@
function buildPresets() {
presetBox.textContent = '';
hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency));
presets(state.goal.exp).forEach(function (p) {
var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) });
b.addEventListener('click', function () { amount.value = String(p); refresh(); });
@@ -119,7 +137,11 @@
state.quote = null;
buttons.setAttribute('data-disabled', 'true');
clearTimeout(timer);
if (!amountStr()) { total.textContent = ''; return; }
if (!amountStr()) { total.textContent = ''; say(''); return; }
var typed = parseFloat(amountStr());
if (isFinite(typed) && Math.round(typed * Math.pow(10, state.goal.exp)) < (C.minMinor || 0)) {
total.textContent = ''; say(sprintf1(T.belowMin, fmt(C.minMinor, state.goal.exp, state.goal.currency)), 'sg-error'); return;
}
var mine = ++seq;
timer = setTimeout(function () {
var qs = 'goal_id=' + state.goal.id + '&amount=' + encodeURIComponent(amountStr()) + '&cover_fees=' + (cover.checked ? '1' : '0');
@@ -149,7 +171,7 @@
if (token !== state.renderToken) { return; }
paypal.Buttons({
onClick: function (d, actions) {
if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { say(T.fixForm, 'sg-error'); return actions.reject(); }
if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { if (!status.textContent) { say(T.fixForm, 'sg-error'); } return actions.reject(); }
say('');
},
createOrder: function () {
+1 -1
View File
@@ -24,7 +24,7 @@ final class DonationsPage {
echo '<form method="get" class="sg-filter"><input type="hidden" name="page" value="streamgoals-donations">';
echo '<select name="status" aria-label="Status"><option value="">All statuses</option>';
foreach ( array( 'completed', 'pending', 'refunded', 'reversed' ) as $s ) {
foreach ( array( 'completed', 'pending' ) as $s ) {
echo '<option value="' . esc_attr( $s ) . '"' . selected( $status, $s, false ) . '>' . esc_html( ucfirst( $s ) ) . '</option>';
}
echo '</select> <label><input type="checkbox" name="tests" value="hide"' . checked( $tests, 'hide', false ) . '> Hide test donations</label> ';
+1 -1
View File
@@ -59,7 +59,7 @@ final class PayPalConnector {
public static function instructions(): void {
?>
<ol class="sg-steps">
<li>You need a <strong>PayPal Business</strong> account (free). A personal account cannot receive donations this way. <a href="https://www.paypal.com/business" target="_blank" rel="noopener noreferrer">Create one</a> or upgrade your existing account in PayPal settings.</li>
<li>To take <em>real</em> payments PayPal requires a <strong>PayPal Business</strong> account (free; your own name is fine). Practising in Sandbox needs no business account. <a href="https://www.paypal.com/business" target="_blank" rel="noopener noreferrer">Create one</a> or upgrade your existing account in PayPal settings.</li>
<li>Open <a href="https://developer.paypal.com/dashboard/applications" target="_blank" rel="noopener noreferrer">developer.paypal.com/dashboard/applications</a> and log in with that Business account.</li>
<li>At the top, pick <strong>Sandbox</strong> (to practise) or <strong>Live</strong> (real money) and click <strong>Create App</strong>.</li>
<li>Give it any name (for example "My stream"), keep the type <strong>Merchant</strong>, and click <strong>Create App</strong>.</li>
+3 -3
View File
@@ -33,7 +33,7 @@ final class SettingsPage {
echo '<option value="' . esc_attr( $c ) . '"' . selected( $cur, $c, false ) . '>' . esc_html( $c . ' - ' . $name ) . '</option>';
}
echo '</select><p class="description">One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( (int) $s['min_donation_minor'], $cur ) ) . '"></td></tr>';
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), $cur ) ) . '"> <span class="description">At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.</span></td></tr>';
echo '<tr><th scope="row"><label for="sg_len">Longest message</label></th><td><input type="number" id="sg_len" name="message_max_length" min="0" max="500" class="small-text" value="' . (int) $s['message_max_length'] . '"> characters <span class="description">(0 to 500; 0 = no messages)</span></td></tr>';
echo '<tr><th scope="row">Names</th><td><fieldset>';
foreach ( self::POLICIES as $k => $l ) {
@@ -64,8 +64,8 @@ final class SettingsPage {
$upd = array();
$min = Input::amountToMinor( $post['min_donation'] ?? '', $cur );
if ( null === $min || $min < 1 ) {
$errors[] = 'Minimum donation must be an amount greater than zero.';
if ( null === $min || $min < \StreamGoals\Core\Settings::HARD_MIN_MINOR ) {
$errors[] = 'Minimum donation must be at least ' . Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) . '. PayPal\'s fixed fee makes smaller donations lose money.';
} else {
$upd['min_donation_minor'] = $min;
}
+1 -1
View File
@@ -107,7 +107,7 @@ final class Store {
$w = array( '1=1' );
$args = array();
$st = $f['status'] ?? '';
if ( in_array( $st, array( 'pending', 'completed', 'refunded', 'reversed' ), true ) ) {
if ( in_array( $st, array( 'pending', 'completed' ), true ) ) {
$w[] = 'status = %s';
$args[] = $st;
}
+41
View File
@@ -0,0 +1,41 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Daily housekeeping: removes checkouts that were started but never paid.
*
* Only rows that never received a PayPal capture id are purged, and only after a week, so a slow payment
* that PayPal finalizes later through the webhook is never discarded.
*/
final class Maintenance {
public const HOOK = 'sg_purge_abandoned';
public const MAX_AGE_DAYS = 7;
public static function register(): void {
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
if ( ! wp_next_scheduled( self::HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
}
}
public static function unschedule(): void {
wp_clear_scheduled_hook( self::HOOK );
}
/** @return int Number of rows removed. */
public static function purge_abandoned(): int {
global $wpdb;
$table = $wpdb->prefix . 'sg_donations';
$cutoff = gmdate( 'Y-m-d H:i:s', time() - self::MAX_AGE_DAYS * DAY_IN_SECONDS );
$n = $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$table} WHERE status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '') AND goal_id > 0 AND created_at < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$cutoff
)
);
return (int) $n;
}
}
+1
View File
@@ -18,6 +18,7 @@ final class Plugin {
public static function boot(): void {
Installer::maybe_upgrade();
Maintenance::register();
foreach ( self::MODULES as $module ) {
if ( class_exists( $module ) && method_exists( $module, 'register' ) ) {
$module::register();
+11
View File
@@ -8,6 +8,17 @@ namespace StreamGoals\Core;
*/
final class Settings {
/**
* Absolute minimum donation in minor units (1.00 of the currency). PayPal's fixed per-transaction fee
* makes smaller donations a net loss for the streamer, so the configured minimum can never go below this.
*/
public const HARD_MIN_MINOR = 100;
/** The minimum that is actually enforced: the configured value, but never below the hard floor. */
public static function effectiveMin( int $configured ): int {
return max( self::HARD_MIN_MINOR, $configured );
}
public static function defaults(): array {
return array(
'paypal_mode' => 'sandbox', // sandbox | live
+2 -2
View File
@@ -94,9 +94,9 @@ final class OrderValidator {
} catch ( \InvalidArgumentException $e ) {
throw new ValidationException( 'invalid_amount', 'Please enter a valid amount.' );
}
$min = (int) ( $settings['min_donation_minor'] ?? 0 );
$min = \StreamGoals\Core\Settings::effectiveMin( (int) ( $settings['min_donation_minor'] ?? 0 ) );
if ( $base <= 0 || $base < $min ) {
throw new ValidationException( 'amount_too_small', 'The amount is below the minimum donation.' );
throw new ValidationException( 'amount_too_small', 'The minimum donation is ' . ( new Money( $min, $currency ) )->toDecimalString() . ' ' . $currency . '.' );
}
if ( $base > 99999999 ) { // sanity cap (~$999,999.99)
throw new ValidationException( 'amount_too_large', 'The amount is too large.' );
+9 -1
View File
@@ -177,7 +177,7 @@ final class DonateController {
'restUrl' => esc_url_raw( rest_url( self::NS ) ),
'clientId' => (string) $s['paypal_client_id'],
'policy' => (string) $s['anonymity_policy'],
'minMinor' => (int) $s['min_donation_minor'],
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
'messageMax' => min( 500, (int) $s['message_max_length'] ),
'goals' => $goals,
'i18n' => array(
@@ -193,6 +193,14 @@ final class DonateController {
'error' => __( 'Something went wrong. Please try again.', 'streamgoals-donate' ),
'sdkError' => __( 'Could not load PayPal.', 'streamgoals-donate' ),
'fixForm' => __( 'Please fix the form before paying.', 'streamgoals-donate' ),
'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ),
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
/* translators: %s: formatted minimum amount, e.g. $1.00 */
'belowMin' => __( 'The minimum donation is %s.', 'streamgoals-donate' ),
'coverInfoLabel' => __( 'What does this mean?', 'streamgoals-donate' ),
'coverInfo' => __( 'PayPal takes a small fee from every donation. Tick this box to add that fee to your total, so the full amount you chose reaches the streamer. It is optional.', 'streamgoals-donate' ),
),
);
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
+1
View File
@@ -31,4 +31,5 @@ spl_autoload_register(
);
register_activation_hook( __FILE__, array( \StreamGoals\Core\Installer::class, 'activate' ) );
register_deactivation_hook( __FILE__, array( \StreamGoals\Core\Maintenance::class, 'unschedule' ) );
add_action( 'plugins_loaded', array( \StreamGoals\Core\Plugin::class, 'boot' ) );
+73
View File
@@ -0,0 +1,73 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\FeeCalculator;
use StreamGoals\Core\Settings;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\PayPal\ValidationException;
final class MinimumDonationTest extends TestCase {
private const NOW = 1800000000;
private function quote( string $amount, int $configuredMin, string $currency = 'USD' ): array {
$goal = array( 'id' => 1, 'currency' => $currency, 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
$settings = array_merge( Settings::defaults(), array( 'min_donation_minor' => $configuredMin ) );
return OrderValidator::quote( array( 'amount' => $amount ), $goal, $settings, new FeeCalculator( 349, 49 ), self::NOW );
}
public function test_effective_min_never_below_hard_floor(): void {
$this->assertSame( 100, Settings::effectiveMin( 0 ) );
$this->assertSame( 100, Settings::effectiveMin( 1 ) );
$this->assertSame( 100, Settings::effectiveMin( 99 ) );
$this->assertSame( 500, Settings::effectiveMin( 500 ) );
}
public function test_configured_zero_or_tiny_minimum_still_enforces_floor(): void {
foreach ( array( 0, 1, 50 ) as $configured ) {
try {
$this->quote( '0.50', $configured );
$this->fail( "0.50 accepted with configured min $configured" );
} catch ( ValidationException $e ) {
$this->assertSame( 'amount_too_small', $e->errorCode );
}
}
}
public function test_exactly_the_floor_is_accepted(): void {
$this->assertSame( 100, $this->quote( '1.00', 0 )['base_minor'] );
$this->assertSame( 100, $this->quote( '1', 100 )['base_minor'] );
}
public function test_higher_configured_minimum_wins_and_error_names_it(): void {
$this->assertSame( 500, $this->quote( '5.00', 500 )['base_minor'] );
try {
$this->quote( '4.99', 500 );
$this->fail( 'expected rejection' );
} catch ( ValidationException $e ) {
$this->assertSame( 'amount_too_small', $e->errorCode );
$this->assertStringContainsString( '5.00 USD', $e->getMessage() );
}
}
public function test_zero_and_negative_rejected(): void {
foreach ( array( '0', '0.00', '-5' ) as $amt ) {
try {
$this->quote( $amt, 100 );
$this->fail( "amount '$amt' was accepted" );
} catch ( ValidationException $e ) {
$this->assertContains( $e->errorCode, array( 'amount_too_small', 'invalid_amount' ) );
}
}
}
public function test_fee_cover_does_not_change_the_floor_check(): void {
// The floor applies to the base amount the streamer receives, not the fee-inflated total.
$this->expectException( ValidationException::class );
$goal = array( 'id' => 1, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
OrderValidator::quote( array( 'amount' => '0.60', 'cover_fees' => true ), $goal, Settings::defaults(), new FeeCalculator( 349, 49 ), self::NOW );
}
}