Diff -- /var/www/vhosts/3dshawn.com/affiliate.3dshawn.com/admin_billing.cgi

O Operator
Diff

/var/www/vhosts/3dshawn.com/affiliate.3dshawn.com/admin_billing.cgi

added on local at 2026-07-11 18:38:27

Added
+681
lines
Removed
-0
lines
Context
0
unchanged
Blobs
from
to 735fb8e5c726
Restore this content →
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.
1#!/usr/bin/perl
2#======================================================================
3# WebSTLs - Admin Billing Console
4#
5# Company-staff only. Surfaces every dimension of the billing system:
6# - Money received (MTD) -- actual cash received this calendar month
7# - Credit consumed (30d) -- services delivered against credit
8# - Outstanding credit -- liability still on the books
9# - MRR / ARR + plan breakdown
10# - Recent invoices (all users) with status + refund-as-credit action
11# - Accounts with non-zero credit balance
12#
13# Critically: cash revenue and credit consumption are reported as
14# separate numbers. The cash tile NEVER includes credit applications,
15# so the staff can never mistake credit-applied revenue for cash.
16#======================================================================
17use strict;
18use warnings;
19
20use lib '/var/www/vhosts/3dshawn.com/affiliate.3dshawn.com';
21use CGI;
22use MODS::Template;
23use MODS::DBConnect;
24use MODS::Login;
25use MODS::AffSoft::Config;
26use MODS::AffSoft::Wrapper;
27use MODS::AffSoft::Admin;
28use MODS::AffSoft::Billing;
29
30my $q = CGI->new;
31my $form = $q->Vars;
32my $auth = MODS::Login->new;
33my $wrap = MODS::AffSoft::Wrapper->new;
34my $tfile = MODS::Template->new;
35my $db = MODS::DBConnect->new;
36my $cfg = MODS::AffSoft::Config->new;
37my $admin = MODS::AffSoft::Admin->new;
38my $bill = MODS::AffSoft::Billing->new;
39my $DB = $cfg->settings('database_name');
40
41$| = 1;
42my $userinfo = $auth->login_verify();
43if (!$userinfo) {
44 print "Status: 302 Found\nLocation: /login.cgi\n\n";
45 exit;
46}
47$admin->require_admin($userinfo);
48require MODS::AffSoft::Permissions;
49my $perm = MODS::AffSoft::Permissions->new;
50
51my $entry = ($ENV{SCRIPT_NAME} || '') =~ m{/([^/]+)\.cgi$} ? $1 : 'admin_billing';
52
53if ($entry eq 'admin_billing_action') {
54 $perm->require_feature($userinfo, 'admin_edit_billing');
55 _handle_action();
56 exit;
57}
58
59$perm->require_feature($userinfo, 'admin_view_billing');
60
61# Two-tier visibility on this page:
62# - Manager / Editor (anyone with admin_view_billing) sees the per-user
63# panels: Recent invoices (with refund-as-credit) and Credit holders
64# (with grant-credit). These power day-to-day user support.
65# - Only super-admin sees the platform-wide aggregates: cash revenue,
66# MRR/ARR, projected month-end, signups chart, plan distribution.
67# is_super_admin() reads users.is_super_admin lazily and caches on
68# $userinfo -- login_verify intentionally doesn't include the flag.
69my $is_super = $perm->is_super_admin($userinfo);
70
71my $tutorial_mode = ($form->{tutorial} && $form->{tutorial} eq '1') ? 1 : 0;
72
73# Month selector. Param is 'month' as YYYY-MM (e.g. 2026-04). Defaults
74# to the current calendar month. Anything else falls back silently
75# rather than 500-ing -- this is a query-string toggle, not a form.
76my ($sel_year, $sel_month) = _parse_month_param($form->{month});
77
78my $dbh = $db->db_connect();
79my $schema_ready = $bill->schema_ready($db, $dbh, $DB);
80
81# Daily series powering the in-modal mini-charts on each banner tile.
82# Scoped to the SELECTED month so the chart matches the tile numbers
83# (one bar per day of that month). Computed first so it runs while the
84# DB connection is fresh -- admin_summary and the recent-invoices /
85# credit-holder queries that follow are heavier and can leave the
86# connection in a state where a subsequent GROUP BY fails on slow links.
87my @daily_billing;
88if ($schema_ready) {
89 my $period_start = sprintf('%04d-%02d-01', $sel_year, $sel_month);
90 my $days_in_sel = _days_in_month($sel_year, $sel_month);
91 my %by_date;
92 my @rows = $db->db_readwrite_multiple($dbh, qq~
93 SELECT DATE(paid_at) AS d,
94 COALESCE(SUM(cash_paid_cents),0) AS cash,
95 COALESCE(SUM(credit_applied_cents),0) AS credit,
96 COUNT(*) AS invoices
97 FROM `${DB}`.invoices
98 WHERE status='paid' AND paid_at IS NOT NULL
99 AND paid_at >= '$period_start 00:00:00'
100 AND paid_at < DATE_ADD('$period_start 00:00:00', INTERVAL 1 MONTH)
101 GROUP BY DATE(paid_at)
102 ~, $ENV{SCRIPT_NAME}, __LINE__);
103 foreach my $r (@rows) { $by_date{$r->{d} || ''} = $r; }
104 for (my $d = 1; $d <= $days_in_sel; $d++) {
105 my $ymd = sprintf('%04d-%02d-%02d', $sel_year, $sel_month, $d);
106 my $r = $by_date{$ymd} || {};
107 push @daily_billing, {
108 date => $ymd,
109 cash => int(($r->{cash} || 0) / 100),
110 credit => int(($r->{credit} || 0) / 100),
111 invoices => $r->{invoices} || 0,
112 };
113 }
114}
115my $daily_billing_json = _ab_to_json_array(\@daily_billing);
116
117my $summary = $schema_ready ? $bill->admin_summary($db, $dbh, $DB, $sel_year, $sel_month) : {};
118my @recent_invoices_raw = $schema_ready ? $bill->admin_recent_invoices($db, $dbh, $DB, 30) : ();
119my @credit_holders_raw = $schema_ready ? $bill->admin_credit_holders($db, $dbh, $DB, 25) : ();
120my $signups_daily = $schema_ready ? $bill->admin_signups_daily($db, $dbh, $DB, 30) : [];
121my $signups_monthly = $schema_ready ? $bill->admin_signups_monthly($db, $dbh, $DB, 12) : [];
122
123# Format invoice rows for the table.
124my @recent_invoices;
125foreach my $r (@recent_invoices_raw) {
126 my $status = $r->{status} || 'open';
127 my $issued = $r->{issued_at} || $r->{created_at} || '';
128 push @recent_invoices, {
129 id => $r->{id},
130 invoice_number => $r->{invoice_number} || ('INV-' . $r->{id}),
131 user_id => $r->{user_id},
132 user_label => ($r->{display_name} || $r->{email} || ('User #' . $r->{user_id})),
133 user_email => $r->{email} || '',
134 amount_due_display => $bill->fmt_money($r->{amount_due_cents} || 0),
135 credit_applied_display => $bill->fmt_money($r->{credit_applied_cents} || 0),
136 cash_paid_display => $bill->fmt_money($r->{cash_paid_cents} || 0),
137 cash_paid_cents => $r->{cash_paid_cents} || 0,
138 status => $status,
139 is_paid => $status eq 'paid' ? 1 : 0,
140 is_open => $status eq 'open' ? 1 : 0,
141 is_failed => $status eq 'failed' ? 1 : 0,
142 is_refunded => $status eq 'refunded' ? 1 : 0,
143 is_void => $status eq 'void' ? 1 : 0,
144 can_refund => ($status eq 'paid' && ($r->{cash_paid_cents} || 0) > 0) ? 1 : 0,
145 issued_at => $issued,
146 issued_at_epoch => _abil_epoch($issued),
147 paid_at => $r->{paid_at} || '-',
148 paid_at_epoch => _abil_epoch($r->{paid_at}),
149 };
150}
151
152# Parse a MySQL DATETIME or DATE to an epoch second; 0 on failure. Kept
153# next to the tvars build so the tzLocalize spans can render the correct
154# viewer-local timestamp against the raw string shown as the fallback.
155sub _abil_epoch {
156 my $s = shift; return 0 unless defined $s;
157 if ($s =~ /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})/) {
158 require Time::Local;
159 return eval { Time::Local::timelocal($6, $5, $4, $3, $2 - 1, $1 - 1900) } || 0;
160 }
161 if ($s =~ /^(\d{4})-(\d{2})-(\d{2})$/) {
162 require Time::Local;
163 return eval { Time::Local::timelocal(0, 0, 0, $3, $2 - 1, $1 - 1900) } || 0;
164 }
165 return 0;
166}
167
168# Credit-holder rows.
169my @credit_holders;
170foreach my $r (@credit_holders_raw) {
171 push @credit_holders, {
172 user_id => $r->{user_id},
173 user_label => ($r->{display_name} || $r->{email} || ('User #' . $r->{user_id})),
174 user_email => $r->{email} || '',
175 balance_cents => $r->{balance_cents} || 0,
176 balance_display => $bill->fmt_money($r->{balance_cents} || 0),
177 is_positive => (($r->{balance_cents} || 0) > 0) ? 1 : 0,
178 is_negative => (($r->{balance_cents} || 0) < 0) ? 1 : 0,
179 };
180}
181
182# Plan breakdown for the donut-ish list.
183my @plan_breakdown;
184my %tier_color = (
185 free=>'#94a3b8', starter=>'#60a5fa', pro=>'#a78bfa', studio=>'#fbbf24'
186);
187my $plan_total = 0;
188foreach my $r (@{ $summary->{plan_breakdown} || [] }) { $plan_total += $r->{n}; }
189foreach my $r (@{ $summary->{plan_breakdown} || [] }) {
190 my $pct = $plan_total ? sprintf('%.1f', ($r->{n} / $plan_total) * 100) : '0.0';
191 push @plan_breakdown, {
192 tier => $r->{tier},
193 tier_label => ucfirst($r->{tier}),
194 count => $r->{n},
195 pct => $pct,
196 color => $tier_color{ $r->{tier} } || '#94a3b8',
197 };
198}
199
200$db->db_disconnect($dbh);
201
202# ---- Projected monthly earnings -------------------------------------
203# For the CURRENT month: linear pace extrapolation + scheduled renewals.
204# For PAST months: the month is closed; "projected" == actual cash
205# received that month and days_elapsed == days_in_month.
206my ($proj_total_cents, $pace_only_cents,
207 $days_elapsed, $days_in_month, $days_left,
208 $expected_subs_cents) = _project_month_earnings($summary, $sel_year, $sel_month);
209
210# Build the month-selector dropdown options. 24 months back from today.
211my @month_options = _build_month_options($sel_year, $sel_month, 24);
212
213# Format signup chart series for JSON.
214my $signups_daily_json = _ab_to_json_array($signups_daily);
215my $signups_monthly_json = _ab_to_json_array($signups_monthly);
216my $signups_total_30d = 0;
217my $signups_paid_30d = 0;
218foreach my $row (@$signups_daily) {
219 $signups_total_30d += $row->{total};
220 $signups_paid_30d += $row->{paid};
221}
222
223my $tvars = {
224 user_id => $userinfo->{user_id},
225 is_super_admin => $is_super,
226 not_super_admin => $is_super ? 0 : 1,
227
228 # Month-selector state
229 sel_period_label => _period_label($sel_year, $sel_month),
230 sel_period_ym => sprintf('%04d-%02d', $sel_year, $sel_month),
231 is_current_month => $summary->{is_current_month} ? 1 : 0,
232 not_current_month => $summary->{is_current_month} ? 0 : 1,
233 month_options => \@month_options,
234
235 # Cash / credit / liability tiles -- all scoped to the selected month.
236 cash_mtd => $bill->fmt_money($summary->{cash_revenue_mtd_cents} || 0),
237 credit_mtd => $bill->fmt_money($summary->{credit_consumed_mtd_cents} || 0),
238 outstanding_credit => $bill->fmt_money($summary->{outstanding_credit_cents} || 0),
239
240 # Projected earnings tile
241 projected_month => $bill->fmt_money($proj_total_cents),
242 projected_pace_only => $bill->fmt_money($pace_only_cents),
243 projected_subs_due => $bill->fmt_money($expected_subs_cents),
244 projection_days_left => $days_left,
245 projection_days_elap => $days_elapsed,
246 projection_days_in_m => $days_in_month,
247
248 # Signups module
249 signups_daily_json => $signups_daily_json,
250 signups_monthly_json => $signups_monthly_json,
251 signups_total_30d => $signups_total_30d,
252 signups_paid_30d => $signups_paid_30d,
253 signups_free_30d => $signups_total_30d - $signups_paid_30d,
254 has_signups => scalar(@$signups_daily) ? 1 : 0,
255
256 # Subscription counts
257 active_subs => $summary->{active_subs} || 0,
258 trialing_subs => $summary->{trialing_subs} || 0,
259 past_due_subs => $summary->{past_due_subs} || 0,
260 canceled_subs_30d => $summary->{canceled_subs_30d}|| 0,
261
262 # MRR / ARR
263 mrr_display => $bill->fmt_money($summary->{mrr_cents} || 0),
264 arr_display => $bill->fmt_money($summary->{arr_cents} || 0),
265
266 # Breakdowns / tables
267 plan_breakdown => \@plan_breakdown,
268 has_plan_breakdown => scalar(@plan_breakdown) ? 1 : 0,
269 recent_invoices => \@recent_invoices,
270 has_recent_invoices => scalar(@recent_invoices) ? 1 : 0,
271 credit_holders => \@credit_holders,
272 has_credit_holders => scalar(@credit_holders) ? 1 : 0,
273
274 # Banners
275 schema_ready => $schema_ready ? 1 : 0,
276 schema_missing => $schema_ready ? 0 : 1,
277
278 # Daily series feeding the KPI-modal area charts
279 daily_billing_json => $daily_billing_json,
280 has_daily_billing => scalar(@daily_billing) ? 1 : 0,
281
282 # Tutorial mode
283 tutorial_mode => $tutorial_mode,
284 not_tutorial_mode => $tutorial_mode ? 0 : 1,
285};
286
287# ---- Tutorial-mode overlay -----------------------------------------
288if ($tutorial_mode) {
289 $tvars->{cash_mtd} = '$18,440.00';
290 $tvars->{credit_mtd} = '$1,284.00';
291 $tvars->{outstanding_credit} = '$3,612.00';
292 $tvars->{projected_month} = '$44,920.00';
293 $tvars->{projected_pace_only}= '$36,880.00';
294 $tvars->{projected_subs_due} = '$8,040.00';
295 $tvars->{projection_days_left}= 19;
296 $tvars->{projection_days_elap}= 12;
297 $tvars->{projection_days_in_m}= 31;
298 $tvars->{active_subs} = 1089;
299 $tvars->{trialing_subs} = 24;
300 $tvars->{past_due_subs} = 11;
301 $tvars->{canceled_subs_30d} = 18;
302 $tvars->{mrr_display} = '$31,420.00';
303 $tvars->{arr_display} = '$377,040.00';
304
305 # Sample signup data -- mix of free and paid tiers, gentle weekly cadence.
306 my @sample_daily;
307 for (my $i = 29; $i >= 0; $i--) {
308 my @t = localtime(time - $i * 86400);
309 my $ymd = sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]);
310 my $dow = $t[6];
311 my $free = (($dow == 0 || $dow == 6) ? 14 : 22) + int(rand(6)) - 2;
312 my $starter = (($dow == 0 || $dow == 6) ? 2 : 4) + int(rand(2));
313 my $pro = (($dow == 0 || $dow == 6) ? 1 : 2) + int(rand(2));
314 my $studio = int(rand(2));
315 $free = 0 if $free < 0; $starter = 0 if $starter < 0;
316 $pro = 0 if $pro < 0; $studio = 0 if $studio < 0;
317 my $paid = $starter + $pro + $studio;
318 push @sample_daily, {
319 date => $ymd, free => $free,
320 starter => $starter, pro => $pro, studio => $studio,
321 paid => $paid, total => $free + $paid,
322 };
323 }
324 $tvars->{signups_daily_json} = _ab_to_json_array(\@sample_daily);
325 my @sample_monthly;
326 my @t = localtime(time);
327 my ($y, $m) = ($t[5]+1900, $t[4]+1);
328 for (my $i = 11; $i >= 0; $i--) {
329 my $bm = $m - $i; my $by = $y;
330 while ($bm <= 0) { $bm += 12; $by--; }
331 my $free = 400 + int(rand(120));
332 my $starter = 70 + int(rand(20));
333 my $pro = 32 + int(rand(12));
334 my $studio = 8 + int(rand(6));
335 my $paid = $starter + $pro + $studio;
336 push @sample_monthly, {
337 month => sprintf('%04d-%02d', $by, $bm),
338 free => $free, starter => $starter, pro => $pro, studio => $studio,
339 paid => $paid, total => $free + $paid,
340 };
341 }
342 $tvars->{signups_monthly_json} = _ab_to_json_array(\@sample_monthly);
343 my $t30 = 0; my $p30 = 0;
344 foreach my $r (@sample_daily) { $t30 += $r->{total}; $p30 += $r->{paid}; }
345 $tvars->{signups_total_30d} = $t30;
346 $tvars->{signups_paid_30d} = $p30;
347 $tvars->{signups_free_30d} = $t30 - $p30;
348 $tvars->{has_signups} = 1;
349
350 # Sample month-selector state
351 $tvars->{sel_period_label} = _period_label($y, $m);
352 $tvars->{sel_period_ym} = sprintf('%04d-%02d', $y, $m);
353 $tvars->{is_current_month} = 1;
354 $tvars->{not_current_month} = 0;
355 $tvars->{month_options} = [ _build_month_options($y, $m, 24) ];
356
357 $tvars->{plan_breakdown} = [
358 { tier=>'free', tier_label=>'Free', count=>612, pct=>'56.2', color=>'#94a3b8' },
359 { tier=>'starter', tier_label=>'Starter', count=>248, pct=>'22.8', color=>'#60a5fa' },
360 { tier=>'pro', tier_label=>'Pro', count=>178, pct=>'16.3', color=>'#a78bfa' },
361 { tier=>'studio', tier_label=>'Studio', count=>51, pct=>'4.7', color=>'#fbbf24' },
362 ];
363 $tvars->{has_plan_breakdown} = 1;
364
365 $tvars->{recent_invoices} = [
366 { id=>4012, invoice_number=>'INV-0001247-202605', user_id=>1247,
367 user_label=>'Rune Caster', user_email=>'rune.caster@example.com',
368 amount_due_display=>'$29.00', credit_applied_display=>'$12.00',
369 cash_paid_display=>'$17.00', cash_paid_cents=>1700,
370 status=>'paid', is_paid=>1, is_open=>0, is_failed=>0, is_refunded=>0, is_void=>0,
371 can_refund=>1, issued_at=>'2026-05-12', paid_at=>'2026-05-12' },
372 { id=>4011, invoice_number=>'INV-0001192-202605', user_id=>1192,
373 user_label=>'Maya R.', user_email=>'maya.r@example.com',
374 amount_due_display=>'$29.00', credit_applied_display=>'$0.00',
375 cash_paid_display=>'$29.00', cash_paid_cents=>2900,
376 status=>'paid', is_paid=>1, is_open=>0, is_failed=>0, is_refunded=>0, is_void=>0,
377 can_refund=>1, issued_at=>'2026-05-12', paid_at=>'2026-05-12' },
378 { id=>4010, invoice_number=>'INV-0001088-202605', user_id=>1088,
379 user_label=>'Bench Hammer', user_email=>'bench.hammer@example.com',
380 amount_due_display=>'$9.00', credit_applied_display=>'$0.00',
381 cash_paid_display=>'$9.00', cash_paid_cents=>900,
382 status=>'paid', is_paid=>1, is_open=>0, is_failed=>0, is_refunded=>0, is_void=>0,
383 can_refund=>1, issued_at=>'2026-05-12', paid_at=>'2026-05-12' },
384 { id=>4009, invoice_number=>'INV-0000987-202605', user_id=>987,
385 user_label=>'Priya T.', user_email=>'priya.t@example.com',
386 amount_due_display=>'$29.00', credit_applied_display=>'$0.00',
387 cash_paid_display=>'$0.00', cash_paid_cents=>0,
388 status=>'failed', is_paid=>0, is_open=>0, is_failed=>1, is_refunded=>0, is_void=>0,
389 can_refund=>0, issued_at=>'2026-05-12', paid_at=>'-' },
390 { id=>4008, invoice_number=>'INV-0001247-202604', user_id=>1247,
391 user_label=>'Rune Caster', user_email=>'rune.caster@example.com',
392 amount_due_display=>'$29.00', credit_applied_display=>'$0.00',
393 cash_paid_display=>'$29.00', cash_paid_cents=>2900,
394 status=>'refunded', is_paid=>0, is_open=>0, is_failed=>0, is_refunded=>1, is_void=>0,
395 can_refund=>0, issued_at=>'2026-04-12', paid_at=>'2026-04-12' },
396 ];
397 $tvars->{has_recent_invoices} = 1;
398
399 $tvars->{credit_holders} = [
400 { user_id=>1247, user_label=>'Rune Caster', user_email=>'rune.caster@example.com',
401 balance_cents=>2900, balance_display=>'$29.00', is_positive=>1, is_negative=>0 },
402 { user_id=>1192, user_label=>'Maya R.', user_email=>'maya.r@example.com',
403 balance_cents=>1500, balance_display=>'$15.00', is_positive=>1, is_negative=>0 },
404 { user_id=>987, user_label=>'Priya T.', user_email=>'priya.t@example.com',
405 balance_cents=>1000, balance_display=>'$10.00', is_positive=>1, is_negative=>0 },
406 { user_id=>1088, user_label=>'Bench Hammer', user_email=>'bench.hammer@example.com',
407 balance_cents=>500, balance_display=>'$5.00', is_positive=>1, is_negative=>0 },
408 ];
409 $tvars->{has_credit_holders} = 1;
410
411 $tvars->{schema_ready} = 1;
412 $tvars->{schema_missing} = 0;
413}
414
415print "Content-Type: text/html; charset=utf-8\nCache-Control: no-store, no-cache, must-revalidate, max-age=0\nPragma: no-cache\nExpires: 0\n\n";
416
417my $body = join('', $tfile->template('webstls_admin_billing.html', $tvars, $userinfo));
418
419$wrap->render({
420 userinfo => $userinfo,
421 page_key => 'admin_billing',
422 title => 'Admin &middot; Billing',
423 body => $body,
424 extra_js => ['/assets/javascript/graphs.js'],
425});
426
427#----------------------------------------------------------------------
428# Monthly-earnings projection.
429#
430# Current month -> linear pace extrapolation + scheduled renewals.
431# Past months -> month is closed; "projected" equals the actual cash
432# that landed that month (days_elapsed == days_in_month,
433# days_left == 0, expected_subs == 0).
434#
435# Returns: (projected_total_cents, pace_only_cents,
436# days_elapsed_including_today, days_in_month, days_left,
437# expected_subscription_renewals_remaining_this_month)
438sub _project_month_earnings {
439 my ($s, $year, $month) = @_;
440 $s ||= {};
441 my $mtd_cents = $s->{cash_revenue_mtd_cents} || 0;
442 my $expected = $s->{expected_subs_remaining_cents} || 0;
443 my $is_current = $s->{is_current_month} ? 1 : 0;
444
445 my $days_in_month = _days_in_month($year, $month);
446 my ($days_elapsed, $days_left);
447
448 if ($is_current) {
449 my @t = localtime(time);
450 $days_elapsed = $t[3]; # day-of-month, includes today
451 $days_left = $days_in_month - $days_elapsed;
452 } else {
453 $days_elapsed = $days_in_month;
454 $days_left = 0;
455 }
456
457 my $pace_only = 0;
458 if ($days_elapsed > 0) {
459 $pace_only = int( ($mtd_cents * $days_in_month) / $days_elapsed );
460 }
461 my $pace_remaining = $pace_only - $mtd_cents;
462 $pace_remaining = 0 if $pace_remaining < 0;
463 my $projected_total = $is_current
464 ? ($mtd_cents + $pace_remaining + $expected)
465 : $mtd_cents;
466
467 return ($projected_total, $pace_only,
468 $days_elapsed, $days_in_month, $days_left, $expected);
469}
470
471sub _days_in_month {
472 my ($year, $month) = @_;
473 my @days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
474 if ($month == 2) {
475 my $leap = ($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0);
476 return $leap ? 29 : 28;
477 }
478 return $days[$month - 1];
479}
480
481# Parse `month` query string. Accepts YYYY-MM; anything else falls back
482# to the current calendar month. Returns ($year, $month).
483sub _parse_month_param {
484 my ($raw) = @_;
485 my @t = localtime(time);
486 my $cur_year = $t[5] + 1900;
487 my $cur_month = $t[4] + 1;
488 return ($cur_year, $cur_month) unless defined $raw && $raw =~ /^(\d{4})-(\d{1,2})$/;
489 my ($y, $m) = ($1 + 0, $2 + 0);
490 return ($cur_year, $cur_month) unless $y >= 2000 && $y <= 2100;
491 return ($cur_year, $cur_month) unless $m >= 1 && $m <= 12;
492 return ($y, $m);
493}
494
495# Long-form label for the selected period -- "May 2026".
496sub _period_label {
497 my ($year, $month) = @_;
498 my @names = qw(January February March April May June July August September October November December);
499 return $names[$month - 1] . ' ' . $year;
500}
501
502# Build the dropdown options list for the month picker. Most-recent
503# month first. Each entry: { ym => 'YYYY-MM', label => 'Month YYYY',
504# selected_attr => ' selected' if it matches the requested period }.
505sub _build_month_options {
506 my ($sel_year, $sel_month, $count) = @_;
507 $count ||= 24;
508 my @t = localtime(time);
509 my $y = $t[5] + 1900;
510 my $m = $t[4] + 1;
511 my @out;
512 for (my $i = 0; $i < $count; $i++) {
513 my $ym = sprintf('%04d-%02d', $y, $m);
514 my $is_sel = ($y == $sel_year && $m == $sel_month) ? 1 : 0;
515 push @out, {
516 ym => $ym,
517 label => _period_label($y, $m),
518 selected_attr => $is_sel ? ' selected' : '',
519 is_selected => $is_sel,
520 };
521 $m--;
522 if ($m == 0) { $m = 12; $y--; }
523 }
524 return @out;
525}
526
527# Tiny JSON-array encoder for the daily_billing series. Local copy
528# (prefixed _ab_) so admin_billing.cgi stays self-contained and we
529# don't accidentally rely on a helper that might move.
530sub _ab_to_json_array {
531 my ($aref) = @_;
532 $aref ||= [];
533 my @out;
534 foreach my $row (@$aref) {
535 my @pairs;
536 foreach my $k (sort keys %$row) {
537 my $v = $row->{$k};
538 if (!defined $v) { push @pairs, '"'.$k.'":null'; next; }
539 if ($v =~ /^-?(?:\d+\.?\d*|\.\d+)$/) { push @pairs, '"'.$k.'":'.($v+0); next; }
540 $v =~ s/\\/\\\\/g; $v =~ s/"/\\"/g;
541 $v =~ s/\r/\\r/g; $v =~ s/\n/\\n/g; $v =~ s/\t/\\t/g;
542 $v =~ s|</|<\\/|g;
543 push @pairs, '"'.$k.'":"'.$v.'"';
544 }
545 push @out, '{' . join(',', @pairs) . '}';
546 }
547 return '[' . join(',', @out) . ']';
548}
549
550#======================================================================
551# admin_billing_action entry: POST handler
552# act=refund_as_credit -- credit invoice's cash_paid back to user's
553# credit_ledger and mark invoice refunded.
554# act=grant_credit -- insert a positive credit_ledger row.
555# act=void_invoice -- mark an open/failed invoice as void.
556#======================================================================
557sub _handle_action {
558 my $admin_id = $userinfo->{user_id};
559 $admin_id =~ s/[^0-9]//g;
560
561 my $act = defined $form->{act} ? $form->{act} : '';
562
563 my $dbh = $db->db_connect();
564 unless ($bill->schema_ready($db, $dbh, $DB)) {
565 $db->db_disconnect($dbh);
566 _act_redirect('/admin_billing.cgi?err=schema');
567 return;
568 }
569
570 if ($act eq 'refund_as_credit') {
571 my $invoice_id = defined $form->{invoice_id} ? $form->{invoice_id} : '';
572 $invoice_id =~ s/[^0-9]//g;
573 unless ($invoice_id) {
574 $db->db_disconnect($dbh);
575 _act_redirect('/admin_billing.cgi?err=bad_invoice');
576 return;
577 }
578
579 my $inv = $bill->get_invoice($db, $dbh, $DB, $invoice_id);
580 unless ($inv && $inv->{id} && $inv->{status} eq 'paid' && ($inv->{cash_paid_cents} || 0) > 0) {
581 $db->db_disconnect($dbh);
582 _act_redirect('/admin_billing.cgi?err=not_refundable');
583 return;
584 }
585
586 my $cash = $inv->{cash_paid_cents};
587 my $note = 'Refund for invoice ' . ($inv->{invoice_number} || $inv->{id}) . ' issued as account credit.';
588
589 # 1) credit_ledger row: positive grant
590 $bill->grant_credit($db, $dbh, $DB,
591 user_id => $inv->{user_id},
592 amount_cents => $cash,
593 reason => 'refund',
594 related_invoice_id => $inv->{id},
595 granted_by_user_id => $admin_id,
596 note => $note,
597 );
598
599 # 2) mark the invoice as refunded so the seller billing page
600 # surfaces the "Refunded as credit" pill on this row.
601 $db->db_readwrite($dbh, qq~
602 UPDATE `${DB}`.invoices
603 SET status='refunded'
604 WHERE id='$inv->{id}'
605 ~, $ENV{SCRIPT_NAME}, __LINE__);
606
607 $db->db_disconnect($dbh);
608 _act_redirect('/admin_billing.cgi?ok=refunded');
609 return;
610 }
611
612 if ($act eq 'grant_credit') {
613 my $target_uid = defined $form->{user_id} ? $form->{user_id} : '';
614 $target_uid =~ s/[^0-9]//g;
615 my $amount_cents = defined $form->{amount_cents}? $form->{amount_cents}: '';
616 $amount_cents =~ s/[^0-9]//g; # positive integer cents only
617 my $note = defined $form->{note} ? $form->{note} : '';
618 $note =~ s/[\r\n]+/ /g;
619 $note = substr($note, 0, 480);
620
621 unless ($target_uid && $amount_cents) {
622 $db->db_disconnect($dbh);
623 _act_redirect(_act_back($form, '/admin_billing.cgi', 'err=bad_grant'));
624 return;
625 }
626
627 $bill->grant_credit($db, $dbh, $DB,
628 user_id => $target_uid,
629 amount_cents => $amount_cents,
630 reason => 'manual_grant',
631 granted_by_user_id => $admin_id,
632 note => $note,
633 );
634
635 $db->db_disconnect($dbh);
636 _act_redirect(_act_back($form, '/admin_billing.cgi', 'ok=credit_granted'));
637 return;
638 }
639
640 if ($act eq 'void_invoice') {
641 my $invoice_id = defined $form->{invoice_id} ? $form->{invoice_id} : '';
642 $invoice_id =~ s/[^0-9]//g;
643 unless ($invoice_id) {
644 $db->db_disconnect($dbh);
645 _act_redirect('/admin_billing.cgi?err=bad_invoice');
646 return;
647 }
648 $db->db_readwrite($dbh, qq~
649 UPDATE `${DB}`.invoices
650 SET status='void'
651 WHERE id='$invoice_id' AND status IN ('open','failed','draft')
652 ~, $ENV{SCRIPT_NAME}, __LINE__);
653
654 $db->db_disconnect($dbh);
655 _act_redirect('/admin_billing.cgi?ok=voided');
656 return;
657 }
658
659 $db->db_disconnect($dbh);
660 _act_redirect('/admin_billing.cgi?err=unknown_act');
661}
662
663sub _act_redirect {
664 my $url = shift;
665 print "Status: 302 Found\nLocation: $url\n\n";
666}
667
668# Pick the redirect target: caller-supplied return_to (must be a same-site
669# absolute path; rejects protocol-relative // and full URLs) or fall back
670# to the per-action default. $suffix is the query-string flash, with or
671# without leading '?'.
672sub _act_back {
673 my ($f, $default, $suffix) = @_;
674 my $rt = defined $f->{return_to} ? $f->{return_to} : '';
675 if ($rt !~ m{^/[^/]} && $rt ne '/') { $rt = ''; } # reject //, http://, empty
676 my $base = $rt || $default;
677 return $base unless defined $suffix && length $suffix;
678 $suffix =~ s/^\?//;
679 my $sep = ($base =~ /\?/) ? '&' : '?';
680 return $base . $sep . $suffix;
681}