Add admin UI: setup wizard, goals, rules editor, donations, moderation, overlays, settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b9e6e7cbb
commit
4efdef72f6
18 files changed
+2169
No files matched your search
@@ -0,0 +1,46 @@
|
||||
.sg-admin .sg-lead { font-size: 15px; max-width: 70ch; }
|
||||
.sg-admin .sg-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 6px; padding: 8px 20px 16px; margin: 16px 0; max-width: 960px; }
|
||||
.sg-admin .sg-card h2 { margin-top: 12px; }
|
||||
.sg-admin .sg-inline { display: inline-block; margin: 0 4px 4px 0; }
|
||||
.sg-admin .sg-ok { color: #00700f; font-weight: 600; }
|
||||
.sg-admin .sg-warn { color: #8a4b00; font-weight: 600; }
|
||||
.sg-admin .sg-steps { max-width: 80ch; line-height: 1.6; }
|
||||
.sg-admin .sg-steps li { margin-bottom: 6px; }
|
||||
.sg-admin .sg-progress { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; padding: 0; margin: 12px 0; counter-reset: sg; }
|
||||
.sg-admin .sg-progress li { counter-increment: sg; padding: 6px 14px; border-radius: 999px; background: #f0f0f1; color: #50575e; }
|
||||
.sg-admin .sg-progress li::before { content: counter(sg) ". "; }
|
||||
.sg-admin .sg-progress li.is-done { background: #d7f0dc; }
|
||||
.sg-admin .sg-progress li.is-current { background: #2271b1; color: #fff; font-weight: 600; }
|
||||
.sg-admin .sg-progress li.is-current a { color: #fff; }
|
||||
.sg-admin .sg-tabs { display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0 4px; }
|
||||
.sg-admin .sg-tab { border: 2px solid #c3c4c7; border-radius: 6px; padding: 8px 14px; cursor: pointer; background: #fff; }
|
||||
.sg-admin .sg-tab:has(input:checked) { border-color: #2271b1; background: #f0f6fc; }
|
||||
.sg-admin .sg-templates { display: grid; gap: 10px; margin: 10px 0; }
|
||||
.sg-admin .sg-template { border: 2px solid #c3c4c7; border-radius: 6px; padding: 10px 14px; cursor: pointer; display: block; }
|
||||
.sg-admin .sg-template:has(input:checked) { border-color: #2271b1; background: #f0f6fc; }
|
||||
.sg-admin .sg-template span { color: #50575e; margin-left: 24px; }
|
||||
.sg-admin .sg-copy { display: flex; gap: 8px; align-items: center; max-width: 720px; }
|
||||
.sg-admin .sg-copy input { flex: 1; min-width: 0; }
|
||||
.sg-admin .sg-overlay-card { border-top: 1px solid #dcdcde; padding: 4px 0 10px; }
|
||||
.sg-admin .sg-overlay-card:first-of-type { border-top: 0; }
|
||||
.sg-admin .sg-preview { overflow: auto; max-width: 100%; margin-top: 6px; border: 1px solid #c3c4c7; background: repeating-conic-gradient(#e6e6e6 0% 25%, #fafafa 0% 50%) 50% / 20px 20px; }
|
||||
.sg-admin .sg-preview iframe { border: 0; display: block; max-width: none; }
|
||||
.sg-admin .sg-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
|
||||
.sg-admin .sg-grid label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; }
|
||||
.sg-admin .sg-grid input[type="color"] { padding: 0; height: 32px; width: 64px; }
|
||||
.sg-admin .sg-table td, .sg-admin .sg-table th { vertical-align: top; }
|
||||
.sg-admin .sg-actions { white-space: normal; }
|
||||
.sg-admin .sg-badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; background: #f0f0f1; }
|
||||
.sg-admin .sg-active { background: #d7f0dc; }
|
||||
.sg-admin .sg-paused, .sg-admin .sg-pending { background: #fcf0c3; }
|
||||
.sg-admin .sg-complete { background: #dbe7f7; }
|
||||
.sg-admin .sg-test { background: #f4d6f5; font-weight: 700; }
|
||||
.sg-admin .sg-rejected { background: #f7d5d5; }
|
||||
.sg-admin .sg-bar { height: 6px; background: #e0e0e0; border-radius: 3px; margin-top: 4px; max-width: 180px; overflow: hidden; }
|
||||
.sg-admin .sg-bar span { display: block; height: 100%; background: #2271b1; }
|
||||
.sg-admin tr.sg-off td { opacity: .55; }
|
||||
.sg-admin .sg-preview-list { font-size: 14px; list-style: disc; margin-left: 20px; }
|
||||
.sg-admin .sg-form-preview { color: #00700f; font-weight: 600; min-height: 1.4em; }
|
||||
.sg-admin .sg-filter { display: inline-block; margin: 8px 8px 8px 0; }
|
||||
.sg-admin .sg-table { max-width: 100%; }
|
||||
@media (max-width: 782px) { .sg-admin .sg-copy { flex-direction: column; align-items: stretch; } }
|
||||
@@ -0,0 +1,59 @@
|
||||
/* StreamGoals admin: copy buttons and confirm prompts. No dependencies. */
|
||||
( function () {
|
||||
'use strict';
|
||||
|
||||
function flash( btn, text ) {
|
||||
var old = btn.getAttribute( 'data-label' ) || btn.textContent;
|
||||
btn.setAttribute( 'data-label', old );
|
||||
btn.textContent = text;
|
||||
window.setTimeout( function () { btn.textContent = old; }, 1500 );
|
||||
}
|
||||
|
||||
function copyText( text, btn, input ) {
|
||||
function fallback() {
|
||||
var el = input;
|
||||
var temp = null;
|
||||
if ( ! el ) {
|
||||
temp = el = document.createElement( 'textarea' );
|
||||
el.value = text;
|
||||
el.style.position = 'fixed';
|
||||
el.style.opacity = '0';
|
||||
document.body.appendChild( el );
|
||||
}
|
||||
el.select();
|
||||
var ok = false;
|
||||
try { ok = document.execCommand( 'copy' ); } catch ( e ) { ok = false; }
|
||||
if ( temp ) { document.body.removeChild( temp ); }
|
||||
flash( btn, ok ? 'Copied!' : 'Press Ctrl+C' );
|
||||
}
|
||||
if ( navigator.clipboard && window.isSecureContext ) {
|
||||
navigator.clipboard.writeText( text ).then( function () { flash( btn, 'Copied!' ); }, fallback );
|
||||
} else {
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener( 'click', function ( e ) {
|
||||
var btn = e.target.closest ? e.target.closest( '[data-sg-copy],[data-sg-copy-text]' ) : null;
|
||||
if ( ! btn ) { return; }
|
||||
e.preventDefault();
|
||||
if ( btn.hasAttribute( 'data-sg-copy-text' ) ) {
|
||||
copyText( btn.getAttribute( 'data-sg-copy-text' ), btn, null );
|
||||
return;
|
||||
}
|
||||
var input = btn.parentNode.querySelector( 'input' );
|
||||
if ( input ) { copyText( input.value, btn, input ); }
|
||||
} );
|
||||
|
||||
document.addEventListener( 'focusin', function ( e ) {
|
||||
if ( e.target.classList && e.target.classList.contains( 'sg-url' ) ) { e.target.select(); }
|
||||
} );
|
||||
|
||||
document.addEventListener( 'submit', function ( e ) {
|
||||
var form = e.target;
|
||||
if ( ! form.classList || ! form.classList.contains( 'sg-confirm' ) ) { return; }
|
||||
var src = e.submitter || form.querySelector( '[data-confirm]' );
|
||||
var msg = src && src.getAttribute( 'data-confirm' );
|
||||
if ( msg && ! window.confirm( msg ) ) { e.preventDefault(); }
|
||||
} );
|
||||
}() );
|
||||
@@ -0,0 +1,77 @@
|
||||
/* StreamGoals overlay style builder: keeps every overlay URL and preview in sync with the style form. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var form = document.getElementById( 'sg-style' );
|
||||
if ( ! form ) { return; }
|
||||
var cards = Array.prototype.slice.call( document.querySelectorAll( '.sg-overlay-card' ) );
|
||||
var COLORS = [ 'color', 'accent', 'accent2', 'track', 'bg' ];
|
||||
var timer = null;
|
||||
|
||||
function params() {
|
||||
var q = [];
|
||||
function add( k, v ) { q.push( encodeURIComponent( k ) + '=' + encodeURIComponent( v ) ); }
|
||||
var theme = form.elements.theme.value;
|
||||
if ( theme && theme !== 'dark' ) { add( 'theme', theme ); }
|
||||
var font = form.elements.font.value;
|
||||
var customBox = form.querySelector( '.sg-custom-font' );
|
||||
if ( font === '__custom' ) {
|
||||
var f = ( form.elements.font_custom.value || '' ).trim();
|
||||
if ( /^[A-Za-z0-9][A-Za-z0-9 \-]{0,39}$/.test( f ) ) { add( 'font', f ); }
|
||||
if ( customBox ) { customBox.hidden = false; }
|
||||
} else {
|
||||
if ( customBox ) { customBox.hidden = true; }
|
||||
if ( font && font !== 'sans' ) { add( 'font', font ); }
|
||||
}
|
||||
var scale = parseFloat( form.elements.scale.value );
|
||||
if ( isFinite( scale ) && scale >= 0.5 && scale <= 3 && scale !== 1 ) { add( 'scale', String( Math.round( scale * 100 ) / 100 ) ); }
|
||||
COLORS.forEach( function ( k ) {
|
||||
if ( form.elements[ 'use_' + k ].checked ) { add( k, form.elements[ k ].value.replace( '#', '' ) ); }
|
||||
} );
|
||||
return q.join( '&' );
|
||||
}
|
||||
|
||||
function previewSrc( card ) {
|
||||
var base = card.getAttribute( 'data-base' );
|
||||
var sep = card.getAttribute( 'data-sep' );
|
||||
var q = params();
|
||||
return q ? base + sep + q : base;
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
cards.forEach( function ( card ) {
|
||||
var url = previewSrc( card );
|
||||
var input = card.querySelector( '.sg-url' );
|
||||
if ( input ) { input.value = url; }
|
||||
var wrap = card.querySelector( '.sg-preview' );
|
||||
var frame = wrap && wrap.querySelector( 'iframe' );
|
||||
if ( frame && ! wrap.hidden ) { frame.src = url; }
|
||||
} );
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
window.clearTimeout( timer );
|
||||
timer = window.setTimeout( refresh, 250 );
|
||||
}
|
||||
|
||||
form.addEventListener( 'input', schedule );
|
||||
form.addEventListener( 'change', schedule );
|
||||
|
||||
cards.forEach( function ( card ) {
|
||||
var btn = card.querySelector( '[data-sg-preview]' );
|
||||
if ( ! btn ) { return; }
|
||||
btn.addEventListener( 'click', function () {
|
||||
var wrap = card.querySelector( '.sg-preview' );
|
||||
var frame = wrap.querySelector( 'iframe' );
|
||||
if ( wrap.hidden ) {
|
||||
wrap.hidden = false;
|
||||
frame.src = previewSrc( card );
|
||||
btn.textContent = 'Hide preview';
|
||||
} else {
|
||||
wrap.hidden = true;
|
||||
frame.removeAttribute( 'src' );
|
||||
btn.textContent = 'Show live preview';
|
||||
}
|
||||
} );
|
||||
} );
|
||||
refresh();
|
||||
}() );
|
||||
@@ -0,0 +1,122 @@
|
||||
/* StreamGoals rules editor: show the right fields per type and preview what a donation would do. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var dataEl = document.getElementById( 'sg-rules-data' );
|
||||
var form = document.querySelector( '.sg-rule-form' );
|
||||
var cfg = { currency: 'USD', exp: 2, rules: [] };
|
||||
try { if ( dataEl ) { cfg = JSON.parse( dataEl.textContent ); } } catch ( e ) { /* keep defaults */ }
|
||||
|
||||
/* Parse "1,000.50" into minor units using string maths only (no float rounding). Returns null if invalid. */
|
||||
function toMinor( raw ) {
|
||||
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
|
||||
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
|
||||
if ( ! m ) { return null; }
|
||||
var frac = m[ 2 ] || '';
|
||||
if ( frac.length > cfg.exp ) { return null; }
|
||||
while ( frac.length < cfg.exp ) { frac += '0'; }
|
||||
var n = parseInt( m[ 1 ] + frac, 10 );
|
||||
return isFinite( n ) ? n : null;
|
||||
}
|
||||
|
||||
function money( minor ) {
|
||||
var s = String( minor );
|
||||
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
|
||||
while ( s.length < 3 ) { s = '0' + s; }
|
||||
return cfg.currency + ' ' + s.slice( 0, -2 ) + '.' + s.slice( -2 );
|
||||
}
|
||||
|
||||
function duration( secs ) {
|
||||
var parts = [];
|
||||
[ [ 'day', 86400 ], [ 'hour', 3600 ], [ 'minute', 60 ], [ 'second', 1 ] ].forEach( function ( u ) {
|
||||
var n = Math.floor( secs / u[ 1 ] );
|
||||
secs -= n * u[ 1 ];
|
||||
if ( n > 0 ) { parts.push( n + ' ' + u[ 0 ] + ( n === 1 ? '' : 's' ) ); }
|
||||
} );
|
||||
return parts.length ? parts.join( ' ' ) : '0 seconds';
|
||||
}
|
||||
|
||||
/* Same maths as the PHP Rules classes (integer division, caps). */
|
||||
function effect( rule, amount ) {
|
||||
var c = rule.config || {};
|
||||
if ( rule.type === 'add_time' ) {
|
||||
if ( ! c.unit_minor ) { return null; }
|
||||
var d = Math.floor( amount * c.seconds_per_unit / c.unit_minor );
|
||||
if ( c.cap_seconds_per_donation != null ) { d = Math.min( d, c.cap_seconds_per_donation ); }
|
||||
return d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added';
|
||||
}
|
||||
if ( rule.type === 'counter' ) {
|
||||
if ( ! c.per_minor ) { return null; }
|
||||
return ( c.label || 'Counter' ) + ': +' + ( Math.floor( amount / c.per_minor ) * c.step );
|
||||
}
|
||||
if ( rule.type === 'bonus' ) {
|
||||
return 'Bonus "' + c.event + '" ' + ( amount >= c.min_minor ? 'triggers' : 'does not trigger' );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var amountEl = document.getElementById( 'sg-preview-amount' );
|
||||
var out = document.getElementById( 'sg-preview-out' );
|
||||
function renderPreview() {
|
||||
if ( ! amountEl || ! out ) { return; }
|
||||
var amt = toMinor( amountEl.value );
|
||||
out.textContent = '';
|
||||
var lines = [];
|
||||
if ( amt === null ) {
|
||||
lines.push( 'Enter an amount like 25.00' );
|
||||
} else {
|
||||
lines.push( 'A ' + money( amt ) + ' donation:' );
|
||||
cfg.rules.forEach( function ( r ) { var l = effect( r, amt ); if ( l ) { lines.push( l ); } } );
|
||||
if ( ! cfg.rules.length ) { lines.push( 'No rules are on, so it only fills the goal bar.' ); }
|
||||
}
|
||||
lines.forEach( function ( l ) { var li = document.createElement( 'li' ); li.textContent = l; out.appendChild( li ); } );
|
||||
}
|
||||
if ( amountEl ) { amountEl.addEventListener( 'input', renderPreview ); renderPreview(); }
|
||||
|
||||
/* Type switch + preview of the rule being edited. */
|
||||
if ( ! form ) { return; }
|
||||
var typeSel = document.getElementById( 'sg-rule-type' );
|
||||
var typeHidden = form.querySelector( 'input[name="type"]' );
|
||||
var formPrev = document.getElementById( 'sg-form-preview' );
|
||||
|
||||
function currentType() { return typeSel ? typeSel.value : ( typeHidden ? typeHidden.value : 'add_time' ); }
|
||||
function val( group, f ) {
|
||||
var el = group.querySelector( '[data-f="' + f + '"]' );
|
||||
if ( ! el ) { return ''; }
|
||||
return el.type === 'checkbox' ? el.checked : el.value;
|
||||
}
|
||||
function buildRule( type ) {
|
||||
var g = form.querySelector( '.sg-rule-group[data-type="' + type + '"]' );
|
||||
if ( ! g ) { return null; }
|
||||
var unit = toMinor( val( g, 'unit_amount' ) );
|
||||
if ( type === 'add_time' ) {
|
||||
var mult = { seconds: 1, minutes: 60, hours: 3600 }[ val( g, 'time_unit' ) ] || 60;
|
||||
var n = parseInt( val( g, 'time_amount' ), 10 );
|
||||
if ( ! unit || ! n ) { return null; }
|
||||
var cap = parseInt( val( g, 'cap_minutes' ), 10 );
|
||||
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null } };
|
||||
}
|
||||
if ( type === 'counter' ) {
|
||||
var step = parseInt( val( g, 'step' ), 10 );
|
||||
if ( ! unit || ! step ) { return null; }
|
||||
return { type: type, config: { step: step, per_minor: unit, label: val( g, 'label' ) } };
|
||||
}
|
||||
var min = toMinor( val( g, 'min_amount' ) );
|
||||
if ( ! min ) { return null; }
|
||||
return { type: type, config: { min_minor: min, event: val( g, 'event' ) || 'big_donation' } };
|
||||
}
|
||||
function update() {
|
||||
var type = currentType();
|
||||
Array.prototype.forEach.call( form.querySelectorAll( '.sg-rule-group' ), function ( g ) {
|
||||
g.hidden = g.getAttribute( 'data-type' ) !== type;
|
||||
} );
|
||||
if ( ! formPrev ) { return; }
|
||||
var amt = amountEl ? toMinor( amountEl.value ) : null;
|
||||
var rule = buildRule( type );
|
||||
var line = ( rule && amt !== null ) ? effect( rule, amt ) : null;
|
||||
formPrev.textContent = line ? 'With this rule, a ' + money( amt ) + ' donation gives: ' + line : '';
|
||||
}
|
||||
form.addEventListener( 'input', update );
|
||||
form.addEventListener( 'change', update );
|
||||
if ( amountEl ) { amountEl.addEventListener( 'input', update ); }
|
||||
update();
|
||||
}() );
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/**
|
||||
* Admin bootstrap: one top-level "StreamGoals" menu, assets, shared helpers (nonce/capability guard,
|
||||
* flash notices). Every screen requires manage_options; every admin-post handler goes through guard().
|
||||
*/
|
||||
final class Admin {
|
||||
|
||||
public const CAP = 'manage_options';
|
||||
public const HOME = 'streamgoals';
|
||||
|
||||
/** admin-post action => [class, method]. */
|
||||
private const HANDLERS = array(
|
||||
'sg_paypal_connect' => array( PayPalConnector::class, 'handle' ),
|
||||
'sg_wizard_goal' => array( SetupPage::class, 'handleGoal' ),
|
||||
'sg_wizard_page' => array( SetupPage::class, 'handlePage' ),
|
||||
'sg_goal_save' => array( GoalsPage::class, 'handleSave' ),
|
||||
'sg_goal_status' => array( GoalsPage::class, 'handleStatus' ),
|
||||
'sg_goal_delete' => array( GoalsPage::class, 'handleDelete' ),
|
||||
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
|
||||
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
|
||||
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
'sg_moderate' => array( DonationsPage::class, 'handleModerate' ),
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
|
||||
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
|
||||
'sg_settings_save' => array( SettingsPage::class, 'handleSave' ),
|
||||
);
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'admin_menu', array( self::class, 'menu' ) );
|
||||
add_action( 'admin_init', array( self::class, 'maybe_flush_rewrites' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( self::class, 'assets' ) );
|
||||
foreach ( self::HANDLERS as $action => $cb ) {
|
||||
add_action( 'admin_post_' . $action, $cb );
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ menu */
|
||||
|
||||
public static function menu(): void {
|
||||
$connected = PayPalConnector::isConnected();
|
||||
add_menu_page( 'StreamGoals', 'StreamGoals', self::CAP, self::HOME, array( self::class, 'page_home' ), 'dashicons-heart', 58 );
|
||||
add_submenu_page( self::HOME, $connected ? 'Goals' : 'Setup', $connected ? 'Goals' : 'Setup', self::CAP, self::HOME, array( self::class, 'page_home' ) );
|
||||
if ( $connected ) {
|
||||
add_submenu_page( self::HOME, 'Setup guide', 'Setup guide', self::CAP, 'streamgoals-setup', array( SetupPage::class, 'render' ) );
|
||||
}
|
||||
add_submenu_page( self::HOME, 'Donations', 'Donations', self::CAP, 'streamgoals-donations', array( DonationsPage::class, 'render' ) );
|
||||
$pending = Store::pendingModerationCount();
|
||||
if ( Settings::get( 'moderate_messages' ) || $pending > 0 ) {
|
||||
$badge = $pending > 0 ? ' <span class="awaiting-mod">' . (int) $pending . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) );
|
||||
}
|
||||
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
|
||||
}
|
||||
|
||||
/** First screen: the setup wizard until PayPal is connected, then the goals list. */
|
||||
public static function page_home(): void {
|
||||
if ( PayPalConnector::isConnected() ) {
|
||||
GoalsPage::render();
|
||||
} else {
|
||||
SetupPage::render();
|
||||
}
|
||||
}
|
||||
|
||||
/** Overlay rewrite rules (registered by Overlay\Router on init) need a one-off flush. */
|
||||
public static function maybe_flush_rewrites(): void {
|
||||
if ( current_user_can( self::CAP ) && class_exists( \StreamGoals\Overlay\Router::class ) && \StreamGoals\Overlay\Router::flush_rules_needed() ) {
|
||||
flush_rewrite_rules( false );
|
||||
\StreamGoals\Overlay\Router::mark_flushed();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- assets */
|
||||
|
||||
public static function assets( string $hook ): void {
|
||||
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
if ( 0 !== strpos( $page, 'streamgoals' ) ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_style( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.css', array(), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.js', array(), STREAMGOALS_VERSION, true );
|
||||
if ( self::HOME === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-rules', STREAMGOALS_URL . 'assets/admin/rules.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- helpers */
|
||||
|
||||
/** Capability + nonce check for every admin-post handler. Dies on failure. */
|
||||
public static function guard( string $action ): void {
|
||||
if ( ! current_user_can( self::CAP ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
check_admin_referer( $action );
|
||||
}
|
||||
|
||||
/** Echo an opening <form> posting to admin-post.php with the nonce for $action. */
|
||||
public static function form( string $action, array $hidden = array(), string $class = '' ): void {
|
||||
echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '"' . ( '' !== $class ? ' class="' . esc_attr( $class ) . '"' : '' ) . '>';
|
||||
echo '<input type="hidden" name="action" value="' . esc_attr( $action ) . '">';
|
||||
wp_nonce_field( $action );
|
||||
foreach ( $hidden as $k => $v ) {
|
||||
echo '<input type="hidden" name="' . esc_attr( (string) $k ) . '" value="' . esc_attr( (string) $v ) . '">';
|
||||
}
|
||||
}
|
||||
|
||||
public static function url( string $page = self::HOME, array $args = array() ): string {
|
||||
return add_query_arg( array_merge( array( 'page' => $page ), $args ), admin_url( 'admin.php' ) );
|
||||
}
|
||||
|
||||
/** Redirect back with a one-time notice shown on the next screen load. */
|
||||
public static function redirect( string $url, string $type, string $message ): void {
|
||||
set_transient( 'sg_notice_' . get_current_user_id(), array( 'type' => $type, 'msg' => $message ), 120 );
|
||||
wp_safe_redirect( $url );
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function notices(): void {
|
||||
$key = 'sg_notice_' . get_current_user_id();
|
||||
$n = get_transient( $key );
|
||||
if ( is_array( $n ) && isset( $n['msg'] ) ) {
|
||||
delete_transient( $key );
|
||||
$cls = in_array( $n['type'] ?? '', array( 'success', 'error', 'warning', 'info' ), true ) ? $n['type'] : 'info';
|
||||
echo '<div class="notice notice-' . esc_attr( $cls ) . ' is-dismissible"><p>' . esc_html( (string) $n['msg'] ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function currency(): string {
|
||||
return Format::currency( get_option( 'sg_currency', 'USD' ) );
|
||||
}
|
||||
|
||||
/** Start a screen: capability check, wrapper and flash notices. */
|
||||
public static function open( string $title ): void {
|
||||
if ( ! current_user_can( self::CAP ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to view this page.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
echo '<div class="wrap sg-admin"><h1>' . esc_html( $title ) . '</h1>';
|
||||
self::notices();
|
||||
if ( PayPalConnector::isConnected() && '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
|
||||
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so refunds/reversals will not be noticed. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function close(): void {
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/** Safe int from $_GET. */
|
||||
public static function get_int( string $key ): int {
|
||||
return isset( $_GET[ $key ] ) ? absint( wp_unslash( $_GET[ $key ] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
public static function get_str( string $key ): string {
|
||||
return isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] ) ? sanitize_key( wp_unslash( $_GET[ $key ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
/** Safe string from $_POST (already nonce-checked by guard()). */
|
||||
public static function post_str( string $key, int $max = 200 ): string {
|
||||
return isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ? Input::text( wp_unslash( $_POST[ $key ] ), $max ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
public static function post_raw(): array {
|
||||
return is_array( $_POST ) ? wp_unslash( $_POST ) : array(); // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
/** CSV helpers. Guards against spreadsheet formula injection (=, +, -, @, tab, CR prefixes). */
|
||||
final class Csv {
|
||||
|
||||
public static function cell( mixed $v ): string {
|
||||
$s = is_scalar( $v ) || null === $v ? (string) $v : '';
|
||||
if ( '' !== $s && str_contains( "=+-@\t\r", $s[0] ) ) {
|
||||
return "'" . $s;
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public static function row( array $cells ): array {
|
||||
return array_map( array( self::class, 'cell' ), array_values( $cells ) );
|
||||
}
|
||||
|
||||
/** Render one RFC-4180 line (no WordPress needed; used for tests and streaming). */
|
||||
public static function line( array $cells ): string {
|
||||
$out = array();
|
||||
foreach ( self::row( $cells ) as $c ) {
|
||||
$out[] = '"' . str_replace( '"', '""', $c ) . '"';
|
||||
}
|
||||
return implode( ',', $out ) . "\r\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** Donations table (search, filter, pagination), CSV export, and the message moderation queue. */
|
||||
final class DonationsPage {
|
||||
|
||||
private const PER_PAGE = 25;
|
||||
|
||||
private static function fmtDate( string $utc ): string {
|
||||
return get_date_from_gmt( $utc, 'Y-m-d H:i' );
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Donations' );
|
||||
$status = Admin::get_str( 'status' );
|
||||
$tests = 'hide' === Admin::get_str( 'tests' ) ? 'hide' : '';
|
||||
$search = isset( $_GET['s'] ) && is_scalar( $_GET['s'] ) ? Input::text( wp_unslash( $_GET['s'] ), 100 ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
$page = max( 1, Admin::get_int( 'paged' ) );
|
||||
$res = Store::searchDonations( array( 'status' => $status, 'search' => $search, 'tests' => $tests ), $page, self::PER_PAGE );
|
||||
|
||||
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 ) {
|
||||
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> ';
|
||||
echo '<input type="search" name="s" value="' . esc_attr( $search ) . '" placeholder="Search name, message or PayPal ID"> <button class="button">Filter</button> ';
|
||||
echo '</form>';
|
||||
Admin::form( 'sg_export_csv', array(), 'sg-inline' );
|
||||
echo '<button class="button">Export CSV (all real donations)</button></form>';
|
||||
|
||||
echo '<p class="description">Donors who chose to be anonymous are shown as "Anonymous". Their name is never stored. Test donations are marked TEST and left out of the CSV and your totals.</p>';
|
||||
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>No donations found.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$goals = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$goals[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Fee</th><th>Total paid</th><th>Goal</th><th>Status</th><th>Message</th></tr></thead><tbody>';
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
$test = Format::isTest( $r );
|
||||
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
|
||||
echo '<td>' . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
|
||||
echo '<td>' . esc_html( (string) $r['message'] ) . '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
$pages = (int) ceil( $res['total'] / self::PER_PAGE );
|
||||
if ( $pages > 1 ) {
|
||||
echo '<div class="tablenav"><div class="tablenav-pages">' . wp_kses_post( (string) paginate_links( array(
|
||||
'base' => add_query_arg( 'paged', '%#%' ),
|
||||
'format' => '',
|
||||
'current' => $page,
|
||||
'total' => $pages,
|
||||
'prev_text' => '«',
|
||||
'next_text' => '»',
|
||||
) ) ) . '</div></div>';
|
||||
}
|
||||
echo '<p class="description">' . (int) $res['total'] . ' donation(s).</p>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function renderModeration(): void {
|
||||
Admin::open( 'Message moderation' );
|
||||
if ( ! Settings::get( 'moderate_messages' ) ) {
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.</p></div>';
|
||||
}
|
||||
echo '<p class="description">Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.</p>';
|
||||
$res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 );
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>Nothing waiting for review.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Message</th><th>Decision</th></tr></thead><tbody>';
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td><td>' . esc_html( Format::donorName( $r ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( (string) $r['message'] ) . '</td><td class="sg-actions">';
|
||||
foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) {
|
||||
Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' );
|
||||
echo '<button class="button' . ( 'approved' === $to ? ' button-primary' : '' ) . '">' . esc_html( $lbl ) . '</button></form> ';
|
||||
}
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleModerate(): void {
|
||||
Admin::guard( 'sg_moderate' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
|
||||
$to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : '';
|
||||
$ok = $id && Store::setModeration( $id, $to );
|
||||
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' );
|
||||
}
|
||||
|
||||
public static function handleExport(): void {
|
||||
Admin::guard( 'sg_export_csv' );
|
||||
$goals = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$goals[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
nocache_headers();
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="streamgoals-donations-' . gmdate( 'Y-m-d' ) . '.csv"' );
|
||||
header( 'X-Content-Type-Options: nosniff' );
|
||||
echo "\xEF\xBB\xBF"; // UTF-8 BOM so Excel reads accents correctly
|
||||
echo Csv::line( array( 'ID', 'Date (UTC)', 'Goal', 'Donor', 'Amount', 'Fee covered', 'Total paid', 'Currency', 'Status', 'Message status', 'Message', 'PayPal order', 'PayPal capture' ) ); // phpcs:ignore WordPress.Security.EscapeOutput -- CSV, not HTML
|
||||
$after = 0;
|
||||
do {
|
||||
$rows = Store::exportBatch( $after, 500 );
|
||||
foreach ( $rows as $r ) {
|
||||
$after = (int) $r['id'];
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
echo Csv::line( array( // phpcs:ignore WordPress.Security.EscapeOutput
|
||||
$r['id'],
|
||||
$r['created_at'],
|
||||
$goals[ (int) $r['goal_id'] ] ?? '',
|
||||
Format::donorName( $r ),
|
||||
Format::decimal( (int) $r['base_minor'], $cur ),
|
||||
Format::decimal( (int) $r['fee_minor'], $cur ),
|
||||
Format::decimal( (int) $r['total_minor'], $cur ),
|
||||
$cur,
|
||||
$r['status'],
|
||||
$r['moderation'],
|
||||
$r['message'],
|
||||
$r['paypal_order_id'],
|
||||
$r['paypal_capture_id'],
|
||||
) );
|
||||
}
|
||||
} while ( count( $rows ) === 500 );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
|
||||
/** Pure display helpers. */
|
||||
final class Format {
|
||||
|
||||
/** Test donations are inserted with goal_id 0 and a paypal_order_id starting with this prefix. */
|
||||
public const TEST_PREFIX = 'TEST-';
|
||||
|
||||
/** PayPal-supported currencies (subset). */
|
||||
public const CURRENCIES = array(
|
||||
'USD' => 'US Dollar', 'EUR' => 'Euro', 'GBP' => 'British Pound', 'CAD' => 'Canadian Dollar', 'AUD' => 'Australian Dollar',
|
||||
'NZD' => 'New Zealand Dollar', 'CHF' => 'Swiss Franc', 'SEK' => 'Swedish Krona', 'NOK' => 'Norwegian Krone', 'DKK' => 'Danish Krone',
|
||||
'PLN' => 'Polish Zloty', 'CZK' => 'Czech Koruna', 'HUF' => 'Hungarian Forint', 'JPY' => 'Japanese Yen', 'SGD' => 'Singapore Dollar',
|
||||
'HKD' => 'Hong Kong Dollar', 'MXN' => 'Mexican Peso', 'BRL' => 'Brazilian Real', 'PHP' => 'Philippine Peso', 'TWD' => 'New Taiwan Dollar',
|
||||
'THB' => 'Thai Baht', 'ILS' => 'Israeli Shekel', 'MYR' => 'Malaysian Ringgit', 'CNY' => 'Chinese Yuan',
|
||||
);
|
||||
|
||||
public static function currency( mixed $c ): string {
|
||||
$c = is_string( $c ) ? strtoupper( trim( $c ) ) : '';
|
||||
return isset( self::CURRENCIES[ $c ] ) ? $c : 'USD';
|
||||
}
|
||||
|
||||
public static function money( int $minor, string $currency ): string {
|
||||
return Payloads::money( $minor, $currency );
|
||||
}
|
||||
|
||||
/** Plain decimal for form inputs, e.g. 1050 USD -> "10.50". */
|
||||
public static function decimal( int $minor, string $currency ): string {
|
||||
return ( new \StreamGoals\Core\Money( max( 0, $minor ), $currency ) )->toDecimalString();
|
||||
}
|
||||
|
||||
public static function duration( int $seconds ): string {
|
||||
$seconds = max( 0, $seconds );
|
||||
if ( 0 === $seconds ) {
|
||||
return '0 seconds';
|
||||
}
|
||||
$parts = array();
|
||||
foreach ( array( 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1 ) as $name => $size ) {
|
||||
$n = intdiv( $seconds, $size );
|
||||
$seconds %= $size;
|
||||
if ( $n > 0 ) {
|
||||
$parts[] = $n . ' ' . $name . ( 1 === $n ? '' : 's' );
|
||||
}
|
||||
}
|
||||
return implode( ' ', $parts );
|
||||
}
|
||||
|
||||
public static function isTest( array $row ): bool {
|
||||
return str_starts_with( (string) ( $row['paypal_order_id'] ?? '' ), self::TEST_PREFIX );
|
||||
}
|
||||
|
||||
/** The real name is shown only for non-anonymous donors. Anonymous names are not stored at all. */
|
||||
public static function donorName( array $row ): string {
|
||||
if ( ! empty( $row['is_anonymous'] ) || '' === trim( (string) ( $row['donor_name'] ?? '' ) ) ) {
|
||||
return 'Anonymous';
|
||||
}
|
||||
return (string) $row['donor_name'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** 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 );
|
||||
} 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();
|
||||
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 '<table class="widefat striped sg-table"><thead><tr><th>Goal</th><th>Status</th><th>Raised</th><th>Dates</th><th>Actions</th></tr></thead><tbody>';
|
||||
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><td><strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' · <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
|
||||
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div></td>';
|
||||
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="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> ';
|
||||
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 '</tbody></table>';
|
||||
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();
|
||||
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>';
|
||||
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 '</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 );
|
||||
if ( '' === $title ) {
|
||||
Admin::redirect( $back, 'error', 'Please give the goal a title.' );
|
||||
}
|
||||
if ( 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 );
|
||||
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.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- 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() ) . '">← 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 '<table class="widefat striped sg-table"><thead><tr><th>Rule</th><th>What it does</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $rules as $r ) {
|
||||
$rid = (int) $r['id'];
|
||||
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
|
||||
echo '<td>' . esc_html( RuleConfig::summary( (string) $r['type'], $r['config'], $cur ) ) . '</td><td class="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 '</tbody></table>';
|
||||
}
|
||||
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'] ?? '' ) !== '' ) ) ? ' 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>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.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** Pure (WordPress-free) input parsing/sanitizing helpers for the admin screens. */
|
||||
final class Input {
|
||||
|
||||
/** Parse "$1,000.50" / "10" / "10.5" into minor units, or null when invalid. */
|
||||
public static function amountToMinor( mixed $raw, string $currency ): ?int {
|
||||
if ( ! is_scalar( $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$s = str_replace( array( ',', ' ', "\u{00A0}" ), '', trim( (string) $raw ) );
|
||||
$s = ltrim( $s, '$€£¥' );
|
||||
if ( '' === $s ) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$minor = Money::fromDecimalString( $s, $currency )->minor;
|
||||
} catch ( \InvalidArgumentException ) {
|
||||
return null;
|
||||
}
|
||||
return $minor > 99999999999 ? null : $minor;
|
||||
}
|
||||
|
||||
/** "3.49" (percent) -> 349 basis points; null when invalid or outside 0..30%. */
|
||||
public static function percentToBps( mixed $raw ): ?int {
|
||||
if ( ! is_scalar( $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$s = rtrim( trim( str_replace( ',', '.', (string) $raw ) ), '%' );
|
||||
if ( ! preg_match( '/^\d{1,2}(\.\d{1,2})?$/', $s ) ) {
|
||||
return null;
|
||||
}
|
||||
[ $w, $f ] = array_pad( explode( '.', $s, 2 ), 2, '' );
|
||||
$bps = (int) $w * 100 + (int) str_pad( $f, 2, '0' );
|
||||
return $bps <= 3000 ? $bps : null;
|
||||
}
|
||||
|
||||
/** Whole number within [min,max], else null. Empty string -> null. */
|
||||
public static function int( mixed $raw, int $min, int $max ): ?int {
|
||||
if ( ! is_scalar( $raw ) || ! preg_match( '/^\s*\d{1,12}\s*$/', (string) $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$n = (int) trim( (string) $raw );
|
||||
return ( $n >= $min && $n <= $max ) ? $n : null;
|
||||
}
|
||||
|
||||
/** Normalise a "one word per line" textarea: trimmed, lowercase, deduplicated, bounded. */
|
||||
public static function words( string $text ): string {
|
||||
$out = array();
|
||||
foreach ( preg_split( '/\r\n|\r|\n|,/', $text ) ?: array() as $w ) {
|
||||
$w = preg_replace( '/[\x00-\x1F\x7F<>]/u', '', trim( $w ) ) ?? '';
|
||||
$w = function_exists( 'mb_strtolower' ) ? mb_strtolower( $w ) : strtolower( $w );
|
||||
if ( '' === $w || ( function_exists( 'mb_strlen' ) ? mb_strlen( $w ) : strlen( $w ) ) > 40 ) {
|
||||
continue;
|
||||
}
|
||||
$out[ $w ] = true;
|
||||
if ( count( $out ) >= 500 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return implode( "\n", array_keys( $out ) );
|
||||
}
|
||||
|
||||
/** Event name slug: [a-z0-9_-], max 40, falling back to $default. */
|
||||
public static function slug( mixed $raw, string $default = 'big_donation' ): string {
|
||||
$s = is_scalar( $raw ) ? strtolower( trim( (string) $raw ) ) : '';
|
||||
$s = preg_replace( '/[^a-z0-9_-]+/', '_', $s ) ?? '';
|
||||
$s = substr( trim( $s, '_-' ), 0, 40 );
|
||||
return '' === $s ? $default : $s;
|
||||
}
|
||||
|
||||
/** Plain single-line text with control chars and tags removed, bounded in length. */
|
||||
public static function text( mixed $raw, int $max ): string {
|
||||
$s = is_scalar( $raw ) ? strip_tags( (string) $raw ) : '';
|
||||
$s = preg_replace( '/[\x00-\x1F\x7F]/u', '', $s ) ?? '';
|
||||
$s = trim( $s );
|
||||
return function_exists( 'mb_substr' ) ? mb_substr( $s, 0, $max ) : substr( $s, 0, $max );
|
||||
}
|
||||
|
||||
/** Mask for showing that a secret exists without revealing it. */
|
||||
public static function maskSecret( string $secret ): string {
|
||||
return '' === $secret ? '' : str_repeat( "\u{2022}", 12 );
|
||||
}
|
||||
|
||||
/** True when the submitted value is the untouched placeholder or empty (=> keep the stored secret). */
|
||||
public static function secretUnchanged( string $submitted ): bool {
|
||||
$t = trim( $submitted );
|
||||
return '' === $t || 1 === preg_match( '/^[\x{2022}*]+$/u', $t );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Style;
|
||||
use StreamGoals\Rest\OverlayController;
|
||||
|
||||
/** Overlay URLs, style builder, live preview, token regeneration, and test donations. */
|
||||
final class OverlaysPage {
|
||||
|
||||
public const WIDGETS = array(
|
||||
'goal' => array( 'Goal bar', 800, 120, 'Progress bar towards your active goal.' ),
|
||||
'timer' => array( 'Subathon timer', 400, 120, 'Countdown that grows with donations (needs an "Add time" rule).' ),
|
||||
'counter' => array( 'Counter', 400, 120, 'A running count (needs a "Counter" rule).' ),
|
||||
'alerts' => array( 'Donation alerts', 600, 300, 'Pop-up alert for each new donation.' ),
|
||||
);
|
||||
|
||||
/** @return array{url:string,base:string,sep:string} */
|
||||
public static function widgetUrl( string $widget ): array {
|
||||
$token = OverlayController::token();
|
||||
if ( get_option( 'permalink_structure' ) ) {
|
||||
$base = home_url( '/streamgoals-overlay/' . rawurlencode( $token ) . '/' . rawurlencode( $widget ) . '/' );
|
||||
return array( 'url' => $base, 'base' => $base, 'sep' => '?' );
|
||||
}
|
||||
$base = add_query_arg( array( 'sg_overlay_token' => $token, 'sg_overlay_widget' => $widget ), home_url( '/' ) );
|
||||
return array( 'url' => $base, 'base' => $base, 'sep' => '&' );
|
||||
}
|
||||
|
||||
/** Used by the wizard and this screen: one copy-able link per widget. */
|
||||
public static function urlList( bool $withPreview = false ): void {
|
||||
foreach ( self::WIDGETS as $w => [ $label, $width, $height, $desc ] ) {
|
||||
$u = self::widgetUrl( $w );
|
||||
echo '<div class="sg-overlay-card" data-widget="' . esc_attr( $w ) . '" data-base="' . esc_attr( $u['base'] ) . '" data-sep="' . esc_attr( $u['sep'] ) . '" data-w="' . (int) $width . '" data-h="' . (int) $height . '">';
|
||||
echo '<h3>' . esc_html( $label ) . '</h3><p class="description">' . esc_html( $desc ) . ' OBS size: <strong>' . (int) $width . ' x ' . (int) $height . '</strong></p>';
|
||||
echo '<div class="sg-copy"><input type="text" readonly class="large-text code sg-url" value="' . esc_attr( $u['url'] ) . '" aria-label="' . esc_attr( $label . ' overlay URL' ) . '"> <button type="button" class="button" data-sg-copy>Copy</button></div>';
|
||||
if ( $withPreview ) {
|
||||
echo '<p><button type="button" class="button" data-sg-preview>Show live preview</button></p>';
|
||||
echo '<div class="sg-preview" hidden><iframe title="' . esc_attr( $label . ' preview' ) . '" loading="lazy" style="width:' . (int) $width . 'px;height:' . (int) $height . 'px"></iframe></div>';
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
if ( ! get_option( 'permalink_structure' ) ) {
|
||||
echo '<p class="description">Your site uses "Plain" permalinks, so the links use the longer form. They work the same.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Overlays' );
|
||||
$fonts = array( 'sans' => 'Clean sans-serif', 'serif' => 'Serif', 'mono' => 'Monospace', 'rounded' => 'Rounded', 'condensed' => 'Condensed' );
|
||||
echo '<p class="sg-lead">Paste these links into OBS as Browser Sources. Use the style builder to change how they look: all links update as you go.</p>';
|
||||
echo '<div class="sg-card"><h2>Style</h2><form id="sg-style" onsubmit="return false"><div class="sg-grid">';
|
||||
echo '<label>Theme<select name="theme">';
|
||||
foreach ( Style::THEMES as $t ) {
|
||||
echo '<option value="' . esc_attr( $t ) . '">' . esc_html( ucfirst( $t ) ) . '</option>';
|
||||
}
|
||||
echo '</select></label>';
|
||||
echo '<label>Font<select name="font">';
|
||||
foreach ( $fonts as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '">' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '<option value="__custom">A font installed on my PC...</option></select></label>';
|
||||
echo '<label class="sg-custom-font" hidden>Font name<input type="text" name="font_custom" maxlength="40" placeholder="Bebas Neue"></label>';
|
||||
echo '<label>Size (50% - 300%)<input type="number" name="scale" min="0.5" max="3" step="0.1" value="1"></label>';
|
||||
foreach ( array( 'color' => 'Text color', 'accent' => 'Accent color', 'accent2' => 'Second accent', 'track' => 'Bar background', 'bg' => 'Panel background' ) as $k => $l ) {
|
||||
echo '<label class="sg-color">' . esc_html( $l ) . '<span><input type="checkbox" name="use_' . esc_attr( $k ) . '" aria-label="Use custom ' . esc_attr( $l ) . '"> <input type="color" name="' . esc_attr( $k ) . '" value="#ffffff"></span></label>';
|
||||
}
|
||||
echo '</div><p class="description">Tick a box to override that color; unticked colors come from the theme.</p></form></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Links</h2>';
|
||||
self::urlList( true );
|
||||
echo '</div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Send a test donation</h2>';
|
||||
echo '<p>Shows a fake donation on the <strong>Donation alerts</strong> overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.</p>';
|
||||
echo '<p class="description"><strong>How tests are kept out of your numbers:</strong> test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked <em>TEST</em> in the Donations list. Test donations are kept in the database until you delete them below.</p>';
|
||||
Admin::form( 'sg_test_donation', array(), 'sg-inline' );
|
||||
echo '<label>Amount (' . esc_html( Admin::currency() ) . ') <input type="text" name="amount" class="small-text" value="' . esc_attr( 0 === \StreamGoals\Core\Money::exponent( Admin::currency() ) ? '500' : '5.00' ) . '"></label> ';
|
||||
echo '<button type="submit" class="button button-primary">Send test donation</button></form> ';
|
||||
Admin::form( 'sg_delete_tests', array(), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">Delete all test donations</button></form></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Security</h2><p>The links contain a secret token. If a link was shown on stream or shared by mistake, make new links. The old ones stop working immediately and you will need to paste the new ones into OBS.</p>';
|
||||
Admin::form( 'sg_regen_token', array(), 'sg-confirm' );
|
||||
echo '<button type="submit" class="button button-secondary" data-confirm="Make new overlay links? Your current links will stop working and you must update OBS.">Regenerate token</button></form></div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleTestDonation(): void {
|
||||
Admin::guard( 'sg_test_donation' );
|
||||
$cur = Admin::currency();
|
||||
$amt = Input::amountToMinor( Admin::post_str( 'amount', 30 ), $cur );
|
||||
if ( null === $amt || $amt <= 0 || $amt > 99999999 ) {
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'error', 'Please enter a valid test amount, for example 5.00.' );
|
||||
}
|
||||
$id = Store::insertTestDonation( $amt, $cur );
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), $id ? 'success' : 'error', $id ? 'Test donation sent. Watch your alerts overlay.' : 'The test donation could not be saved.' );
|
||||
}
|
||||
|
||||
public static function handleDeleteTests(): void {
|
||||
Admin::guard( 'sg_delete_tests' );
|
||||
$n = Store::deleteTestDonations();
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' );
|
||||
}
|
||||
|
||||
public static function handleRegenerate(): void {
|
||||
Admin::guard( 'sg_regen_token' );
|
||||
Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) );
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'New overlay links created. Update them in OBS.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\Client;
|
||||
use StreamGoals\PayPal\PayPalException;
|
||||
use StreamGoals\PayPal\WpCache;
|
||||
use StreamGoals\PayPal\WpTransport;
|
||||
|
||||
/** Saves PayPal credentials, tests them, and registers the webhook. Secrets are never echoed or logged. */
|
||||
final class PayPalConnector {
|
||||
|
||||
private const VERIFIED = 'sg_paypal_verified';
|
||||
|
||||
public static function fingerprint( array $s ): string {
|
||||
return hash_hmac( 'sha256', $s['paypal_mode'] . '|' . $s['paypal_client_id'] . '|' . $s['paypal_client_secret'], function_exists( 'wp_salt' ) ? wp_salt( 'auth' ) : 'sg' );
|
||||
}
|
||||
|
||||
/** True once Test connection succeeded for the credentials currently saved. */
|
||||
public static function isConnected(): bool {
|
||||
$s = Settings::all();
|
||||
return '' !== $s['paypal_client_id'] && '' !== $s['paypal_client_secret']
|
||||
&& hash_equals( (string) get_option( self::VERIFIED, '' ), self::fingerprint( $s ) );
|
||||
}
|
||||
|
||||
public static function webhookUrl(): string {
|
||||
return rest_url( 'streamgoals/v1/webhook' );
|
||||
}
|
||||
|
||||
/** Fields rendered by both the wizard and the Settings screen. */
|
||||
public static function fields(): void {
|
||||
$s = Settings::all();
|
||||
$mode = 'live' === $s['paypal_mode'] ? 'live' : 'sandbox';
|
||||
?>
|
||||
<div class="sg-tabs" role="tablist">
|
||||
<label class="sg-tab"><input type="radio" name="paypal_mode" value="sandbox" <?php checked( $mode, 'sandbox' ); ?>> <strong>Sandbox</strong> <span>(practice mode, fake money)</span></label>
|
||||
<label class="sg-tab"><input type="radio" name="paypal_mode" value="live" <?php checked( $mode, 'live' ); ?>> <strong>Live</strong> <span>(real money)</span></label>
|
||||
</div>
|
||||
<p class="description">Start with Sandbox to try everything for free. When you are ready, create a Live app the same way and switch here. Sandbox and Live use <em>different</em> Client IDs and Secrets.</p>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><label for="sg_client_id">Client ID</label></th>
|
||||
<td><input type="text" id="sg_client_id" name="paypal_client_id" class="regular-text code" autocomplete="off" spellcheck="false" value="<?php echo esc_attr( (string) $s['paypal_client_id'] ); ?>"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="sg_secret">Secret</label></th>
|
||||
<td>
|
||||
<input type="password" id="sg_secret" name="paypal_client_secret" class="regular-text code" autocomplete="new-password" spellcheck="false"
|
||||
value="" placeholder="<?php echo esc_attr( '' !== $s['paypal_client_secret'] ? Input::maskSecret( (string) $s['paypal_client_secret'] ) : 'Paste your Secret here' ); ?>">
|
||||
<p class="description"><?php echo '' !== $s['paypal_client_secret'] ? 'A Secret is saved. Leave this empty to keep it, or paste a new one to replace it.' : 'The Secret stays on your server and is never shown again.'; ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<?php
|
||||
}
|
||||
|
||||
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>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>
|
||||
<li>On the next page, copy the <strong>Client ID</strong>. Under <strong>Secret key 1</strong> click <strong>Show</strong> and copy the <strong>Secret</strong>.</li>
|
||||
<li>Choose the same mode below (Sandbox or Live), paste both values, and press the button. We will check them and set up payment notifications (the webhook) for you.</li>
|
||||
</ol>
|
||||
<p class="description">Webhook note: PayPal can only send notifications to a public <strong>https://</strong> website. On a local test site the webhook step will fail, which is fine for trying things out.</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/** admin-post: save credentials, test, register webhook. */
|
||||
public static function handle(): void {
|
||||
Admin::guard( 'sg_paypal_connect' );
|
||||
$from = Admin::post_str( 'return', 20 );
|
||||
// Computed lazily: the wizard lives at a different menu slug depending on whether PayPal is connected.
|
||||
$to = static fn( int $step ): string => 'settings' === $from ? Admin::url( 'streamgoals-settings' ) : SetupPage::url( $step );
|
||||
|
||||
$old = Settings::all();
|
||||
$post = Admin::post_raw();
|
||||
$mode = ( $post['paypal_mode'] ?? '' ) === 'live' ? 'live' : 'sandbox';
|
||||
$cid = Input::text( $post['paypal_client_id'] ?? '', 200 );
|
||||
$sec = Input::secretUnchanged( (string) ( $post['paypal_client_secret'] ?? '' ) ) ? (string) $old['paypal_client_secret'] : Input::text( $post['paypal_client_secret'], 300 );
|
||||
|
||||
if ( '' === $cid || '' === $sec ) {
|
||||
Admin::redirect( $to( 1 ), 'error', 'Please enter both the Client ID and the Secret from your PayPal app.' );
|
||||
}
|
||||
$changed = $mode !== $old['paypal_mode'] || $cid !== $old['paypal_client_id'] || $sec !== $old['paypal_client_secret'];
|
||||
$update = array( 'paypal_mode' => $mode, 'paypal_client_id' => $cid, 'paypal_client_secret' => $sec );
|
||||
if ( $changed ) {
|
||||
$update['paypal_webhook_id'] = ''; // a webhook belongs to one specific app/mode
|
||||
delete_option( self::VERIFIED );
|
||||
}
|
||||
Settings::update( $update );
|
||||
|
||||
$client = new Client( new WpTransport(), new WpCache(), $mode, $cid, $sec );
|
||||
$err = $client->testConnection();
|
||||
if ( null !== $err ) {
|
||||
Admin::redirect( $to( 1 ), 'error', 'Connection failed. ' . self::scrub( $err, $sec ) . ' Double-check that you copied the right values and that the mode (Sandbox/Live) matches the app.' );
|
||||
}
|
||||
update_option( self::VERIFIED, self::fingerprint( Settings::all() ), false );
|
||||
|
||||
$msg = 'Connected to PayPal (' . ( 'live' === $mode ? 'Live' : 'Sandbox' ) . ').';
|
||||
$type = 'success';
|
||||
if ( '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
|
||||
try {
|
||||
$id = $client->createWebhook( self::webhookUrl() );
|
||||
Settings::update( array( 'paypal_webhook_id' => $id ) );
|
||||
$msg .= ' Payment notifications (webhook) were set up automatically.';
|
||||
} catch ( PayPalException $e ) {
|
||||
$type = 'warning';
|
||||
$msg .= ' However, the webhook could not be registered automatically: ' . self::scrub( $e->getMessage(), $sec )
|
||||
. ' Webhooks need a public https:// site, and a webhook for this address may already exist in your PayPal app (delete it there and try again).';
|
||||
}
|
||||
}
|
||||
Admin::redirect( $to( 2 ), $type, $msg );
|
||||
}
|
||||
|
||||
/** Defensive: make sure an error text can never contain the secret or client id. */
|
||||
public static function scrub( string $text, string $secret ): string {
|
||||
$text = '' !== $secret ? str_replace( $secret, '[hidden]', $text ) : $text;
|
||||
return Input::text( $text, 400 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Rules\AddTimeRule;
|
||||
use StreamGoals\Rules\BonusRule;
|
||||
use StreamGoals\Rules\CounterRule;
|
||||
use StreamGoals\Rules\Donation;
|
||||
|
||||
/**
|
||||
* Pure rule-config logic: turns friendly form input into the exact config keys the Rules classes read,
|
||||
* produces human summaries and "what would a donation do" previews. No WordPress dependency.
|
||||
*/
|
||||
final class RuleConfig {
|
||||
|
||||
public const TYPES = array(
|
||||
'add_time' => 'Add time to the timer',
|
||||
'counter' => 'Counter',
|
||||
'bonus' => 'Big-donation bonus alert',
|
||||
);
|
||||
|
||||
private const UNIT_SECONDS = array( 'seconds' => 1, 'minutes' => 60, 'hours' => 3600 );
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $in Raw (already wp_unslash'ed) form fields.
|
||||
* @return array{config:?array,errors:string[]}
|
||||
*/
|
||||
public static function sanitize( string $type, array $in, string $currency ): array {
|
||||
$errors = array();
|
||||
$basis = ( $in['basis'] ?? 'base' ) === 'total' ? 'total' : 'base';
|
||||
$unit = Input::amountToMinor( $in['unit_amount'] ?? '', $currency );
|
||||
|
||||
switch ( $type ) {
|
||||
case 'add_time':
|
||||
$mult = self::UNIT_SECONDS[ (string) ( $in['time_unit'] ?? 'minutes' ) ] ?? null;
|
||||
$n = Input::int( $in['time_amount'] ?? '', 1, 1000000 );
|
||||
if ( null === $mult ) {
|
||||
$errors[] = 'Choose seconds, minutes or hours.';
|
||||
}
|
||||
if ( null === $n ) {
|
||||
$errors[] = 'Enter how much time to add (a whole number, 1 or more).';
|
||||
}
|
||||
if ( null === $unit || $unit <= 0 ) {
|
||||
$errors[] = 'Enter the donation amount that earns that time (for example 1.00).';
|
||||
}
|
||||
$cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors );
|
||||
$max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors );
|
||||
if ( $errors ) {
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
$secs = $n * $mult;
|
||||
if ( $secs > 31536000 ) {
|
||||
return array( 'config' => null, 'errors' => array( 'That is too much time per unit (more than a year).' ) );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'seconds_per_unit' => $secs,
|
||||
'unit_minor' => $unit,
|
||||
'cap_seconds_per_donation' => $cap,
|
||||
'max_total_seconds' => $max,
|
||||
'basis' => $basis,
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
|
||||
case 'counter':
|
||||
$step = Input::int( $in['step'] ?? '', 1, 1000000 );
|
||||
if ( null === $step ) {
|
||||
$errors[] = 'Enter how much the counter goes up each time (a whole number, 1 or more).';
|
||||
}
|
||||
if ( null === $unit || $unit <= 0 ) {
|
||||
$errors[] = 'Enter the donation amount that earns each step (for example 10.00).';
|
||||
}
|
||||
if ( $errors ) {
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'step' => $step,
|
||||
'per_minor' => $unit,
|
||||
'carry_over' => ! empty( $in['carry_over'] ),
|
||||
'basis' => $basis,
|
||||
'label' => Input::text( $in['label'] ?? '', 40 ),
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
|
||||
case 'bonus':
|
||||
$min = Input::amountToMinor( $in['min_amount'] ?? '', $currency );
|
||||
if ( null === $min || $min <= 0 ) {
|
||||
$errors[] = 'Enter the smallest single donation that triggers the bonus (for example 50.00).';
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'min_minor' => $min,
|
||||
'event' => Input::slug( $in['event'] ?? '' ),
|
||||
'basis' => $basis,
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
}
|
||||
return array( 'config' => null, 'errors' => array( 'Unknown rule type.' ) );
|
||||
}
|
||||
|
||||
private static function optionalMinutes( mixed $raw, string $what, array &$errors ): ?int {
|
||||
if ( ! is_scalar( $raw ) || '' === trim( (string) $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$m = Input::int( $raw, 1, 525600 );
|
||||
if ( null === $m ) {
|
||||
$errors[] = $what . ' must be a whole number of minutes (or leave it empty for no limit).';
|
||||
return null;
|
||||
}
|
||||
return $m * 60;
|
||||
}
|
||||
|
||||
/** Human-readable one-liner, e.g. "Adds 1 minute for every $1.00". */
|
||||
public static function summary( string $type, array $c, string $currency ): string {
|
||||
$basisNote = 'total' === ( $c['basis'] ?? 'base' ) ? ' (including fees the donor covers)' : '';
|
||||
switch ( $type ) {
|
||||
case 'add_time':
|
||||
$s = 'Adds ' . Format::duration( (int) ( $c['seconds_per_unit'] ?? 0 ) ) . ' for every ' . Format::money( (int) ( $c['unit_minor'] ?? 0 ), $currency ) . $basisNote;
|
||||
if ( isset( $c['cap_seconds_per_donation'] ) ) {
|
||||
$s .= ', at most ' . Format::duration( (int) $c['cap_seconds_per_donation'] ) . ' per donation';
|
||||
}
|
||||
if ( isset( $c['max_total_seconds'] ) ) {
|
||||
$s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total';
|
||||
}
|
||||
return $s;
|
||||
case 'counter':
|
||||
$label = (string) ( $c['label'] ?? '' );
|
||||
$s = 'Adds ' . (int) ( $c['step'] ?? 1 ) . ( '' !== $label ? ' to "' . $label . '"' : ' to the counter' )
|
||||
. ' for every ' . Format::money( (int) ( $c['per_minor'] ?? 0 ), $currency ) . $basisNote;
|
||||
return $s . ( ! empty( $c['carry_over'] ) ? ' (leftover amounts carry over to the next donation)' : ' (leftover amounts are not carried over)' );
|
||||
case 'bonus':
|
||||
return 'Triggers the "' . (string) ( $c['event'] ?? 'bonus' ) . '" bonus for any single donation of '
|
||||
. Format::money( (int) ( $c['min_minor'] ?? 0 ), $currency ) . ' or more' . $basisNote;
|
||||
}
|
||||
return 'Unknown rule';
|
||||
}
|
||||
|
||||
/**
|
||||
* What would a donation of $baseMinor (plus optional covered fee) do against these rules,
|
||||
* assuming a fresh state (no carry-over, no accumulated caps)?
|
||||
*
|
||||
* @param array<int,array{type:string,config:array}> $rules
|
||||
* @return string[]
|
||||
*/
|
||||
public static function preview( array $rules, int $baseMinor, string $currency, int $feeMinor = 0 ): array {
|
||||
$d = new Donation( 0, 0, $baseMinor, $feeMinor, $baseMinor + $feeMinor, $currency );
|
||||
$lines = array();
|
||||
foreach ( $rules as $r ) {
|
||||
$type = (string) ( $r['type'] ?? '' );
|
||||
$cfg = (array) ( $r['config'] ?? array() );
|
||||
try {
|
||||
if ( 'add_time' === $type ) {
|
||||
$res = AddTimeRule::fromConfig( $cfg )->apply( $d, 0, 0, 0 );
|
||||
$lines[] = $res['delta'] > 0 ? 'Timer: +' . Format::duration( $res['delta'] ) : 'Timer: no time added';
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 );
|
||||
$lbl = (string) ( $cfg['label'] ?? '' );
|
||||
$lines[] = ( '' !== $lbl ? $lbl : 'Counter' ) . ': +' . $res['delta'];
|
||||
} elseif ( 'bonus' === $type ) {
|
||||
$b = BonusRule::fromConfig( $cfg );
|
||||
$lines[] = $b->apply( $d ) ? 'Bonus "' . $b->event . '" triggers' : 'Bonus "' . $b->event . '" does not trigger';
|
||||
}
|
||||
} catch ( \InvalidArgumentException ) {
|
||||
$lines[] = 'A rule is misconfigured and will be skipped.';
|
||||
}
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Reverse of sanitize(): config -> editable form values. */
|
||||
public static function toForm( string $type, array $c, string $currency ): array {
|
||||
$f = array( 'basis' => 'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base' );
|
||||
if ( 'add_time' === $type ) {
|
||||
$s = (int) ( $c['seconds_per_unit'] ?? 60 );
|
||||
[ $f['time_amount'], $f['time_unit'] ] = 0 === $s % 3600 && $s > 0 ? array( $s / 3600, 'hours' ) : ( 0 === $s % 60 && $s > 0 ? array( $s / 60, 'minutes' ) : array( $s, 'seconds' ) );
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['unit_minor'] ?? 100 ), $currency );
|
||||
$f['cap_minutes'] = isset( $c['cap_seconds_per_donation'] ) ? (string) intdiv( (int) $c['cap_seconds_per_donation'], 60 ) : '';
|
||||
$f['max_total_minutes'] = isset( $c['max_total_seconds'] ) ? (string) intdiv( (int) $c['max_total_seconds'], 60 ) : '';
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$f['step'] = (int) ( $c['step'] ?? 1 );
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency );
|
||||
$f['carry_over'] = ! empty( $c['carry_over'] );
|
||||
$f['label'] = (string) ( $c['label'] ?? '' );
|
||||
} else {
|
||||
$f['min_amount'] = Format::decimal( (int) ( $c['min_minor'] ?? 5000 ), $currency );
|
||||
$f['event'] = (string) ( $c['event'] ?? 'big_donation' );
|
||||
}
|
||||
return $f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** Settings: PayPal credentials (own form), fees, anonymity, moderation, profanity, limits, currency. */
|
||||
final class SettingsPage {
|
||||
|
||||
private const POLICIES = array(
|
||||
'allow' => 'Donors choose: they can give a name or stay anonymous',
|
||||
'require_name' => 'Donors must give a name',
|
||||
'force_anonymous' => 'Everyone is anonymous (no names are collected or stored)',
|
||||
);
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'StreamGoals settings' );
|
||||
$s = Settings::all();
|
||||
$cur = Admin::currency();
|
||||
|
||||
echo '<div class="sg-card"><h2>PayPal connection</h2>';
|
||||
echo PayPalConnector::isConnected() ? '<p class="sg-ok">Connected (' . esc_html( 'live' === $s['paypal_mode'] ? 'Live' : 'Sandbox' ) . ').</p>' : '<p class="sg-warn">Not connected yet. Follow the steps in the <a href="' . esc_url( SetupPage::url( 1 ) ) . '">setup guide</a>.</p>';
|
||||
Admin::form( 'sg_paypal_connect', array( 'return' => 'settings' ) );
|
||||
PayPalConnector::fields();
|
||||
echo '<p class="description">Webhook address (registered automatically): <code>' . esc_html( PayPalConnector::webhookUrl() ) . '</code><br>Webhook status: ' . ( '' !== (string) $s['paypal_webhook_id'] ? 'registered' : 'not registered' ) . '</p>';
|
||||
echo '<p><button class="button button-primary">Save and test connection</button></p></form></div>';
|
||||
|
||||
Admin::form( 'sg_settings_save' );
|
||||
echo '<div class="sg-card"><h2>Donations</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_cur">Currency</label></th><td><select id="sg_cur" name="currency">';
|
||||
foreach ( Format::CURRENCIES as $c => $name ) {
|
||||
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_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 ) {
|
||||
echo '<label><input type="radio" name="anonymity_policy" value="' . esc_attr( $k ) . '"' . checked( $s['anonymity_policy'], $k, false ) . '> ' . esc_html( $l ) . '</label><br>';
|
||||
}
|
||||
echo '</fieldset><p class="description">Anonymous donors\' names are never saved.</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Messages</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Moderation</th><td><label><input type="checkbox" name="moderate_messages" value="1"' . checked( ! empty( $s['moderate_messages'] ), true, false ) . '> Hold messages for my approval before they can be shown in alerts</label></td></tr>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Filter bad language in messages and names</label><br>';
|
||||
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
|
||||
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>PayPal fee estimate</h2>';
|
||||
echo '<p>When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (<strong>3.49% + $0.49</strong>) are <strong>US domestic estimates</strong>. Fees for international (cross-border) payments and currency conversion are higher and are <strong>not</strong> included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.</p>';
|
||||
echo '<table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_pct">Percentage fee</label></th><td><input type="text" id="sg_pct" name="fee_percent" class="small-text" inputmode="decimal" value="' . esc_attr( number_format( (int) $s['fee_percent_bps'] / 100, 2, '.', '' ) ) . '"> %</td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_fix">Fixed fee (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_fix" name="fee_fixed" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( (int) $s['fee_fixed_minor'], $cur ) ) . '"></td></tr></table></div>';
|
||||
echo '<p><button class="button button-primary button-hero">Save settings</button></p></form>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_settings_save' );
|
||||
$post = Admin::post_raw();
|
||||
$back = Admin::url( 'streamgoals-settings' );
|
||||
$errors = array();
|
||||
$cur = Format::currency( $post['currency'] ?? 'USD' );
|
||||
$upd = array();
|
||||
|
||||
$min = Input::amountToMinor( $post['min_donation'] ?? '', $cur );
|
||||
if ( null === $min || $min < 1 ) {
|
||||
$errors[] = 'Minimum donation must be an amount greater than zero.';
|
||||
} else {
|
||||
$upd['min_donation_minor'] = $min;
|
||||
}
|
||||
$len = Input::int( $post['message_max_length'] ?? '', 0, 500 );
|
||||
if ( null === $len ) {
|
||||
$errors[] = 'Longest message must be a number from 0 to 500.';
|
||||
} else {
|
||||
$upd['message_max_length'] = $len;
|
||||
}
|
||||
$pct = Input::percentToBps( $post['fee_percent'] ?? '' );
|
||||
if ( null === $pct ) {
|
||||
$errors[] = 'Percentage fee must be between 0 and 30 (for example 3.49).';
|
||||
} else {
|
||||
$upd['fee_percent_bps'] = $pct;
|
||||
}
|
||||
$fix = Input::amountToMinor( $post['fee_fixed'] ?? '', $cur );
|
||||
if ( null === $fix || $fix > 10000 ) {
|
||||
$errors[] = 'Fixed fee must be a small amount (for example 0.49).';
|
||||
} else {
|
||||
$upd['fee_fixed_minor'] = $fix;
|
||||
}
|
||||
$pol = isset( $post['anonymity_policy'] ) && is_string( $post['anonymity_policy'] ) ? $post['anonymity_policy'] : '';
|
||||
if ( ! isset( self::POLICIES[ $pol ] ) ) {
|
||||
$errors[] = 'Please choose a names option.';
|
||||
} else {
|
||||
$upd['anonymity_policy'] = $pol;
|
||||
}
|
||||
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
|
||||
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
|
||||
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
|
||||
$upd['profanity_words'] = Input::words( isset( $post['profanity_words'] ) && is_string( $post['profanity_words'] ) ? $post['profanity_words'] : '' );
|
||||
|
||||
Settings::update( $upd );
|
||||
update_option( 'sg_currency', $cur, false ); // Settings has no currency key, so it lives in its own option.
|
||||
|
||||
if ( $errors ) {
|
||||
Admin::redirect( $back, 'warning', 'Some settings were not saved: ' . implode( ' ', $errors ) . ' Everything else was saved.' );
|
||||
}
|
||||
Admin::redirect( $back, 'success', 'Settings saved.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
/** The 4-step setup wizard: PayPal, first goal, donation page, overlays. */
|
||||
final class SetupPage {
|
||||
|
||||
private const STEPS = array( 1 => 'PayPal', 2 => 'First goal', 3 => 'Donation page', 4 => 'Overlays' );
|
||||
|
||||
public static function url( int $step = 1 ): string {
|
||||
$page = PayPalConnector::isConnected() ? 'streamgoals-setup' : Admin::HOME;
|
||||
return Admin::url( $page, array( 'step' => $step ) );
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'StreamGoals setup' );
|
||||
$connected = PayPalConnector::isConnected();
|
||||
$step = Admin::get_int( 'step' );
|
||||
$step = isset( self::STEPS[ $step ] ) ? $step : 1;
|
||||
if ( ! $connected ) {
|
||||
$step = 1; // nothing else works before PayPal is connected
|
||||
}
|
||||
echo '<p class="sg-lead">Welcome! Four quick steps and you are ready to collect donations on stream.</p>';
|
||||
echo '<ol class="sg-progress">';
|
||||
foreach ( self::STEPS as $n => $label ) {
|
||||
$cls = $n === $step ? 'is-current' : ( $n < $step || ( $connected && $n > 1 ) ? 'is-done' : '' );
|
||||
echo '<li class="' . esc_attr( $cls ) . '">' . ( $connected ? '<a href="' . esc_url( self::url( $n ) ) . '">' : '' ) . esc_html( $label ) . ( $connected ? '</a>' : '' ) . '</li>';
|
||||
}
|
||||
echo '</ol><div class="sg-card">';
|
||||
match ( $step ) {
|
||||
2 => self::step2(),
|
||||
3 => self::step3(),
|
||||
4 => self::step4(),
|
||||
default => self::step1( $connected ),
|
||||
};
|
||||
echo '</div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function step1( bool $connected ): void {
|
||||
echo '<h2>Step 1: Connect PayPal</h2>';
|
||||
if ( $connected ) {
|
||||
echo '<p class="sg-ok">PayPal is connected. You can continue, or paste new credentials below to change them.</p>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( 2 ) ) . '">Continue to step 2</a></p>';
|
||||
}
|
||||
PayPalConnector::instructions();
|
||||
Admin::form( 'sg_paypal_connect', array( 'return' => 'setup' ) );
|
||||
PayPalConnector::fields();
|
||||
echo '<p><button type="submit" class="button button-primary button-hero">Test connection</button></p></form>';
|
||||
}
|
||||
|
||||
private static function step2(): void {
|
||||
$cur = Admin::currency();
|
||||
echo '<h2>Step 2: Create your first goal</h2><p>Pick a starting point. You can change everything later on the Goals screen.</p>';
|
||||
Admin::form( 'sg_wizard_goal' );
|
||||
echo '<div class="sg-templates">';
|
||||
$first = true;
|
||||
foreach ( Templates::LABELS as $key => [ $label, $desc ] ) {
|
||||
echo '<label class="sg-template"><input type="radio" name="template" value="' . esc_attr( $key ) . '"' . checked( $first, true, false ) . '> <strong>' . esc_html( $label ) . '</strong><br><span>' . esc_html( $desc ) . '</span></label>';
|
||||
$first = false;
|
||||
}
|
||||
echo '</div><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_title">Goal name</label></th><td><input type="text" id="sg_title" name="title" class="regular-text" maxlength="190" placeholder="New gaming PC"></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_target" name="target" class="small-text" inputmode="decimal" value="' . esc_attr( 0 === \StreamGoals\Core\Money::exponent( $cur ) ? '10000' : '100.00' ) . '"> <span class="description">How much you want to raise.</span></td></tr></table>';
|
||||
echo '<p><button type="submit" class="button button-primary button-hero">Create goal</button></p></form>';
|
||||
}
|
||||
|
||||
private static function step3(): void {
|
||||
echo '<h2>Step 3: Add a donation page</h2>';
|
||||
$id = (int) get_option( 'sg_donate_page_id', 0 );
|
||||
$post = $id ? get_post( $id ) : null;
|
||||
if ( $post && 'trash' !== $post->post_status ) {
|
||||
echo '<p class="sg-ok">Your donation page exists: <a href="' . esc_url( (string) get_permalink( $post ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( get_the_title( $post ) ) . '</a> (<a href="' . esc_url( (string) get_edit_post_link( $post->ID, 'raw' ) ) . '">edit</a>).</p>';
|
||||
} else {
|
||||
echo '<p>Viewers donate through a page on your site. We can create it for you now. It simply contains this shortcode:</p>';
|
||||
}
|
||||
echo '<p><code>[streamgoals_donate]</code> <button type="button" class="button" data-sg-copy-text="[streamgoals_donate]">Copy</button></p>';
|
||||
echo '<p class="description">You can paste that shortcode into any page or post. To show only one goal use <code>[streamgoals_donate goal="ID"]</code>.</p>';
|
||||
if ( ! $post || 'trash' === $post->post_status ) {
|
||||
Admin::form( 'sg_wizard_page', array( 'mode' => 'create' ), 'sg-inline' );
|
||||
echo '<button type="submit" class="button button-primary button-hero">Create my Donate page</button></form> ';
|
||||
}
|
||||
Admin::form( 'sg_wizard_page', array( 'mode' => 'skip' ), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">' . ( $post && 'trash' !== $post->post_status ? 'Continue' : 'Skip, I will add it myself' ) . '</button></form>';
|
||||
}
|
||||
|
||||
private static function step4(): void {
|
||||
echo '<h2>Step 4: Add the overlays to OBS</h2>';
|
||||
echo '<p>Overlays are small web pages OBS shows on top of your stream. Each one has its own link. <strong>Keep these links private</strong>: anyone with a link can see your live overlay (not your donor details or money info).</p>';
|
||||
OverlaysPage::urlList();
|
||||
echo '<h3>How to add one in OBS</h3><ol class="sg-steps">';
|
||||
echo '<li>In OBS, under <strong>Sources</strong> click <strong>+</strong> and choose <strong>Browser</strong>.</li>';
|
||||
echo '<li>Name it (for example "Goal bar") and click OK.</li>';
|
||||
echo '<li>Paste the link into the <strong>URL</strong> box. Do <em>not</em> tick "Local file".</li>';
|
||||
echo '<li>Set <strong>Width</strong> and <strong>Height</strong> to the recommended size shown next to the link. Leave the custom CSS box as it is.</li>';
|
||||
echo '<li>Click OK, then move and resize it on your canvas. The background is transparent automatically.</li>';
|
||||
echo '<li>Want different colors or fonts? Open the <a href="' . esc_url( Admin::url( 'streamgoals-overlays' ) ) . '">Overlays screen</a>, which builds the link for you and lets you send a test donation.</li></ol>';
|
||||
echo '<p><a class="button button-primary button-hero" href="' . esc_url( Admin::url( Admin::HOME ) ) . '">Finish setup</a></p>';
|
||||
}
|
||||
|
||||
public static function handleGoal(): void {
|
||||
Admin::guard( 'sg_wizard_goal' );
|
||||
$cur = Admin::currency();
|
||||
$key = Admin::post_str( 'template', 20 );
|
||||
$tgt = Input::amountToMinor( Admin::post_str( 'target', 30 ), $cur );
|
||||
if ( ! Templates::exists( $key ) ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'Please choose a goal template.' );
|
||||
}
|
||||
if ( null === $tgt || $tgt <= 0 ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'Please enter a target amount greater than zero, for example 100.00.' );
|
||||
}
|
||||
$built = Templates::build( $key, $cur, $tgt, Admin::post_str( 'title', 190 ) );
|
||||
$built['goal']['starts_at'] = null;
|
||||
$built['goal']['ends_at'] = null;
|
||||
$id = Store::goals()->create( $built['goal'] );
|
||||
if ( $id <= 0 ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'The goal could not be saved. Please try again.' );
|
||||
}
|
||||
foreach ( $built['rules'] as $r ) {
|
||||
Store::saveRule( $id, $r['type'], $r['config'] );
|
||||
}
|
||||
update_option( 'sg_wizard_goal_id', $id, false );
|
||||
Admin::redirect( self::url( 3 ), 'success', 'Goal created.' );
|
||||
}
|
||||
|
||||
public static function handlePage(): void {
|
||||
Admin::guard( 'sg_wizard_page' );
|
||||
if ( 'create' === Admin::post_str( 'mode', 10 ) ) {
|
||||
if ( ! current_user_can( 'publish_pages' ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
$id = wp_insert_post( array(
|
||||
'post_type' => 'page',
|
||||
'post_status' => 'publish',
|
||||
'post_title' => 'Donate',
|
||||
'post_content' => '[streamgoals_donate]',
|
||||
), true );
|
||||
if ( is_wp_error( $id ) ) {
|
||||
Admin::redirect( self::url( 3 ), 'error', 'The page could not be created. You can add the shortcode to any page yourself.' );
|
||||
}
|
||||
update_option( 'sg_donate_page_id', (int) $id, false );
|
||||
Admin::redirect( self::url( 4 ), 'success', 'Donate page created and published.' );
|
||||
}
|
||||
Admin::redirect( self::url( 4 ), 'info', 'Skipped. Remember to add [streamgoals_donate] to a page.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\DonationRepository;
|
||||
use StreamGoals\Core\GoalRepository;
|
||||
|
||||
/** $wpdb access used only by the admin screens. Requires live WordPress. */
|
||||
final class Store {
|
||||
|
||||
private static function t( string $name ): string {
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'sg_' . $name;
|
||||
}
|
||||
|
||||
public static function goals(): GoalRepository {
|
||||
return new GoalRepository();
|
||||
}
|
||||
|
||||
public static function donations(): DonationRepository {
|
||||
return new DonationRepository();
|
||||
}
|
||||
|
||||
/** @return array[] all rules (enabled or not) with decoded config. */
|
||||
public static function rules( int $goalId ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A );
|
||||
foreach ( (array) $rows as &$r ) {
|
||||
$cfg = json_decode( (string) $r['config'], true );
|
||||
$r['config'] = is_array( $cfg ) ? $cfg : array();
|
||||
}
|
||||
return (array) $rows;
|
||||
}
|
||||
|
||||
public static function rule( int $ruleId, int $goalId ): ?array {
|
||||
foreach ( self::rules( $goalId ) as $r ) {
|
||||
if ( (int) $r['id'] === $ruleId ) {
|
||||
return $r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function saveRule( int $goalId, string $type, array $config, ?int $ruleId = null ): void {
|
||||
global $wpdb;
|
||||
$json = wp_json_encode( $config );
|
||||
if ( null === $ruleId ) {
|
||||
$sort = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COALESCE(MAX(sort),0)+1 FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
$wpdb->insert( self::t( 'rules' ), array( 'goal_id' => $goalId, 'type' => $type, 'config' => $json, 'enabled' => 1, 'sort' => $sort ), array( '%d', '%s', '%s', '%d', '%d' ) );
|
||||
} else {
|
||||
$wpdb->update( self::t( 'rules' ), array( 'config' => $json ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%s' ), array( '%d', '%d' ) );
|
||||
}
|
||||
}
|
||||
|
||||
public static function setRuleEnabled( int $ruleId, int $goalId, bool $on ): void {
|
||||
global $wpdb;
|
||||
$wpdb->update( self::t( 'rules' ), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d' ), array( '%d', '%d' ) );
|
||||
}
|
||||
|
||||
/** Deleting a rule keeps its event history rows out of the way (they are only idempotency markers). */
|
||||
public static function deleteRule( int $ruleId, int $goalId ): void {
|
||||
global $wpdb;
|
||||
if ( ! self::rule( $ruleId, $goalId ) ) {
|
||||
return;
|
||||
}
|
||||
$wpdb->delete( self::t( 'rules' ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d', '%d' ) );
|
||||
$wpdb->delete( self::t( 'rule_events' ), array( 'rule_id' => $ruleId ), array( '%d' ) );
|
||||
$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'state' ) . ' WHERE goal_id = %d AND skey LIKE %s', $goalId, '%:' . $ruleId ) );
|
||||
}
|
||||
|
||||
public static function donationCountForGoal( int $goalId ): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
}
|
||||
|
||||
/** Only possible when the goal has no donations (otherwise donations would be orphaned). */
|
||||
public static function deleteGoal( int $goalId ): bool {
|
||||
global $wpdb;
|
||||
if ( self::donationCountForGoal( $goalId ) > 0 ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( self::rules( $goalId ) as $r ) {
|
||||
self::deleteRule( (int) $r['id'], $goalId );
|
||||
}
|
||||
$wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
return self::goals()->delete( $goalId );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{status?:string,search?:string,tests?:string,moderation?:string} $f
|
||||
* @return array{rows:array[],total:int}
|
||||
*/
|
||||
public static function searchDonations( array $f, int $page, int $perPage ): array {
|
||||
global $wpdb;
|
||||
[ $where, $args ] = self::donationWhere( $f );
|
||||
$t = self::t( 'donations' );
|
||||
$total = (int) $wpdb->get_var( $args ? $wpdb->prepare( "SELECT COUNT(*) FROM {$t} WHERE {$where}", ...$args ) : "SELECT COUNT(*) FROM {$t} WHERE {$where}" );
|
||||
$a2 = array_merge( $args, array( $perPage, max( 0, ( $page - 1 ) * $perPage ) ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$t} WHERE {$where} ORDER BY id DESC LIMIT %d OFFSET %d", ...$a2 ), ARRAY_A );
|
||||
return array( 'rows' => (array) $rows, 'total' => $total );
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:array} */
|
||||
private static function donationWhere( array $f ): array {
|
||||
global $wpdb;
|
||||
$w = array( '1=1' );
|
||||
$args = array();
|
||||
$st = $f['status'] ?? '';
|
||||
if ( in_array( $st, array( 'pending', 'completed', 'refunded', 'reversed' ), true ) ) {
|
||||
$w[] = 'status = %s';
|
||||
$args[] = $st;
|
||||
}
|
||||
if ( in_array( $f['moderation'] ?? '', array( 'pending', 'approved', 'rejected' ), true ) ) {
|
||||
$w[] = 'moderation = %s';
|
||||
$args[] = $f['moderation'];
|
||||
}
|
||||
if ( 'hide' === ( $f['tests'] ?? '' ) ) {
|
||||
$w[] = 'paypal_order_id NOT LIKE %s';
|
||||
$args[] = $wpdb->esc_like( Format::TEST_PREFIX ) . '%';
|
||||
}
|
||||
$s = trim( (string) ( $f['search'] ?? '' ) );
|
||||
if ( '' !== $s ) {
|
||||
$like = '%' . $wpdb->esc_like( $s ) . '%';
|
||||
// Names of anonymous donors are never stored, and are never searchable.
|
||||
$w[] = '( ( is_anonymous = 0 AND donor_name LIKE %s ) OR message LIKE %s OR paypal_order_id LIKE %s OR paypal_capture_id LIKE %s )';
|
||||
array_push( $args, $like, $like, $like, $like );
|
||||
}
|
||||
return array( implode( ' AND ', $w ), $args );
|
||||
}
|
||||
|
||||
/** Real donations only (test donations excluded). Streams in batches to bound memory. */
|
||||
public static function exportBatch( int $afterId, int $limit ): array {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
|
||||
$afterId,
|
||||
$wpdb->esc_like( Format::TEST_PREFIX ) . '%',
|
||||
$limit
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
}
|
||||
|
||||
public static function pendingModerationCount(): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND moderation = 'pending'" );
|
||||
}
|
||||
|
||||
public static function setModeration( int $id, string $to ): bool {
|
||||
global $wpdb;
|
||||
if ( ! in_array( $to, array( 'approved', 'rejected' ), true ) ) {
|
||||
return false;
|
||||
}
|
||||
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET moderation = %s WHERE id = %d AND moderation = 'pending'", $to, $id ) );
|
||||
return 1 === $n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test donations: goal_id = 0 (so every per-goal SUM and the rules engine ignore them),
|
||||
* paypal_order_id/capture id start with TEST-, and the message is flagged. Excluded from CSV.
|
||||
*/
|
||||
public static function insertTestDonation( int $amountMinor, string $currency ): ?int {
|
||||
return self::donations()->insert( array(
|
||||
'goal_id' => 0,
|
||||
'paypal_order_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 6 ) ),
|
||||
'paypal_capture_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 8 ) ),
|
||||
'base_minor' => $amountMinor,
|
||||
'fee_minor' => 0,
|
||||
'total_minor' => $amountMinor,
|
||||
'currency' => $currency,
|
||||
'donor_name' => 'Test Donor',
|
||||
'is_anonymous' => 0,
|
||||
'message' => '[TEST] This is a test alert from StreamGoals.',
|
||||
'status' => 'completed',
|
||||
'moderation' => 'approved',
|
||||
) );
|
||||
}
|
||||
|
||||
public static function deleteTestDonations(): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'donations' ) . ' WHERE goal_id = 0 AND paypal_order_id LIKE %s', $wpdb->esc_like( Format::TEST_PREFIX ) . '%' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** Pure goal templates used by the setup wizard. */
|
||||
final class Templates {
|
||||
|
||||
public const LABELS = array(
|
||||
'simple' => array( 'Simple goal', 'A progress bar towards a fundraising target. Nothing else.' ),
|
||||
'subathon' => array( 'Subathon timer: +1 min per $1', 'A countdown that gets longer with every donation (1 minute added for every $1).' ),
|
||||
'counter' => array( 'Counter: +1 per $10', 'A counter that goes up by 1 for every $10 donated (for example "pies thrown").' ),
|
||||
);
|
||||
|
||||
public static function exists( string $key ): bool {
|
||||
return isset( self::LABELS[ $key ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{goal:array,rules:array<int,array{type:string,config:array}>}
|
||||
*/
|
||||
public static function build( string $key, string $currency, int $targetMinor, string $title = '' ): array {
|
||||
$one = 10 ** Money::exponent( $currency ); // one whole currency unit, in minor units
|
||||
$name = '' !== trim( $title ) ? trim( $title ) : ( 'subathon' === $key ? 'Subathon' : ( 'counter' === $key ? 'Donation counter' : 'My first goal' ) );
|
||||
$goal = array( 'title' => $name, 'target_minor' => $targetMinor, 'currency' => $currency, 'status' => 'active', 'counts_fees' => 0 );
|
||||
$rules = array();
|
||||
if ( 'subathon' === $key ) {
|
||||
$rules[] = array( 'type' => 'add_time', 'config' => array(
|
||||
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'basis' => 'base',
|
||||
) );
|
||||
} elseif ( 'counter' === $key ) {
|
||||
$rules[] = array( 'type' => 'counter', 'config' => array(
|
||||
'step' => 1, 'per_minor' => 10 * $one, 'carry_over' => true, 'basis' => 'base', 'label' => 'Count',
|
||||
) );
|
||||
}
|
||||
return array( 'goal' => $goal, 'rules' => $rules );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Csv;
|
||||
use StreamGoals\Admin\Format;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Admin\RuleConfig;
|
||||
use StreamGoals\Admin\Templates;
|
||||
|
||||
final class AdminLogicTest extends TestCase {
|
||||
|
||||
public function test_csv_escapes_formula_prefixes(): void {
|
||||
foreach ( array( '=1+1', '+1', '-1', '@SUM(A1)', "\tx", "\rx" ) as $v ) {
|
||||
$this->assertSame( "'" . $v, Csv::cell( $v ) );
|
||||
}
|
||||
$this->assertSame( 'hello', Csv::cell( 'hello' ) );
|
||||
$this->assertSame( '10.00', Csv::cell( '10.00' ) );
|
||||
$this->assertSame( '', Csv::cell( null ) );
|
||||
$this->assertSame( "\"a\",\"'=b\",\"say \"\"hi\"\"\"\r\n", Csv::line( array( 'a', '=b', 'say "hi"' ) ) );
|
||||
}
|
||||
|
||||
public function test_amount_parsing(): void {
|
||||
$this->assertSame( 100, Input::amountToMinor( '1', 'USD' ) );
|
||||
$this->assertSame( 100050, Input::amountToMinor( '$1,000.50', 'USD' ) );
|
||||
$this->assertSame( 500, Input::amountToMinor( '500', 'JPY' ) );
|
||||
$this->assertNull( Input::amountToMinor( '1.234', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( '-5', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( 'abc', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( '', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( array( '1' ), 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_percent_and_misc_input(): void {
|
||||
$this->assertSame( 349, Input::percentToBps( '3.49' ) );
|
||||
$this->assertSame( 350, Input::percentToBps( '3.5%' ) );
|
||||
$this->assertSame( 0, Input::percentToBps( '0' ) );
|
||||
$this->assertNull( Input::percentToBps( '31' ) );
|
||||
$this->assertNull( Input::percentToBps( 'x' ) );
|
||||
$this->assertSame( "bad\nword", Input::words( " Bad\r\nword\nBAD" ) );
|
||||
$this->assertSame( 'big_donation', Input::slug( '!!!' ) );
|
||||
$this->assertSame( 'mega_win', Input::slug( 'Mega Win' ) );
|
||||
$this->assertTrue( Input::secretUnchanged( Input::maskSecret( 'abc' ) ) );
|
||||
$this->assertTrue( Input::secretUnchanged( '' ) );
|
||||
$this->assertFalse( Input::secretUnchanged( 'newsecret' ) );
|
||||
$this->assertSame( '', Input::maskSecret( '' ) );
|
||||
}
|
||||
|
||||
public function test_add_time_sanitize_uses_exact_config_keys(): void {
|
||||
$r = RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00', 'cap_minutes' => '10', 'max_total_minutes' => '' ), 'USD' );
|
||||
$this->assertSame( array(), $r['errors'] );
|
||||
$this->assertSame(
|
||||
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' ),
|
||||
$r['config']
|
||||
);
|
||||
}
|
||||
|
||||
public function test_sanitize_validation_errors(): void {
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array(), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '0', 'time_unit' => 'minutes', 'unit_amount' => '1' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '0' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1', 'cap_minutes' => 'x' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'counter', array( 'step' => '1' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'bonus', array( 'min_amount' => '0' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'nope', array(), 'USD' )['errors'] );
|
||||
$this->assertNull( RuleConfig::sanitize( 'nope', array(), 'USD' )['config'] );
|
||||
}
|
||||
|
||||
public function test_counter_and_bonus_sanitize(): void {
|
||||
$c = RuleConfig::sanitize( 'counter', array( 'step' => '1', 'unit_amount' => '10', 'carry_over' => '1', 'label' => '<b>Pies</b>' ), 'USD' );
|
||||
$this->assertSame( array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true, 'basis' => 'base', 'label' => 'Pies' ), $c['config'] );
|
||||
$b = RuleConfig::sanitize( 'bonus', array( 'min_amount' => '50', 'event' => 'Big Donation', 'basis' => 'total' ), 'USD' );
|
||||
$this->assertSame( array( 'min_minor' => 5000, 'event' => 'big_donation', 'basis' => 'total' ), $b['config'] );
|
||||
}
|
||||
|
||||
public function test_summaries(): void {
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) );
|
||||
$this->assertStringContainsString( 'at most 10 minutes per donation', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600 ), 'USD' ) );
|
||||
$this->assertStringContainsString( 'Adds 1 to "Pies" for every $10.00', RuleConfig::summary( 'counter', array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies', 'carry_over' => true ), 'USD' ) );
|
||||
$this->assertStringContainsString( '$50.00 or more', RuleConfig::summary( 'bonus', array( 'min_minor' => 5000, 'event' => 'big' ), 'USD' ) );
|
||||
$this->assertSame( '1 hour 1 minute 1 second', Format::duration( 3661 ) );
|
||||
}
|
||||
|
||||
public function test_preview_for_25_dollars(): void {
|
||||
$rules = array(
|
||||
array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ),
|
||||
array( 'type' => 'counter', 'config' => array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies' ) ),
|
||||
array( 'type' => 'bonus', 'config' => array( 'min_minor' => 5000, 'event' => 'big' ) ),
|
||||
);
|
||||
$this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_form_roundtrip(): void {
|
||||
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' );
|
||||
$form = RuleConfig::toForm( 'add_time', $cfg, 'USD' );
|
||||
$back = RuleConfig::sanitize( 'add_time', $form, 'USD' );
|
||||
$this->assertSame( $cfg, $back['config'] );
|
||||
}
|
||||
|
||||
public function test_templates(): void {
|
||||
$t = Templates::build( 'subathon', 'USD', 100000 );
|
||||
$this->assertSame( 60, $t['rules'][0]['config']['seconds_per_unit'] );
|
||||
$this->assertSame( 100, $t['rules'][0]['config']['unit_minor'] );
|
||||
$c = Templates::build( 'counter', 'USD', 5000, 'Pies' );
|
||||
$this->assertSame( 1000, $c['rules'][0]['config']['per_minor'] );
|
||||
$this->assertSame( 'Pies', $c['goal']['title'] );
|
||||
$this->assertSame( 10, Templates::build( 'counter', 'JPY', 5000 )['rules'][0]['config']['per_minor'] );
|
||||
$this->assertSame( array(), Templates::build( 'simple', 'USD', 5000 )['rules'] );
|
||||
$this->assertFalse( Templates::exists( 'x' ) );
|
||||
}
|
||||
|
||||
public function test_donor_name_and_test_flag(): void {
|
||||
$this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ) );
|
||||
$this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => '' ) ) );
|
||||
$this->assertSame( 'Sam', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => 'Sam' ) ) );
|
||||
$this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) );
|
||||
$this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user