Diff -- /var/www/vhosts/3dshawn.com/crm.3dshawn.com/admin_chat.cgi
Diff

/var/www/vhosts/3dshawn.com/crm.3dshawn.com/admin_chat.cgi

added on local at 2026-07-01 15:02:15

Added
+405
lines
Removed
-0
lines
Context
0
unchanged
Blobs
from
to c831d7a2ebcd
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# ContactForge - Admin Chat
4#
5# Dedicated chat console: list of conversations on the left, thread on
6# the right, reply box at the bottom. Online/offline toggle controls
7# whether the chat widget appears on visitor-facing dashboards.
8#======================================================================
9use strict;
10use warnings;
11
12use lib '/var/www/vhosts/3dshawn.com/crm.3dshawn.com';
13use CGI;
14use MODS::Template;
15use MODS::DBConnect;
16use MODS::Login;
17use MODS::ContactForge::Config;
18use MODS::ContactForge::Wrapper;
19use MODS::ContactForge::Admin;
20
21use MODS::ContactForge::NoOp;
22my $q = CGI->new;
23my $form = $q->Vars;
24my $auth = MODS::Login->new;
25my $wrap = MODS::ContactForge::Wrapper->new;
26my $tfile = MODS::Template->new;
27my $db = MODS::DBConnect->new;
28my $cfg = MODS::ContactForge::Config->new;
29my $admin = MODS::ContactForge::Admin->new;
30my $tr = MODS::ContactForge::NoOp->new;
31my $DB = $cfg->settings('database_name');
32
33$|=1;
34my $userinfo = $auth->login_verify();
35if (!$userinfo) {
36 print "Status: 302 Found\nLocation: /login.cgi\n\n";
37 exit;
38}
39$admin->require_admin($userinfo);
40require MODS::ContactForge::Permissions;
41MODS::ContactForge::Permissions->new->require_feature($userinfo, 'admin_chat');
42
43my $tutorial_mode = ($form->{tutorial} && $form->{tutorial} eq '1') ? 1 : 0;
44
45my $dbh = $db->db_connect();
46my $schema_ready = $tr->schema_ready($db, $dbh, $DB);
47
48my $admin_online = $schema_ready ? $tr->admin_online($db, $dbh, $DB) : 0;
49
50# View filter + search
51my %ok_view = (active=>1, closed=>1, archived=>1, all=>1);
52my $view = $form->{view} || 'active';
53$view = 'active' unless $ok_view{$view};
54my $search = defined $form->{q} ? $form->{q} : '';
55$search =~ s/^\s+|\s+$//g;
56my $search_trim = substr($search, 0, 100);
57
58# Conversation list
59my @chats_raw = $schema_ready ? $tr->admin_chat_list($db, $dbh, $DB,
60 filter => $view, search => $search_trim, limit => 100) : ();
61my $counts = $schema_ready ? $tr->chat_counts_by_status($db, $dbh, $DB)
62 : { active=>0, closed=>0, archived=>0, all=>0 };
63
64sub _h { my $s = shift; $s //= ''; $s =~ s/&/&amp;/g; $s =~ s/</&lt;/g; $s =~ s/>/&gt;/g; $s =~ s/"/&quot;/g; return $s; }
65sub _qs { my $s = shift; $s //= ''; $s =~ s/([^A-Za-z0-9\-_.~])/sprintf('%%%02X', ord($1))/eg; return $s; }
66
67# Build the ?view=X&q=... fragment so list links keep filter state.
68my $view_qs = '&view=' . $view;
69$view_qs .= '&q=' . _qs($search_trim) if length $search_trim;
70
71my @chats;
72my $selected_chat_id = $form->{chat} || 0;
73$selected_chat_id =~ s/[^0-9]//g;
74
75foreach my $c (@chats_raw) {
76 my $is_selected = ($selected_chat_id && $c->{chat_id} eq $selected_chat_id) ? 1 : 0;
77 $selected_chat_id ||= $c->{chat_id} if !$selected_chat_id;
78
79 # Pull session fingerprint for classification.
80 my $full = $db->db_readwrite($dbh, qq~
81 SELECT id, contact_account_id FROM `${DB}`.tracking_sessions WHERE id='$c->{session_id}' LIMIT 1
82 ~, $ENV{SCRIPT_NAME}, __LINE__);
83 my $cls = $tr->classify_session($db, $dbh, $DB, $full);
84
85 my $chat_status = $c->{status} || 'open';
86 my $idle = $c->{idle_seconds} || 0;
87 push @chats, {
88 chat_id => $c->{chat_id},
89 session_id => $c->{session_id},
90 label => _h($c->{visitor_label} || ('Visitor #' . $c->{session_id})),
91 platform_meta => _h(($c->{os_name} || '') . ' / ' . ($c->{browser_name} || '')),
92 device => _h($c->{device_type} || ''),
93 current_page => _h($c->{current_page_path} || ''),
94 last_message_at => $c->{last_message_at} || '',
95 last_body => _h(substr($c->{last_body} || '', 0, 60)),
96 last_from => $c->{last_from} || '',
97 unread => $c->{unread_for_admin} || 0,
98 href => '/admin_chat.cgi?chat=' . $c->{chat_id} . $view_qs,
99 is_selected => $is_selected,
100 # Contact classification (guest/lead/customer)
101 status => $cls->{status},
102 status_label => $cls->{status_label},
103 is_customer => $cls->{status} eq 'customer' ? 1 : 0,
104 is_lead => $cls->{status} eq 'lead' ? 1 : 0,
105 is_guest => $cls->{status} eq 'guest' ? 1 : 0,
106 email => _h($cls->{email} || ''),
107 has_email => $cls->{email} ? 1 : 0,
108 total_orders => $cls->{total_orders},
109 ltv_display => '$' . sprintf('%.2f', ($cls->{ltv_cents} || 0) / 100),
110 # Conversation status (open/closed/archived) for visual treatment
111 chat_status => $chat_status,
112 is_open => $chat_status eq 'open' ? 1 : 0,
113 is_closed => $chat_status eq 'closed' ? 1 : 0,
114 is_archived => $chat_status eq 'archived' ? 1 : 0,
115 visitor_online => ($c->{is_online} && $idle < 60) ? 1 : 0,
116 awaiting_reply => (($c->{last_from} || '') eq 'visitor' && $c->{unread_for_admin}) ? 1 : 0,
117 };
118}
119
120# Selected thread + visitor details
121my @thread_rows;
122my $thread = {};
123if ($schema_ready && $selected_chat_id) {
124 # Mark read on view
125 $tr->mark_chat_read($db, $dbh, $DB, $selected_chat_id, 'admin');
126
127 my @msgs = $tr->chat_messages($db, $dbh, $DB, $selected_chat_id, 200);
128 foreach my $m (@msgs) {
129 # HTML-escape first, then linkify URLs. Order matters: escaping
130 # an already-built <a> tag would mangle it; URLs themselves
131 # don't contain HTML-special chars normally, and any that do
132 # (& in querystrings) are correctly &amp;-escaped inside the
133 # href attribute, which is what HTML attribute parsing expects.
134 my $safe = _h($m->{body});
135 $safe =~ s{(https?://[^\s<]+)}{<a href="$1" target="_blank" rel="noopener" style="color:#60a5fa;text-decoration:underline">$1</a>}g;
136 push @thread_rows, {
137 id => $m->{id},
138 from_role => $m->{from_role},
139 body => $safe,
140 sent_at => $m->{sent_at} || '',
141 is_admin => ($m->{from_role} eq 'admin') ? 1 : 0,
142 is_visitor => ($m->{from_role} eq 'visitor') ? 1 : 0,
143 is_system => ($m->{from_role} eq 'system') ? 1 : 0,
144 };
145 }
146
147 # Visitor info for the right rail + chat row for status-driven actions
148 my $sess = $db->db_readwrite($dbh, qq~
149 SELECT s.*, c.status AS chat_status FROM `${DB}`.support_chats c
150 JOIN `${DB}`.tracking_sessions s ON s.id = c.session_id
151 WHERE c.id='$selected_chat_id' LIMIT 1
152 ~, $ENV{SCRIPT_NAME}, __LINE__);
153 if ($sess && $sess->{id}) {
154 my $cls = $tr->classify_session($db, $dbh, $DB, $sess);
155 my $chat_status = $sess->{chat_status} || 'open';
156 $thread = {
157 session_id => $sess->{id},
158 label => _h($sess->{visitor_label} || ''),
159 os => _h(($sess->{os_name} || '') . ' ' . ($sess->{os_version} || '')),
160 browser => _h(($sess->{browser_name} || '') . ' ' . ($sess->{browser_version} || '')),
161 device => _h($sess->{device_type} || ''),
162 screen => ($sess->{screen_width} && $sess->{screen_height}) ? ($sess->{screen_width} . 'x' . $sess->{screen_height}) : '',
163 language => _h($sess->{language} || ''),
164 timezone => _h($sess->{timezone} || ''),
165 current_page => _h($sess->{current_page_path} || ''),
166 status => $cls->{status},
167 status_label => $cls->{status_label},
168 is_customer => $cls->{status} eq 'customer' ? 1 : 0,
169 is_lead => $cls->{status} eq 'lead' ? 1 : 0,
170 is_guest => $cls->{status} eq 'guest' ? 1 : 0,
171 email => _h($cls->{email} || ''),
172 has_email => $cls->{email} ? 1 : 0,
173 total_orders => $cls->{total_orders},
174 ltv_display => '$' . sprintf('%.2f', ($cls->{ltv_cents} || 0) / 100),
175 # Conversation status drives which header buttons render.
176 chat_status => $chat_status,
177 is_open => $chat_status eq 'open' ? 1 : 0,
178 is_closed => $chat_status eq 'closed' ? 1 : 0,
179 is_archived => $chat_status eq 'archived' ? 1 : 0,
180 };
181 }
182}
183
184# ---- Concluded-chats summary (last 30 days + today) -----------------
185# Counts every chat that hit status='closed' OR 'archived' (both count
186# as "resolved" -- archive is just an old close). Today's bar always
187# renders even when zero closures so the trend reads honestly. Also
188# pulls the individual chats so the bar drilldown overlay can list
189# them without a follow-up request.
190my @resolved_raw = $schema_ready ? $tr->chats_closed_by_day($db, $dbh, $DB, 30) : ();
191my @resolved_list = $schema_ready ? $tr->chats_closed_list($db, $dbh, $DB, 30) : ();
192my %resolved_by_d = map { $_->{d} => $_ } @resolved_raw;
193my %chats_by_d;
194foreach my $cc (@resolved_list) {
195 my $d = $cc->{d} || '';
196 push @{ $chats_by_d{$d} }, {
197 id => $cc->{id} + 0,
198 hm => $cc->{hm} || '',
199 label => $cc->{label} || ('Visitor #' . $cc->{id}),
200 };
201}
202
203# Build the trailing 30 days from oldest -> newest so the chart reads
204# left-to-right as time-moves-forward.
205my @resolved_days;
206my $resolved_max = 0;
207my $today_count = 0;
208my @short_months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
209# Today's date as a reference point. We walk back 29 days and stop at today.
210my ($t_sec,$t_min,$t_hour,$t_mday,$t_mon,$t_year) = localtime(time);
211require POSIX;
212my $today_epoch = POSIX::mktime(0,0,12,$t_mday,$t_mon,$t_year);
213for (my $i = 29; $i >= 0; $i--) {
214 my $epoch = $today_epoch - ($i * 86400);
215 my @t = localtime($epoch);
216 my $d_iso = sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]);
217 my $d_short = sprintf('%s %d', $short_months[$t[4]], $t[3]); # "May 17"
218 my $n = ($resolved_by_d{$d_iso} && $resolved_by_d{$d_iso}->{n}) || 0;
219 $resolved_max = $n if $n > $resolved_max;
220 $today_count = $n if $i == 0;
221 # Serialise the per-day chat list so the drilldown can read it
222 # from a data-* attribute. Embeds visitor label + close time +
223 # link to the conversation. Strict JSON (double-quoted keys/values
224 # with JSON-escaping) so the JS can JSON.parse it cleanly.
225 my $chats_for_day = $chats_by_d{$d_iso} || [];
226 my @items_json;
227 for my $cc (@$chats_for_day) {
228 my $lbl = $cc->{label};
229 # JSON-escape: backslash, double-quote, control chars
230 $lbl =~ s/\\/\\\\/g;
231 $lbl =~ s/"/\\"/g;
232 $lbl =~ s/\r/\\r/g;
233 $lbl =~ s/\n/\\n/g;
234 $lbl =~ s/\t/\\t/g;
235 my $hm = $cc->{hm} || '';
236 $hm =~ s/[^0-9:]//g;
237 my $cid = $cc->{id} + 0;
238 # Build with sprintf instead of qq~ so a literal '~' in the
239 # visitor label cannot accidentally terminate the heredoc.
240 push @items_json, sprintf('{"id":%d,"hm":"%s","label":"%s"}', $cid, $hm, $lbl);
241 }
242 my $chats_json = '[' . join(',', @items_json) . ']';
243 # HTML-attribute escape the JSON so it's safe inside data-chats='...'.
244 # Single-quote attribute means we only need to escape the apostrophe.
245 $chats_json =~ s/&/&amp;/g;
246 $chats_json =~ s/'/&#39;/g;
247 push @resolved_days, {
248 d_iso => $d_iso,
249 d_short => $d_short,
250 d_label => $d_short,
251 n => $n,
252 is_current => $i == 0 ? 1 : 0,
253 chats_json => $chats_json,
254 };
255}
256# Add a relative-height percent for the bar visual.
257foreach my $r (@resolved_days) {
258 $r->{bar_pct} = $resolved_max ? sprintf('%.1f', ($r->{n} / $resolved_max) * 100) : '0.0';
259}
260my $resolved_total_30d = 0;
261$resolved_total_30d += $_->{n} for @resolved_days;
262# Preserve the old var names so unrelated template branches keep working.
263my $mtd_resolved = $today_count;
264my @resolved_months = @resolved_days;
265my $resolved_total_6mo = $resolved_total_30d;
266
267$db->db_disconnect($dbh);
268
269my $tvars = {
270 user_id => $userinfo->{user_id},
271 schema_ready => $schema_ready ? 1 : 0,
272 schema_missing => $schema_ready ? 0 : 1,
273 admin_online => $admin_online,
274
275 # Monthly resolved-chats summary
276 resolved_months => \@resolved_months,
277 has_resolved_months => scalar(@resolved_months) ? 1 : 0,
278 resolved_total_6mo => $resolved_total_6mo,
279 resolved_mtd => $mtd_resolved,
280 chats => \@chats,
281 has_chats => scalar(@chats) ? 1 : 0,
282 chat_count => scalar(@chats),
283 selected_chat_id => $selected_chat_id || 0,
284 has_selected => $selected_chat_id ? 1 : 0,
285 thread => $thread,
286 has_thread => %$thread ? 1 : 0,
287 thread_rows => \@thread_rows,
288 has_thread_rows => scalar(@thread_rows) ? 1 : 0,
289 tutorial_mode => $tutorial_mode,
290 not_tutorial_mode=> $tutorial_mode ? 0 : 1,
291 # Filter + search state
292 view => $view,
293 is_view_active => $view eq 'active' ? 1 : 0,
294 is_view_closed => $view eq 'closed' ? 1 : 0,
295 is_view_archived => $view eq 'archived' ? 1 : 0,
296 is_view_all => $view eq 'all' ? 1 : 0,
297 search_q => _h($search_trim),
298 has_search => length $search_trim ? 1 : 0,
299 count_active => $counts->{active},
300 count_closed => $counts->{closed},
301 count_archived => $counts->{archived},
302 count_all => $counts->{all},
303};
304
305# Tutorial sample
306if ($tutorial_mode) {
307 $tvars->{admin_online} = 1;
308 $tvars->{count_active} = 3;
309 $tvars->{count_closed} = 12;
310 $tvars->{count_archived} = 48;
311 $tvars->{count_all} = 63;
312 # Sample daily resolved-chats trend (30 trailing days). Numbers
313 # picked to look organic (busier weekdays, quieter weekends) without
314 # spiking off-chart so the bar visual reads naturally in tutorial.
315 my @sample_pattern = (4,6,5,7,3,2,1, 5,8,9,7,6,2,3, 6,7,10,8,9,4,2, 5,9,11,8,7,3,1, 6,12);
316 my @sample_days;
317 my @short_months_tut = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
318 my ($s_sec,$s_min,$s_hour,$s_mday,$s_mon,$s_year) = localtime(time);
319 require POSIX;
320 my $s_today_epoch = POSIX::mktime(0,0,12,$s_mday,$s_mon,$s_year);
321 my $sample_total = 0;
322 my $sample_today = 0;
323 my $sample_max = 0;
324 for (my $i = 29; $i >= 0; $i--) {
325 my $n = $sample_pattern[29 - $i] || 0;
326 my @t = localtime($s_today_epoch - ($i * 86400));
327 my $d_iso = sprintf('%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3]);
328 my $d_short = sprintf('%s %d', $short_months_tut[$t[4]], $t[3]);
329 $sample_total += $n;
330 $sample_today = $n if $i == 0;
331 $sample_max = $n if $n > $sample_max;
332 push @sample_days, {
333 d_iso => $d_iso,
334 d_short => $d_short,
335 d_label => $d_short,
336 n => $n,
337 is_current => $i == 0 ? 1 : 0,
338 chats_json => '[]',
339 };
340 }
341 foreach my $m (@sample_days) {
342 $m->{bar_pct} = $sample_max ? sprintf('%.1f', ($m->{n} / $sample_max) * 100) : '0.0';
343 }
344 $tvars->{resolved_months} = \@sample_days;
345 $tvars->{has_resolved_months} = 1;
346 $tvars->{resolved_total_6mo} = $sample_total;
347 $tvars->{resolved_mtd} = $sample_today;
348 $tvars->{chats} = [
349 { chat_id=>1, session_id=>842, label=>'Visitor #842', platform_meta=>'macOS / Safari', device=>'desktop',
350 current_page=>'/store.cgi?id=1', last_message_at=>'2 min ago',
351 last_body=>'Do these prints come with supports?', last_from=>'visitor',
352 unread=>2, href=>'/admin_chat.cgi?tutorial=1&chat=1', is_selected=>1,
353 status=>'customer', status_label=>'Customer', is_customer=>1, is_lead=>0, is_guest=>0,
354 email=>'rune.caster@example.com', has_email=>1, total_orders=>4, ltv_display=>'$96.00',
355 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>1, awaiting_reply=>1 },
356 { chat_id=>2, session_id=>841, label=>'Visitor #841', platform_meta=>'Windows / Chrome', device=>'desktop',
357 current_page=>'/store.cgi?id=1&page=catalog', last_message_at=>'18 min ago',
358 last_body=>'Thanks, that worked!', last_from=>'visitor',
359 unread=>0, href=>'/admin_chat.cgi?tutorial=1&chat=2', is_selected=>0,
360 status=>'guest', status_label=>'Guest', is_customer=>0, is_lead=>0, is_guest=>1,
361 email=>'', has_email=>0, total_orders=>0, ltv_display=>'$0.00',
362 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>0, awaiting_reply=>0 },
363 { chat_id=>3, session_id=>840, label=>'Visitor #840', platform_meta=>'iOS / Safari', device=>'mobile',
364 current_page=>'/store.cgi?id=1&page=about', last_message_at=>'1 h ago',
365 last_body=>'Glad you could help!', last_from=>'admin',
366 unread=>0, href=>'/admin_chat.cgi?tutorial=1&chat=3', is_selected=>0,
367 status=>'lead', status_label=>'Lead', is_customer=>0, is_lead=>1, is_guest=>0,
368 email=>'bench.hammer@example.com', has_email=>1, total_orders=>0, ltv_display=>'$0.00',
369 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0, visitor_online=>0, awaiting_reply=>0 },
370 ];
371 $tvars->{has_chats} = 1;
372 $tvars->{chat_count} = 3;
373 $tvars->{selected_chat_id} = 1;
374 $tvars->{has_selected} = 1;
375 $tvars->{thread} = {
376 session_id=>842, label=>'Visitor #842',
377 os=>'macOS 14.4', browser=>'Safari 17.4', device=>'desktop',
378 screen=>'2560x1440', language=>'en-US', timezone=>'America/Denver',
379 current_page=>'/store.cgi?id=1',
380 status=>'customer', status_label=>'Customer', is_customer=>1, is_lead=>0, is_guest=>0,
381 email=>'rune.caster@example.com', has_email=>1, total_orders=>4, ltv_display=>'$96.00',
382 chat_status=>'open', is_open=>1, is_closed=>0, is_archived=>0,
383 };
384 $tvars->{has_thread} = 1;
385 $tvars->{thread_rows} = [
386 { id=>1, from_role=>'visitor', body=>'Hi! Quick question about the Dragon Lord MK-II.', sent_at=>'14:18', is_admin=>0, is_visitor=>1, is_system=>0 },
387 { id=>2, from_role=>'admin', body=>'Hey! Happy to help -- what is the question?', sent_at=>'14:19', is_admin=>1, is_visitor=>0, is_system=>0 },
388 { id=>3, from_role=>'visitor', body=>'Do these prints come with supports?', sent_at=>'14:20', is_admin=>0, is_visitor=>1, is_system=>0 },
389 { id=>4, from_role=>'visitor', body=>'And what layer height did you test at?', sent_at=>'14:20', is_admin=>0, is_visitor=>1, is_system=>0 },
390 ];
391 $tvars->{has_thread_rows} = 1;
392 $tvars->{schema_ready} = 1;
393 $tvars->{schema_missing} = 0;
394}
395
396print "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";
397
398my $body = join('', $tfile->template('cf_admin_chat.html', $tvars, $userinfo));
399
400$wrap->render({
401 userinfo => $userinfo,
402 page_key => 'admin_chat',
403 title => 'Admin &middot; Chat',
404 body => $body,
405});
Keyboard: j next diff k previous diff g top G bottom r restore c compile-check ? help