Diff -- /var/www/vhosts/3dshawn.com/repricer.3dshawn.com/MODS/RePricer/Wrapper.pm
Diff

/var/www/vhosts/3dshawn.com/repricer.3dshawn.com/MODS/RePricer/Wrapper.pm

added on local at 2026-07-01 21:47:15

Added
+663
lines
Removed
-0
lines
Context
0
unchanged
Blobs
from
to a7d5c90a4fc3
Restore this content →
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.
1package MODS::RePricer::Wrapper;
2#======================================================================
3# RePricer — page wrapper.
4#
5# Renders the sidebar + topbar shell around a page's main content.
6# Uses MODS::Template for the shell template (repricer_wrapper.html
7# for logged-in pages, repricer_marketing.html for logged-out).
8#
9# Caller pattern:
10#
11# my $body = qq~ ...page body html... ~;
12# $wrap->render({
13# userinfo => $userinfo, # required for logged-in shell
14# page_key => 'dashboard', # marks the active sidebar item
15# title => 'Dashboard',
16# body => $body,
17# extra_js => ['/assets/javascript/graphs.js'], # optional
18# });
19#======================================================================
20
21use strict;
22use warnings;
23
24use MODS::Template;
25use MODS::DBConnect;
26use MODS::RePricer::Config;
27
28my $tfile = MODS::Template->new;
29my $config = MODS::RePricer::Config->new;
30my $db = MODS::DBConnect->new;
31
32# Bump this when a new entry is added to /changelog.cgi -- every user
33# whose users.changelog_last_seen_version is lower than this gets the
34# yellow "What's New" dot in their profile dropdown until they visit.
35use constant CURRENT_CHANGELOG_VERSION => '2026-06-03';
36
37# Sidebar nav: section headers + entries. Each entry has a key
38# matched against $page_key to set "active", an icon name (resolved
39# to inline SVG below), label, href, and optional badge.
40my @SIDEBAR = (
41 # Sidebar mirrors the profile dropdown in repricer_wrapper.html --
42 # same sections, same wording, same hrefs, same ordering so the
43 # two menus read as one family. Order: Studio > Insights > Account
44 # > Admin (admin-only). Admin section contains every platform-wide
45 # control surface.
46 #
47 # Per-row gating attrs (all optional):
48 # feature = permission_features.slug -- hide row from team
49 # members who lack the slug. Owners always pass.
50 # owner_only = 1 -- only the account owner (no owner_user_id) sees
51 # this row. Team members never see it regardless of role.
52 # Used for billing + team management + "danger zone" entries.
53 # admin_only = 1 -- hides from non-admin users entirely.
54 { section => 'Workspace' },
55 { key => 'dashboard', label => 'Dashboard', href => '/dashboard.cgi', icon => 'welcome' },
56 { key => 'calendar', label => 'Calendar', href => '/calendar.cgi', icon => 'calendar' },
57 { key => 'products', label => 'My Products', href => '/products.cgi', icon => 'models' },
58 { key => 'rules', label => 'Repricing Rules', href => '/repricing_rules.cgi', icon => 'optimize' },
59 { key => 'competitors', label => 'Competitor Tracking', href => '/competitors.cgi', icon => 'visitors' },
60 { key => 'price_history', label => 'Price History', href => '/price_history.cgi', icon => 'analytics' },
61 { key => 'marketplaces', label => 'Marketplace Accounts', href => '/marketplaces.cgi', icon => 'storefront' },
62
63 # (The WebSTLs "Reporting" block -- Sales Reports / Orders /
64 # Customers / Traffic / Optimization -- was removed because RePricer
65 # doesn't ship a buyer-facing storefront. The relevant repricer
66 # analytics are on /price_history.cgi and /admin_health.cgi.)
67
68 { section => 'Account' },
69 { key => 'profile', label => 'Profile', href => '/profile.cgi', icon => 'profile' },
70 { key => 'preferences', label => 'Preferences', href => '/preferences.cgi', icon => 'settings' },
71 { key => 'billing', label => 'Billing & Plan', href => '/billing.cgi', icon => 'billing', feature => 'manage_billing' },
72 { key => 'team', label => 'Team Members', href => '/team.cgi', icon => 'team', owner_only => 1 },
73 { key => 'changelog', label => "What's New", href => '/changelog.cgi', icon => 'analytics' },
74
75 { section => 'Admin', admin_only => 1 },
76 { key => 'admin_earnings', label => 'Earnings & Expenses', href => '/admin_earnings.cgi', icon => 'billing', super_admin_only => 1, tip => 'Revenue from paid invoices + manual expense ledger. Net + margin. Date range with this-month default.' },
77 { key => 'admin_funnels', label => 'Conversion Funnel', href => '/admin_funnels.cgi', icon => 'funnel',
78 admin_only => 1 },
79 { key => 'admin_traffic', label => 'Traffic Reports', href => '/admin_traffic.cgi', icon => 'analytics',
80 admin_only => 1, tip => 'Where visitors are coming from + globe + per-country drill.' },
81 { key => 'admin_messages', label => 'Support inbox', href => '/admin_messages.cgi', icon => 'messages',
82 admin_only => 1, feature => 'admin_view_messages' }, { key => 'admin_companies', label => 'All Companies', href => '/admin_companies.cgi', icon => 'building', admin_only => 1 },
83
84 { key => 'admin_users', label => 'All Users', href => '/admin_users.cgi', icon => 'admin',
85 admin_only => 1, feature => 'admin_view_users' },
86
87 { key => 'admin_teams', label => 'Team Members', href => '/admin_teams.cgi', icon => 'team',
88 admin_only => 1 },
89 { key => 'admin_billing', label => 'User Billing', href => '/admin_billing.cgi', icon => 'billing',
90 admin_only => 1, feature => 'admin_view_billing' },
91 # Pricing & Promotions is one sidebar entry covering BOTH the
92 # billing-packages catalogue and the platform-wide promotions list.
93 # The two pages share a tab nav at the top so the user can switch
94 # between them; both set page_key='admin_packages' so this entry
95 # stays highlighted across either URL.
96 { key => 'admin_packages', label => 'Pricing & Promotions', href => '/admin_packages.cgi', icon => 'billing',
97 admin_only => 1, super_admin_only => 1 },
98 # Tax: rates + marketplace-facilitator collection policy. Visible
99 # to all admins, but only super-admins can save changes (the CGI
100 # gates the POST handlers). Separate from Pricing & Promotions
101 # because tax is platform-wide compliance, not seller-facing
102 # pricing.
103 { key => 'admin_tax', label => 'Tax', href => '/admin_tax.cgi', icon => 'billing',
104 admin_only => 1 },
105 # (admin_categories sidebar entry removed 2026-06-21 -- categories
106 # were a buyer-storefront concept inherited from the WebSTLs fork
107 # and don't apply to RePricer's seller-side product catalog.)
108 { key => 'admin_seo', label => 'SEO', href => '/admin_seo.cgi', icon => 'seo',
109 admin_only => 1, feature => 'admin_view_seo' },
110 # Heatmaps now lives as a tab inside /admin_visitors.cgi (no
111 # separate sidebar entry). /admin_heatmap.cgi is still reachable
112 # at its direct URL and renders the same tab nav with Heatmaps
113 # highlighted.
114 { key => 'admin_chat', label => 'Chat', href => '/admin_chat.cgi', icon => 'chat',
115 admin_only => 1, feature => 'admin_chat' }, # Sandbox CCs for QA. Super-admin-only because a misused test card
116 # could be assigned to a real seller's account and silently
117 # "approve" their next charge. Staff with manage-billing get to see
118 # tests it; only the platform owner gets to create them.
119 { key => 'admin_test_cards', label => 'Test Credit Cards', href => '/admin_test_cards.cgi', icon => 'card',
120 admin_only => 1, super_admin_only => 1 },
121 { key => 'email_setup', label => 'Email Setup', href => '/admin_emails.cgi', icon => 'messages', admin_only => 1, super_admin_only => 1 },
122 # Repricer-specific admin pages added 2026-06-03.
123 { key => 'admin_health', label => 'Platform Health', href => '/admin_health.cgi', icon => 'dashboard',
124 admin_only => 1 },
125 { key => 'admin_search', label => 'Search', href => '/admin_search.cgi', icon => 'visitors',
126 admin_only => 1 },
127 # Platform-owner-only: edits Stripe keys / branding / email and
128 # other DB-backed settings. Regular admins do NOT see this row.
129 { key => 'admin_maintenance', label => 'Maintenance', href => '/admin_maintenance.cgi', icon => 'settings', super_admin_only => 1, tip => 'Lock the site for everyone except admins; edit the message users see while locked.' }, { key => 'admin_config', label => 'Configuration', href => '/admin_config.cgi', icon => 'settings',
130 admin_only => 1, super_admin_only => 1 },
131);
132
133sub new {
134 my ($class) = @_;
135 return bless({}, $class);
136}
137
138#----------------------------------------------------------------------
139# render(\%opts) — print the full page (Content-Type already sent
140# by the calling .cgi).
141#----------------------------------------------------------------------
142sub render {
143 my ($self, $opts) = @_;
144 $opts ||= {};
145
146 my $userinfo = $opts->{userinfo};
147 my $logged_in = $userinfo && $userinfo->{user_id} ? 1 : 0;
148
149 my $tvars = {
150 website_title => $config->settings('website_title'),
151 brand_name => $config->settings('brand_name'),
152 brand_tagline => $config->settings('brand_tagline'),
153 assets => $config->settings('assets'),
154 assets_css => $config->settings('assets_css'),
155 assets_js => $config->settings('assets_js'),
156 title => $opts->{title} || 'RePricer',
157 body => $opts->{body} || '',
158 extra_js => _format_scripts($opts->{extra_js}),
159 extra_css => _format_styles($opts->{extra_css}),
160 # SEO meta block (built below). Renders into repricer_wrapper.html
161 # / repricer_marketing.html at $meta_tags so every page emits a
162 # consistent <meta> set without each CGI having to know.
163 meta_tags => _build_meta_tags($opts),
164 };
165
166 if ($logged_in) {
167 $tvars->{user_id} = $userinfo->{user_id};
168 $tvars->{display_name} = $userinfo->{display_name};
169 $tvars->{email} = $userinfo->{email};
170 $tvars->{plan_tier} = ucfirst($userinfo->{plan_tier} || 'free');
171 $tvars->{initials} = _initials($userinfo->{display_name} || $userinfo->{email});
172
173 my $is_admin = $userinfo->{is_admin} || $userinfo->{_admin_is_admin} || 0;
174 $tvars->{is_admin} = $is_admin;
175 # Unread comments/reviews drive the red dot on the bell icon and
176 # the Messages entry in both menus. Querying once here so the
177 # sidebar builder + the topbar template both read the same number.
178 my $unread = _unread_messages_count($userinfo->{user_id}, $is_admin);
179 $tvars->{unread_messages_count} = $unread;
180 $tvars->{has_unread_messages} = $unread > 0 ? 1 : 0;
181 # Where the topbar Messages pill lands. Admins manage every
182 # storefront's tickets via the admin console; sellers only
183 # see their own threads at the customer-facing portal.
184 $tvars->{messages_href} = $is_admin ? '/admin_messages.cgi' : '/support.cgi';
185 # Live chats awaiting an admin reply. Drives the topbar pill
186 # so admins can't miss a visitor mid-conversation no matter
187 # what page they're on. Pill always renders for admins; the
188 # idle (blue) vs waiting (green/pulsing) state is gated on
189 # count. Clicking the waiting pill jumps straight to the
190 # longest-waiting chat so admins skip the console list.
191 my $chat_data = $is_admin ? _pending_chats_data() : { n => 0, first_id => 0 };
192 $tvars->{admin_chats_pending} = $chat_data->{n};
193 $tvars->{has_admin_chats_pending} = $chat_data->{n} > 0 ? 1 : 0;
194 $tvars->{admin_chats_first_id} = $chat_data->{first_id} || 0;
195 $tvars->{admin_chats_href} = $chat_data->{first_id}
196 ? "/admin_chat.cgi?chat=$chat_data->{first_id}"
197 : '/admin_chat.cgi';
198 $tvars->{sidebar} = _build_sidebar($opts->{page_key} || '', $is_admin, $unread, $userinfo);
199 $tvars->{dropdown_links} = _build_dropdown_links($is_admin, $unread, $userinfo);
200 $tvars->{impersonation_banner} = _impersonation_banner($userinfo);
201
202 # Per-user sidebar pref: applied as a class on <html> so the
203 # final layout is in place on first paint (no flash). Guarded
204 # against the user_settings.sidebar_collapsed column not having
205 # been added yet -- a missing-column SELECT would 500 the page.
206 my ($collapsed, $mobile_open) = _sidebar_pref($userinfo->{user_id});
207 my @cls;
208 push @cls, 'sidebar-collapsed' if $collapsed;
209 push @cls, 'mobile-nav-open' if $mobile_open;
210 $tvars->{html_class} = join(' ', @cls);
211 }
212
213 # Heatmap-view mode: when /admin_heatmap.cgi loads a page in its
214 # preview iframe it appends `heatmap_view=1` to the URL. We render
215 # that request as if the visitor were logged OUT so the DOM
216 # matches exactly what a real visitor saw -- otherwise the admin
217 # session would inject the studio sidebar wrapper and every stored
218 # selector would resolve to a different element. We also suppress
219 # track.js so the admin's preview clicks don't pollute analytics.
220 my $heatmap_view = ($ENV{QUERY_STRING} || '') =~ /(?:^|&)heatmap_view=1(?:&|$)/ ? 1 : 0;
221 $tvars->{heatmap_view} = $heatmap_view;
222
223 # Tutorial-embed mode: a [frame:/url] block inside a tutorial body
224 # loads the target URL in an iframe with ?tut_embed=1 appended. We
225 # strip the sidebar/topbar (same as heatmap_view does) so the
226 # iframe shows just the page content, not the whole studio shell.
227 my $tut_embed = ($ENV{QUERY_STRING} || '') =~ /(?:^|&)tut_embed=1(?:&|$)/ ? 1 : 0;
228 $tvars->{tut_embed} = $tut_embed;
229
230 my $template_file = ($logged_in && !$heatmap_view && !$tut_embed)
231 ? 'repricer_wrapper.html'
232 : 'repricer_marketing.html';
233
234 my @html = $tfile->template($template_file, $tvars, $userinfo);
235 print "@html";
236 return;
237}
238
239#======================================================================
240# Helpers
241#======================================================================
242
243sub _initials {
244 my ($name) = @_;
245 return '?' unless $name;
246 my @parts = split /[\s\@\.]+/, $name;
247 my $i = '';
248 $i .= uc(substr($parts[0], 0, 1)) if $parts[0];
249 $i .= uc(substr($parts[1], 0, 1)) if $parts[1];
250 return $i || uc(substr($name, 0, 1));
251}
252
253sub _format_scripts {
254 my ($list) = @_;
255 return '' unless $list && ref($list) eq 'ARRAY';
256 return join("\n", map { qq~<script src="$_"></script>~ } @$list);
257}
258
259sub _format_styles {
260 my ($list) = @_;
261 return '' unless $list && ref($list) eq 'ARRAY';
262 return join("\n", map { qq~<link rel="stylesheet" href="$_">~ } @$list);
263}
264
265# Cache the column-existence check so we don't run information_schema
266# on every page load. Under plain CGI this only saves work within a
267# single request; under FCGI/mod_perl it survives across requests.
268our $_sidebar_col_checked;
269our $_sidebar_col_exists;
270
271# Returns ($collapsed, $mobile_open) for the user's sidebar prefs.
272# Both default to 0 (expanded desktop, closed mobile drawer) when no
273# row exists or the migration columns are missing. sidebar_mobile_open
274# was added in a later migration so we guard for its absence.
275sub _sidebar_pref {
276 my ($user_id) = @_;
277 return (0, 0) unless $user_id;
278 $user_id =~ s/[^0-9]//g;
279 return (0, 0) unless $user_id;
280
281 my $DB = $config->settings('database_name');
282 my $dbh = $db->db_connect();
283 return (0, 0) unless $dbh;
284
285 unless ($_sidebar_col_checked) {
286 my $r = $db->db_readwrite($dbh, qq~
287 SELECT COUNT(*) AS n FROM information_schema.columns
288 WHERE table_schema='$DB'
289 AND table_name='user_settings'
290 AND column_name='sidebar_collapsed'
291 ~, $ENV{SCRIPT_NAME}, __LINE__);
292 $_sidebar_col_exists = ($r && $r->{n}) ? 1 : 0;
293 $_sidebar_col_checked = 1;
294 }
295
296 unless ($_sidebar_col_exists) {
297 $db->db_disconnect($dbh);
298 return (0, 0);
299 }
300
301 # Probe the optional mobile column (cheap, cached per-request).
302 my $mob_check = $db->db_readwrite($dbh, qq~
303 SELECT COUNT(*) AS n FROM information_schema.columns
304 WHERE table_schema='$DB'
305 AND table_name='user_settings'
306 AND column_name='sidebar_mobile_open'
307 ~, $ENV{SCRIPT_NAME}, __LINE__);
308 my $mob_extra = ($mob_check && $mob_check->{n}) ? ', sidebar_mobile_open' : '';
309
310 my $r = $db->db_readwrite($dbh, qq~
311 SELECT sidebar_collapsed$mob_extra
312 FROM `${DB}`.user_settings
313 WHERE user_id='$user_id'
314 LIMIT 1
315 ~, $ENV{SCRIPT_NAME}, __LINE__);
316 $db->db_disconnect($dbh);
317
318 my $collapsed = ($r && $r->{sidebar_collapsed}) ? 1 : 0;
319 my $mobile_open = ($r && $r->{sidebar_mobile_open}) ? 1 : 0;
320 return ($collapsed, $mobile_open);
321}
322
323
324sub _build_sidebar {
325 my ($active_key, $is_admin, $unread_messages, $userinfo) = @_;
326 $unread_messages ||= 0;
327 my $html = '';
328 my $pending_section; # buffered header; emitted when a child row gets through
329 my $is_team_member = ($userinfo && $userinfo->{owner_user_id}) ? 1 : 0;
330
331 foreach my $row (@SIDEBAR) {
332 # Admin entries (links AND section headers) are gated -- sellers
333 # must never see them. Hide the rows entirely (not just disable)
334 # so the page keys do not leak in HTML for non-admins to find.
335 next if $row->{admin_only} && !$is_admin;
336
337 if ($row->{section}) {
338 # Buffer the header; we only commit it once a visible child
339 # follows. Prevents dangling "Reporting" labels when every
340 # child is hidden by role.
341 $pending_section = $row->{section};
342 next;
343 }
344
345 # owner_only rows are visible only to the actual account owner
346 # (billing, team management, ...). Team members and impersonated
347 # admins are blocked here so the menu cannot leak them.
348 next if $row->{owner_only} && $is_team_member;
349
350 # super_admin_only rows are visible only to the platform owner
351 # (users.is_super_admin=1). Regular admins managing users / billing
352 # still see all the other admin rows but never this one.
353 if ($row->{super_admin_only}) {
354 require MODS::RePricer::Permissions;
355 next unless MODS::RePricer::Permissions->new->is_super_admin($userinfo);
356 }
357
358 # feature gate: skip if user lacks the slug. _has_user_feature
359 # short-circuits for owners (NULL permission_groups_id).
360 next if $row->{feature} && !_has_user_feature($userinfo, $row->{feature});
361
362 if (defined $pending_section) {
363 $html .= qq~<div class="sidebar-section-label">$pending_section</div>\n~;
364 $pending_section = undef;
365 }
366
367 my $cls = ($row->{key} eq $active_key) ? 'sidebar-link active' : 'sidebar-link';
368 my $svg = _icon($row->{icon});
369 my $badge = $row->{badge} ? qq~<span class="badge">$row->{badge}</span>~ : '';
370 # Live unread dot on the Messages row only -- the dot is omitted
371 # when there are zero unread comments/reviews so the navigation
372 # never shows a permanent "alert" indicator.
373 my $unread_dot = '';
374 if ($row->{key} && $row->{key} eq 'messages' && $unread_messages > 0) {
375 $unread_dot = qq~<span class="menu-dot" title="$unread_messages unread"></span>~;
376 }
377 $html .= qq~<a class="$cls" href="$row->{href}">$svg<span>$row->{label}</span>$unread_dot$badge</a>\n~;
378 }
379 return $html;
380}
381
382# Build the profile-dropdown links from the SAME @SIDEBAR data the
383# left sidebar uses. This guarantees the two menus stay in lockstep
384# whenever items are added / renamed / removed -- never hand-edit the
385# dropdown HTML directly. Section headers become <div class="profile-
386# dropdown-section">, divider rows are inserted before each section
387# (except the first), and admin-only items get the .profile-admin
388# class so they render in the admin red/orange accent like before.
389sub _build_dropdown_links {
390 my ($is_admin, $unread_messages, $userinfo) = @_;
391 $unread_messages ||= 0;
392 my $html = '';
393 my $emitted_first_section = 0;
394 my $pending_section;
395 my $pending_divider = 0;
396 my $is_team_member = ($userinfo && $userinfo->{owner_user_id}) ? 1 : 0;
397
398 foreach my $row (@SIDEBAR) {
399 next if $row->{admin_only} && !$is_admin;
400
401 if ($row->{section}) {
402 # Buffer the header + its divider; emit only when a child
403 # row gets through. Otherwise the dropdown shows lone
404 # "Reporting" headers with nothing under them.
405 $pending_section = $row->{section};
406 $pending_divider = $emitted_first_section ? 1 : 0;
407 next;
408 }
409
410 next if $row->{owner_only} && $is_team_member;
411 if ($row->{super_admin_only}) {
412 require MODS::RePricer::Permissions;
413 next unless MODS::RePricer::Permissions->new->is_super_admin($userinfo);
414 }
415 next if $row->{feature} && !_has_user_feature($userinfo, $row->{feature});
416
417 if (defined $pending_section) {
418 $html .= qq~<div class="profile-dropdown-divider"></div>\n~ if $pending_divider;
419 $html .= qq~<div class="profile-dropdown-section">$pending_section</div>\n~;
420 $emitted_first_section = 1;
421 $pending_section = undef;
422 $pending_divider = 0;
423 }
424
425 my $svg = _icon($row->{icon});
426 my $admin_c = $row->{admin_only} ? ' class="profile-admin"' : '';
427 my $unread_dot = '';
428 if ($row->{key} && $row->{key} eq 'messages' && $unread_messages > 0) {
429 $unread_dot = qq~<span class="menu-dot" style="margin-left:auto" title="$unread_messages unread"></span>~;
430 }
431 if ($row->{key} && $row->{key} eq 'changelog' && _changelog_has_news($userinfo)) {
432 $unread_dot = qq~<span class="menu-dot" style="margin-left:auto;background:#fbbf24" title="New release notes"></span>~;
433 }
434 $html .= qq~<a href="$row->{href}"$admin_c><span class="dropdown-icon">$svg</span> $row->{label}$unread_dot</a>\n~;
435 }
436 return $html;
437}
438
439# Returns true if the user hasn't yet seen the current changelog
440# version. Cheap query, guarded against the column not existing on
441# pre-migration installs (just returns 0 so the dot stays off).
442our $_chlog_col_checked;
443our $_chlog_col_exists;
444sub _changelog_has_news {
445 my ($userinfo) = @_;
446 return 0 unless $userinfo && $userinfo->{user_id};
447 my $uid = $userinfo->{user_id}; $uid =~ s/[^0-9]//g;
448 return 0 unless $uid;
449 my $DB = $config->settings('database_name');
450 my $dbh = $db->db_connect();
451 return 0 unless $dbh;
452 unless ($_chlog_col_checked) {
453 my $r = $db->db_readwrite($dbh, qq~
454 SELECT COUNT(*) AS n FROM information_schema.columns
455 WHERE table_schema='$DB' AND table_name='users'
456 AND column_name='changelog_last_seen_version'
457 ~, $ENV{SCRIPT_NAME}, __LINE__);
458 $_chlog_col_exists = ($r && $r->{n}) ? 1 : 0;
459 $_chlog_col_checked = 1;
460 }
461 return 0 unless $_chlog_col_exists;
462 my $r = $db->db_readwrite($dbh, qq~
463 SELECT changelog_last_seen_version AS v
464 FROM `${DB}`.users WHERE id='$uid'
465 ~, $ENV{SCRIPT_NAME}, __LINE__);
466 my $seen = $r ? ($r->{v} || '') : '';
467 return ($seen ne CURRENT_CHANGELOG_VERSION) ? 1 : 0;
468}
469
470# Thin wrapper around MODS::RePricer::Permissions->has_feature so the
471# sidebar builders stay decoupled from the module loader. Loaded once.
472my $_perm_singleton;
473sub _has_user_feature {
474 my ($userinfo, $slug) = @_;
475 return 1 unless $slug;
476 return 0 unless $userinfo;
477 # Owner / unconstrained: skip the DB trip
478 return 1 if !defined($userinfo->{permission_groups_id}) || $userinfo->{permission_groups_id} eq '';
479 if (!$_perm_singleton) {
480 return 1 unless eval { require MODS::RePricer::Permissions; 1 };
481 $_perm_singleton = MODS::RePricer::Permissions->new;
482 }
483 return $_perm_singleton->has_feature($userinfo, $slug);
484}
485
486# Count rows that should drive the unread indicator on the topbar
487# Messages pill. Sources: support_threads only (the cross-platform
488# external_comments inbox was removed on 2026-06-20). Guarded against
489# the table not existing yet on early-adopter installs.
490sub _unread_messages_count {
491 my ($uid, $is_admin) = @_;
492 return 0 unless $uid;
493 $uid =~ s/[^0-9]//g;
494 return 0 unless $uid;
495
496 require MODS::DBConnect;
497 my $db = MODS::DBConnect->new;
498 my $DB = $config->settings('database_name');
499 my $dbh = $db->db_connect();
500 return 0 unless $dbh;
501
502 my $total = 0;
503
504 # Support tickets / help threads. Admins count threads where
505 # admin_unread > 0 (anyone's ticket needing reply); regular
506 # users count their own threads where customer_unread > 0 (a
507 # reply from admin they haven't read yet). This is what makes
508 # a fresh help request light up the Messages pill.
509 my $have_st = $db->db_readwrite($dbh, qq~
510 SELECT COUNT(*) AS n FROM information_schema.tables
511 WHERE table_schema='$DB' AND table_name='support_threads'
512 ~, $ENV{SCRIPT_NAME}, __LINE__);
513 if ($have_st && $have_st->{n}) {
514 my $sql = $is_admin
515 ? qq~SELECT COUNT(*) AS n FROM `${DB}`.support_threads WHERE admin_unread > 0~
516 : qq~SELECT COUNT(*) AS n FROM `${DB}`.support_threads WHERE customer_user_id='$uid' AND customer_unread > 0~;
517 my $r = $db->db_readwrite($dbh, $sql, $ENV{SCRIPT_NAME}, __LINE__);
518 $total += ($r && $r->{n}) ? $r->{n} : 0;
519 }
520
521 $db->db_disconnect($dbh);
522 return $total;
523}
524
525# Open visitor chats with at least one unread message for the admin.
526# Drives both the topbar pill state (idle/waiting) and its click
527# target (jump direct to the longest-waiting chat). Table existence
528# is guarded via information_schema so pre-migration deploys can't
529# 500 the wrapper. Returns { n => count, first_id => oldest_pending_chat_id }.
530sub _pending_chats_data {
531 require MODS::DBConnect;
532 my $db = MODS::DBConnect->new;
533 my $DB = $config->settings('database_name');
534 my $dbh = $db->db_connect();
535 return { n => 0, first_id => 0 } unless $dbh;
536 my $have = $db->db_readwrite($dbh, qq~
537 SELECT COUNT(*) AS n FROM information_schema.tables
538 WHERE table_schema='$DB' AND table_name='support_chats'
539 ~, $ENV{SCRIPT_NAME}, __LINE__);
540 unless ($have && $have->{n}) {
541 $db->db_disconnect($dbh);
542 return { n => 0, first_id => 0 };
543 }
544 # ORDER BY last_message_at ASC -- oldest unread first. Sending an
545 # admin to the chat that has been waiting longest is the most
546 # courteous default; if they want a different one they can use
547 # the console list as normal.
548 my @rows = $db->db_readwrite_multiple($dbh, qq~
549 SELECT id FROM `${DB}`.support_chats
550 WHERE status = 'open'
551 AND unread_for_admin > 0
552 ORDER BY last_message_at ASC
553 ~, $ENV{SCRIPT_NAME}, __LINE__);
554 $db->db_disconnect($dbh);
555 return {
556 n => scalar(@rows),
557 first_id => scalar(@rows) ? ($rows[0]->{id} + 0) : 0,
558 };
559}
560
561# Banner shown across the top of every authenticated page WHILE an
562# admin is impersonating another user. The "Stop" link is a POST to
563# /admin_action.cgi (form, not GET) so accidental link-followers can't
564# end an impersonation by sharing a URL.
565sub _impersonation_banner {
566 my ($userinfo) = @_;
567 return '' unless $userinfo && $userinfo->{_impersonating};
568
569 my $target_email = _html_escape($userinfo->{email} || '');
570 my $target_name = _html_escape($userinfo->{display_name} || $target_email);
571 my $admin_email = _html_escape($userinfo->{_admin_email} || '');
572
573 return qq~
574<div class="impersonation-banner">
575 <div class="impersonation-banner-msg">
576 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/></svg>
577 <span><strong>Acting as</strong> $target_name &lt;$target_email&gt; &middot; admin: $admin_email</span>
578 </div>
579 <form method="POST" action="/admin_impersonate.cgi" class="impersonation-banner-form">
580 <input type="hidden" name="act" value="stop">
581 <button type="submit" class="impersonation-banner-stop">Stop &amp; return to admin</button>
582 </form>
583</div>
584~;
585}
586
587sub _html_escape {
588 my ($s) = @_;
589 return '' unless defined $s;
590 $s =~ s/&/&amp;/g;
591 $s =~ s/</&lt;/g;
592 $s =~ s/>/&gt;/g;
593 $s =~ s/"/&quot;/g;
594 $s =~ s/'/&#39;/g;
595 return $s;
596}
597
598# Inline SVG icon library — keeps the wrapper independent of any
599# external icon font / file. All icons are 24x24, stroke-based.
600my %ICONS = (
601 dashboard => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>',
602 models => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2 3 7v10l9 5 9-5V7l-9-5Z"/><path d="m3 7 9 5 9-5"/><path d="M12 22V12"/></svg>',
603 upload => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>',
604 storefront => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m3 9 1-5h16l1 5"/><path d="M5 9v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V9"/><path d="M9 21V13h6v8"/></svg>',
605 audience => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',
606 messages => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z"/></svg>',
607 funnel => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 3H2l8 9.46V19l4 2v-8.54L22 3z"/></svg>',
608 analytics => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="m7 14 4-4 4 4 5-5"/></svg>',
609 optimize => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>',
610 settings => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33 1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82v0a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z"/></svg>',
611 building => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="2" width="18" height="20" rx="2"/><path d="M9 22V12h6v10"/><path d="M9 6h.01"/><path d="M9 10h.01"/><path d="M15 6h.01"/><path d="M15 10h.01"/></svg>',
612 calendar => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>',
613 clock => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
614 admin => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/><path d="m9 12 2 2 4-4"/></svg>',
615 billing => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/><line x1="6" y1="15" x2="10" y2="15"/></svg>',
616 promotions => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20.59 13.41 13.42 20.58a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>',
617 profile => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>',
618 seo => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/><path d="M7 11h8"/><path d="M11 7v8"/></svg>',
619 visitors => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7Z"/><circle cx="12" cy="12" r="3"/></svg>',
620 chat => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z"/></svg>',
621 welcome => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12 12 3l9 9"/><path d="M5 10v10a1 1 0 0 0 1 1h4v-6h4v6h4a1 1 0 0 0 1-1V10"/></svg>',
622 heatmap => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="8" cy="9" r="3"/><circle cx="16" cy="14" r="4"/><circle cx="10" cy="17" r="2"/><rect x="2" y="2" width="20" height="20" rx="2"/></svg>',
623 team => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',
624 card => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="5" width="20" height="14" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/><line x1="6" y1="15" x2="10" y2="15"/><line x1="14" y1="15" x2="18" y2="15"/></svg>',
625);
626
627sub _icon {
628 my ($name) = @_;
629 return $ICONS{$name} || '';
630}
631
632# Build the <meta> block injected into every page's <head>. Pulls
633# platform defaults from platform_settings. (The per-storefront SEO
634# overlay was removed 2026-06-21 along with the buyer-facing storefront
635# infrastructure -- RePricer is a B2B SaaS and never serves a buyer
636# storefront.) Cached per-request via $_meta_cache so repeated calls
637# in one CGI don't re-query.
638our $_meta_cache;
639sub _build_meta_tags {
640 my ($opts) = @_;
641 return '' unless $opts;
642
643 require MODS::DBConnect;
644 require MODS::RePricer::SEO;
645 my $db = MODS::DBConnect->new;
646 my $seo = MODS::RePricer::SEO->new;
647 my $DB = $config->settings('database_name');
648 my $dbh = $db->db_connect();
649 return '' unless $dbh;
650
651 my $platform = $seo->get_platform_settings($db, $dbh, $DB);
652
653 my $tags = $seo->render_tags(
654 platform => $platform,
655 page_title => $opts->{title} || '',
656 request_url => $opts->{canonical_url} || '',
657 );
658
659 $db->db_disconnect($dbh);
660 return $tags;
661}
662
6631;
Keyboard: j next diff k previous diff g top G bottom r restore c compile-check ? help