Diff -- /var/www/vhosts/webstls.com/httpdocs/admin_billing.cgi

O Operator
Diff

/var/www/vhosts/webstls.com/httpdocs/admin_billing.cgi

added on WebSTLs (webstls.com) at 2026-07-01 22:26:15

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