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

O Operator
Diff

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

added on local at 2026-07-11 18:36:16

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