From 388f083a2b11a8eb78bf283b831315218d559d22 Mon Sep 17 00:00:00 2001
From: johnnyq
Date: Sun, 22 Nov 2026 21:56:35 -0500
Subject: [PATCH] Add phone system integration with FusionPBX: Admin Phone
Systems with setup lines for mod_xml_cdr and mod_cidlookup, domains linked to
clients with suggestions, a Calls page per client and contact with calls
matched to contacts, Add to Ticket with talk time as time worked, and caller
ID names from ITFlow on desk phones
---
CHANGELOG.md | 8 +-
admin/database_updates/4.1.4.php | 127 +++
admin/includes/side_nav.php | 7 +
admin/modals/phone/phone_domain_link.php | 55 ++
admin/modals/phone/phone_system_add.php | 9 +
admin/modals/phone/phone_system_edit.php | 88 +++
admin/modals/phone/phone_system_setup.php | 77 ++
admin/phone_domains.php | 277 +++++++
admin/phone_systems.php | 181 +++++
admin/post/phone.php | 167 ++++
agent/calls.php | 257 ++++++
agent/contact.php | 24 +
agent/includes/client_side_nav.php | 15 +
agent/includes/inc_all_client.php | 3 +
agent/includes/side_nav.php | 14 +
agent/modals/phone/phone_call_ticket.php | 109 +++
agent/modals/ticket/ticket_add.php | 10 +
agent/post/client.php | 6 +
agent/post/phone.php | 45 ++
agent/post/ticket.php | 8 +
api/phone/cdr.php | 27 +
api/phone/cid.php | 21 +
api/phone/phone_system.php | 41 +
cron/nightly_tasks.php | 3 +
css/itflow_custom.css | 22 +
db.sql | 136 ++++
functions.php | 1 +
functions/audit_log.php | 1 +
functions/client.php | 1 +
functions/phone.php | 902 ++++++++++++++++++++++
functions/ticket.php | 3 +-
31 files changed, 2643 insertions(+), 2 deletions(-)
create mode 100644 admin/database_updates/4.1.4.php
create mode 100644 admin/modals/phone/phone_domain_link.php
create mode 100644 admin/modals/phone/phone_system_add.php
create mode 100644 admin/modals/phone/phone_system_edit.php
create mode 100644 admin/modals/phone/phone_system_setup.php
create mode 100644 admin/phone_domains.php
create mode 100644 admin/phone_systems.php
create mode 100644 admin/post/phone.php
create mode 100644 agent/calls.php
create mode 100644 agent/modals/phone/phone_call_ticket.php
create mode 100644 agent/post/phone.php
create mode 100644 api/phone/cdr.php
create mode 100644 api/phone/cid.php
create mode 100644 api/phone/phone_system.php
create mode 100644 functions/phone.php
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 13a43244b..c3c79d695 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading
-Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's two database changes (4.1.1 to 4.1.3) in the same pass. They add a column to RMM providers for the asset type each kind of device comes in as, and three to rack items for devices side by side in a holder, and change nothing that is there. Nothing else is required.
+Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's three database changes (4.1.1 to 4.1.4) in the same pass. They add a column to RMM providers for the asset type each kind of device comes in as, three to rack items for devices side by side in a holder, and the tables for phone systems, and change nothing that is there. Nothing else is required.
### New Features & Updates
@@ -18,6 +18,9 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- API: assets read through the API come with asset_rmm - each of the asset's devices in an RMM, with its status, when it was last seen, who is signed in, its IPs, and whether it needs a reboot, has patches waiting or has checks failing.
- RMM Providers: most of a client's devices gone from the RMM at once - three or more, and at least half of them - are kept as they were for a day instead of being marked gone straight away. That is far more often the RMM, or a change to what its API key can see, than the devices, and marking them gone dropped them from managed device counts on recurring invoices. The provider's row names the client and how many, and the sync shows as failed so it is noticed. Still missing after a day, they are marked gone. A client deleted in the RMM is treated the same way, and agents reinstalled all at once are still matched to their assets.
- Racks: more than one device on a rack row - two Tiny PCs in a 1U bracket, eight PLCs on a shelf, the cards in a media converter chassis. Turn on Holds devices side by side on a rack item - a shelf, bracket or chassis, an asset or not - and say how many fit across. What is in it is drawn side by side in it, and past that many it wraps onto another row, for stacks. Click an empty slot to add something there, or pick the holder under Goes in when you add it. Drag an asset from Not racked yet or an item from the rack onto an empty slot, or a device to another slot, with Undo. Moving the holder moves what is in it, and removing it takes what is in it out of the rack too, after asking - the assets stay. An asset's page and the assets list show its slot, the page with a link to the holder when that is an asset - a server node to its chassis - and a holder's own page has Devices in it, listing what is in each slot. The client export and the API have slots too.
+- Phone Systems: Admin > Phone Systems takes FusionPBX - without its API or its database. FreeSWITCH, underneath it, sends ITFlow each call's record as it hangs up and asks ITFlow for caller ID names; the system's Setup window gives the lines to paste, with its own key in them. Each of its domains is linked to the client it is, with the client it looks like suggested. A call on a client's domain is that client's; on your own company's domain it goes to whoever called, from any client.
+- Calls: a new Calls page, on the menu and on each client, lists the calls with who they were with - matched to a contact by their number, or to a client by its main number - the extension and agent that took them, how long they talked, and whether they were missed or went to voicemail, with a link to the call's page in FusionPBX and its recording. A contact's page has a Calls tab, and the menu counts the calls missed today that aren't on a ticket. Add to Ticket puts a call on one of the client's open tickets, or a new one, as an internal note with its talk time as time worked.
+- Phone Systems: as a call rings, desk phones show the contact and their client - Marla Whitfield - Ravenwood Dental - when ITFlow knows the number, and the carrier's name otherwise.
### Bug Fixes
@@ -50,6 +53,9 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u
- `reportQuarters($year, $current_year)` in `functions/reports.php` gives a year's quarters - label, months, first and last month, `done`, `now` or `later`, and what each is compared with - and `reportQuarterSum($months, $quarter)` a quarter's share of a year of months. A report puts its `rows` (`label`, `now`, `prev`, `good`, `strong`) on each and `reportQuarterCards($quarters, $whole)` draws them, in the `.itflow-report-stats` strip, laid out by a container query on its own width: four across, two by two, or one a row. `agent/reports/profit_loss.php` and `agent/reports/tax_summary.php` show them on Quarterly in place of the chart, the latter adding up last year's tax paid on purchases for net tax. `reportChartColumns($months, $columns, $months_shown)` sums a year's months into a report's columns for a chart, null for a column still to come.
- Database 4.1.3: `rack_units.unit_slots` (how many a holder takes side by side, 0 for any other item), `unit_parent_id` (the holder a device is in - a foreign key to `rack_units` that cascades on delete) and `unit_position` (its slot, 1 the first, counting across and then a row on). Re-runnable. A device in a holder keeps its holder's units, face and depth in its own columns - `rackSyncChildren($holder_id)` after the holder moves or changes - so whatever reads where an asset is racked reads it as before, and `rackOccupancy()` and `rackUnitConflict()` skip devices in a holder. `rackPositionForAsset()` adds `unit_id`, `unit_slots`, `unit_position`, `holder_name` and `holder_asset_id`. `rackSlotHtml()` links the holder from an asset's page, and `rackHolderChildren($unit_id)` lists what is in a holder for its own page, from `rackUnitRows($where)`, which `rackLoadUnits()` now uses too.
- `rackPlacement($rack_id, $unit_id, $want)` in `functions/rack.php` checks where an item goes - in the rack (bounds, overlaps, and that a holder with devices in it still holds devices) or in a slot (the holder is in the same rack and holds devices, the item holds none, the slot is free and at most a row past the last one used, `rackSlotLimit()`) - and `rackPlacementSet()` writes it. The rack item form, the drag (`move_rack_unit` with `holder` and `slot`), Undo (`['rack_place', ...]`) and the API's `rack_units` endpoints (`unit_slots`, `unit_parent_id`, `unit_position`) all go through it. `rackNestItems()` and `rackHolderCells()` lay a holder out for `agent/includes/rack_elevation.php`, its rows counting the way the rack's units do.
+- Database 4.1.4: `phone_systems`, `phone_domains`, `phone_calls`, `phone_devices`, `phone_events` and `user_settings.user_config_phone_line`. Re-runnable. `functions/phone.php` has them; nothing in ITFlow connects to a phone system - it sends to `api/phone/`, keyed by the address's `key` or the HTTP Basic password (`phoneSystemByKey()`), 404 for an unknown key and 503 for a system turned off.
+- `api/phone/cdr.php` takes mod_xml_cdr's post - the `cdr` field URL-encoded or base64, or the body - through `phoneCdrParse()` (its variables URL-decoded, the rest from the first caller profile) and `phoneCallFromCdr()` (FusionPBX's `call_direction`, else worked out from the numbers). A second leg (`originating_leg_uuid`, or `uuid` starting `b_`) is set aside, and a call is kept once per uuid. `api/phone/cid.php` answers mod_cidlookup with `phoneCallerName()`.
+- `phoneWho($number, $domain_client_id)` matches a number with `smsContactsFor()` - a mobile before an office number many share - then clients' location phones; a number more than one client has is nobody's. On a client's domain only that client counts; on your own company's (`config_internal_client_id`) or one not linked, every client does. `phoneDomainLink()` matches a domain's calls again. `phoneCallToTicket()` adds the internal note, its talk time as `ticket_reply_time_worked` with the work start and end, and `add_ticket` takes `phone_call_id` (ticket source Phone). `phoneCleanup()` runs nightly: calls over 400 days old that aren't on a ticket go. Client delete and merge take the phone tables.
## [26.12]
diff --git a/admin/database_updates/4.1.4.php b/admin/database_updates/4.1.4.php
new file mode 100644
index 000000000..7d5720b7d
--- /dev/null
+++ b/admin/database_updates/4.1.4.php
@@ -0,0 +1,127 @@
+RMM Providers
+ 'domains',
+ 'icon' => 'fa-globe',
+ 'title' => escapeHtml($show === 'unlinked' ? 'Every domain is linked' : 'No domains yet'),
+ 'text' => $show === 'unlinked' ? '' : escapeHtml($system['phone_system_heard_at'] ? "$name hasn't named a domain yet." : "Once $short is set up, each domain shows here with its first call."),
+ 'actions' => !$system['phone_system_heard_at'] ? [['label' => 'Setup', 'modal' => $setup_url, 'size' => 'lg', 'icon' => 'fa-plug']] : [],
+ 'filtered' => $q !== '',
+ ];
+ ?>
+
+
+
+
+
+
+
+ Phone Systems - the PBXs that send ITFlow their calls (functions/phone.php), FusionPBX
+ * the first kind. Each row says which it is, how many of its domains are linked to clients, how
+ * many calls came in the last 30 days, and when it was last heard from. Its domains, and how to
+ * set it up, are on its Domains page (phone_domains.php). Add and Edit are one window
+ * (modals/phone/phone_system_edit.php); the rest are admin/post/phone.php.
+ */
+
+// Default Column Sortby Filter
+$sort = "phone_system_name";
+$order = "ASC";
+
+require_once "includes/inc_all_admin.php";
+
+// The tables arrive with the 4.1.4 database update
+if (!phoneTablesReady()) { ?>
+
Phone Systems arrive with a database update - run it in Maintenance > Update first.
+ "phone_system_name $order",
+ 'phone_system_kind' => "phone_system_kind $order, phone_system_name ASC",
+ 'domains_linked' => "domains_linked $order, phone_system_name ASC",
+ 'calls_month' => "calls_month $order, phone_system_name ASC",
+ 'phone_system_heard_at' => "phone_system_heard_at IS NULL, phone_system_heard_at $order, phone_system_name ASC",
+];
+if (!isset($sortable_columns[$sort])) {
+ $sort = 'phone_system_name';
+}
+
+$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS phone_systems.*,
+ (SELECT COUNT(*) FROM phone_domains WHERE phone_domain_system_id = phone_system_id) AS domains_total,
+ (SELECT COUNT(*) FROM phone_domains WHERE phone_domain_system_id = phone_system_id AND phone_domain_client_id > 0) AS domains_linked,
+ (SELECT COUNT(*) FROM phone_calls WHERE phone_call_system_id = phone_system_id AND phone_call_started_at >= NOW() - INTERVAL 30 DAY) AS calls_month
+ FROM phone_systems
+ WHERE (phone_system_name LIKE '%$q%' OR phone_system_web_url LIKE '%$q%' OR phone_system_kind LIKE '%$q%')
+ ORDER BY {$sortable_columns[$sort]}, phone_system_id ASC
+ LIMIT $record_from, $record_to");
+
+$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
+
+$add_url = 'modals/phone/phone_system_add.php';
+$csrf = $_SESSION['csrf_token'];
+
+?>
+
+
+ 'phone systems',
+ 'icon' => 'fa-phone-volume',
+ 'text' => 'Add ' . escapeHtml(implode(' or ', array_column($kinds, 'name'))) . ' and set it up to tell ITFlow about its calls: each call is kept with the contact it was with, and its desk phones show who is calling - nothing is asked of its API or database.',
+ 'actions' => [['label' => 'New Phone System', 'modal' => $add_url]],
+ ];
+ ?>
+
+
+
+ Phone Systems (functions/phone.php) - Add and Edit, turning one off and on, a new key
+ * for its addresses, Delete, and on its Domains page linking its domains to clients - one at a
+ * time, the suggested ones, and unlinking. What changed is in the audit log - never the key.
+ */
+
+defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
+
+if (isset($_POST['save_phone_system'])) {
+
+ validateCSRFToken();
+
+ $phone_system_id = intval($_POST['phone_system_id'] ?? 0);
+ $before = $phone_system_id ? phoneSystemRow($phone_system_id) : null;
+ if ($phone_system_id && !$before) {
+ flashAlert('That phone system no longer exists.', 'error');
+ redirect('phone_systems.php');
+ }
+
+ [$after, $errors] = phoneSystemCheck($_POST, $before);
+ if ($errors) {
+ flashAlert('Not saved - ' . escapeHtml(reset($errors)), 'error');
+ redirect();
+ }
+
+ $name = $after['phone_system_name'];
+ if ($before) {
+ $lines = phoneSystemChangeLines($before, $after);
+ if (!$lines) {
+ flashAlert('Nothing changed on ' . escapeHtml($name) . '', 'info');
+ redirect();
+ }
+ phoneSystemWrite($after, $phone_system_id);
+ logAudit("Phone System", "Edit", "$session_name changed phone system " . escapeSql(phoneSystemName($before) . ': ' . implode('; ', $lines)), 0, $phone_system_id);
+ flashAlert('' . escapeHtml($name) . ' saved');
+ redirect();
+ }
+
+ $phone_system_id = phoneSystemWrite($after);
+ $kind = phoneSystemKinds()[$after['phone_system_kind']];
+ logAudit("Phone System", "Create", "$session_name added phone system " . escapeSql($name . ($name !== $kind['name'] ? " ({$kind['name']})" : '')), 0, $phone_system_id);
+ flashAlert('' . escapeHtml($name) . ' created - now set it up to send ITFlow its calls');
+ redirect("phone_domains.php?phone_system_id=$phone_system_id&setup=1");
+
+}
+
+// Turn it off - what it sends is turned away - or on again
+if (isset($_GET['turn_phone_system_off']) || isset($_GET['turn_phone_system_on'])) {
+
+ validateCSRFToken();
+
+ $on = isset($_GET['turn_phone_system_on']);
+ $system = phoneSystemRow($on ? $_GET['turn_phone_system_on'] : $_GET['turn_phone_system_off']);
+ if (!$system) {
+ flashAlert('That phone system no longer exists.', 'error');
+ redirect('phone_systems.php');
+ }
+ $phone_system_id = intval($system['phone_system_id']);
+ mysqli_query($mysqli, "UPDATE phone_systems SET phone_system_active = " . ($on ? 1 : 0) . " WHERE phone_system_id = $phone_system_id");
+ logAudit("Phone System", "Edit", "$session_name turned phone system " . escapeSql(phoneSystemName($system)) . ($on ? ' on' : ' off'), 0, $phone_system_id);
+ flashAlert('' . escapeHtml(phoneSystemName($system)) . ' turned ' . ($on ? 'on' : 'off - what it sends is turned away'), $on ? 'success' : 'error');
+ redirect();
+
+}
+
+// A new key - its addresses change, and the old ones stop working
+if (isset($_GET['new_phone_system_key'])) {
+
+ validateCSRFToken();
+
+ $system = phoneSystemRow($_GET['new_phone_system_key']);
+ if (!$system) {
+ flashAlert('That phone system no longer exists.', 'error');
+ redirect('phone_systems.php');
+ }
+ $phone_system_id = intval($system['phone_system_id']);
+ mysqli_query($mysqli, "UPDATE phone_systems SET phone_system_key = '" . escapeSql(phoneSystemNewKey()) . "' WHERE phone_system_id = $phone_system_id");
+ logAudit("Phone System", "Edit", "$session_name made a new key for phone system " . escapeSql(phoneSystemName($system)), 0, $phone_system_id);
+ flashAlert('' . escapeHtml(phoneSystemName($system)) . ' has a new key - put its new addresses in FusionPBX; the old ones no longer work', 'warning');
+ redirect("phone_domains.php?phone_system_id=$phone_system_id&setup=1");
+
+}
+
+if (isset($_GET['delete_phone_system'])) {
+
+ validateCSRFToken();
+
+ $system = phoneSystemRow($_GET['delete_phone_system']);
+ if (!$system) {
+ flashAlert('That phone system no longer exists.', 'error');
+ redirect('phone_systems.php');
+ }
+ $phone_system_id = intval($system['phone_system_id']);
+ $calls = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM phone_calls WHERE phone_call_system_id = $phone_system_id"))[0]);
+ foreach (['phone_calls' => 'phone_call_system_id', 'phone_devices' => 'phone_device_system_id', 'phone_events' => 'phone_event_system_id', 'phone_domains' => 'phone_domain_system_id'] as $table => $column) {
+ mysqli_query($mysqli, "DELETE FROM $table WHERE $column = $phone_system_id");
+ }
+ mysqli_query($mysqli, "DELETE FROM phone_systems WHERE phone_system_id = $phone_system_id");
+ logAudit("Phone System", "Delete", "$session_name deleted phone system " . escapeSql(phoneSystemName($system)) . " and its $calls call" . ($calls === 1 ? '' : 's'), 0, $phone_system_id);
+ flashAlert('' . escapeHtml(phoneSystemName($system)) . ' deleted', 'error');
+ redirect('phone_systems.php');
+
+}
+
+// A domain linked to a client - from its window
+if (isset($_POST['link_phone_domain'])) {
+
+ validateCSRFToken();
+
+ $domain = phoneDomainRow($_POST['phone_domain_id'] ?? 0);
+ $client_id = intval($_POST['client_id'] ?? 0);
+ $client_name = $client_id ? (string) getFieldById('clients', $client_id, 'client_name') : '';
+ if (!$domain || $client_name === '') {
+ flashAlert(!$domain ? 'That domain is gone.' : 'Pick a client.', 'error');
+ redirect();
+ }
+ phoneDomainLink(intval($domain['phone_domain_id']), $client_id);
+ logAudit("Phone System", "Edit", "$session_name linked " . escapeSql(phoneSystemName($domain)) . " domain " . escapeSql($domain['phone_domain_name']) . " to client " . escapeSql($client_name), $client_id, intval($domain['phone_system_id']));
+ flashAlert('' . escapeHtml($domain['phone_domain_name']) . ' linked to ' . escapeHtml($client_name) . '');
+ redirect();
+
+}
+
+// The suggested link for one domain, or for all of them
+if (isset($_GET['link_phone_suggested'])) {
+
+ validateCSRFToken();
+
+ $system = phoneSystemRow($_GET['phone_system_id'] ?? 0);
+ if (!$system) {
+ flashAlert('That phone system no longer exists.', 'error');
+ redirect('phone_systems.php');
+ }
+ $suggestions = phoneDomainSuggestions(intval($system['phone_system_id']));
+ $which = (string) $_GET['link_phone_suggested'];
+ if ($which !== 'all') {
+ $suggestions = array_intersect_key($suggestions, [intval($which) => true]);
+ }
+ foreach ($suggestions as $domain_id => $client_id) {
+ $domain = phoneDomainRow($domain_id);
+ phoneDomainLink($domain_id, $client_id);
+ logAudit("Phone System", "Edit", "$session_name linked " . escapeSql(phoneSystemName($system)) . " domain " . escapeSql($domain['phone_domain_name']) . " to client " . escapeSql((string) getFieldById('clients', $client_id, 'client_name')), $client_id, intval($system['phone_system_id']));
+ }
+ $count = count($suggestions);
+ flashAlert($count ? "$count domain" . ($count === 1 ? '' : 's') . " linked" : 'Nothing to link', $count ? 'success' : 'info');
+ redirect();
+
+}
+
+if (isset($_GET['unlink_phone_domain'])) {
+
+ validateCSRFToken();
+
+ $domain = phoneDomainRow($_GET['unlink_phone_domain']);
+ if (!$domain) {
+ flashAlert('That domain is gone.', 'error');
+ redirect();
+ }
+ $client_id = intval($domain['phone_domain_client_id']);
+ phoneDomainLink(intval($domain['phone_domain_id']), 0);
+ logAudit("Phone System", "Edit", "$session_name unlinked " . escapeSql(phoneSystemName($domain)) . " domain " . escapeSql($domain['phone_domain_name']) . " from client " . escapeSql((string) $domain['client_name']), $client_id, intval($domain['phone_system_id']));
+ flashAlert('' . escapeHtml($domain['phone_domain_name']) . ' unlinked', 'error');
+ redirect();
+
+}
diff --git a/agent/calls.php b/agent/calls.php
new file mode 100644
index 000000000..1e2770698
--- /dev/null
+++ b/agent/calls.php
@@ -0,0 +1,257 @@
+ Phone Systems), or one
+ * client's, or one contact's (contact_id). Each row is who it was with - the contact, else the
+ * caller ID name or number - the extension and agent on this side, when, how long they talked and
+ * how it ended, and the ticket it went on. Add to Ticket puts it on one of the client's open
+ * tickets, or a new one, as an internal note with its talk time
+ * (modals/phone/phone_call_ticket.php, agent/post/phone.php).
+ */
+
+// Default Column Sortby Filter
+$sort = "phone_call_started_at";
+$order = "DESC";
+
+// If client_id is in URI then show client Side Bar and client header
+if (isset($_GET['client_id'])) {
+ require_once "includes/inc_all_client.php";
+ $client_query = "AND phone_call_client_id = $client_id";
+ $client_url = "client_id=$client_id&";
+} else {
+ require_once "includes/inc_all.php";
+ $client_query = '';
+ $client_url = '';
+}
+
+enforceUserPermission('module_support');
+
+$page_title = 'Calls';
+
+if (!phoneSystemsExist()) { ?>
+
+
+
+ No phone system is set up - an admin adds one in Admin > Integrations > Phone Systems.
+
+
+ = 2;
+$statuses = phoneCallStatuses();
+$directions = phoneCallDirections();
+
+// One contact's calls - from their page
+$contact_filter = intval($_GET['contact_id'] ?? 0);
+$contact_filter_name = '';
+if ($contact_filter) {
+ $contact_row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_client_id FROM contacts WHERE contact_id = $contact_filter"));
+ if ($contact_row && hasClientAccess($contact_row['contact_client_id'])) {
+ $contact_filter_name = (string) $contact_row['contact_name'];
+ } else {
+ $contact_filter = 0;
+ }
+}
+$contact_query = $contact_filter ? "AND phone_call_contact_id = $contact_filter" : '';
+
+// The views - all of them, each way, missed ones, and callers nobody knows
+$shows = [
+ '' => ['label' => 'All', 'icon' => 'fa-list', 'sql' => '1 = 1'],
+ 'inbound' => ['label' => 'Inbound', 'icon' => 'fa-arrow-down', 'sql' => "phone_call_direction = 'inbound'"],
+ 'outbound' => ['label' => 'Outbound', 'icon' => 'fa-arrow-up', 'sql' => "phone_call_direction = 'outbound'"],
+ 'missed' => ['label' => 'Missed', 'icon' => 'fa-phone-slash', 'sql' => "phone_call_direction = 'inbound' AND phone_call_status IN ('missed', 'voicemail')"],
+ 'unknown' => ['label' => 'Unknown', 'icon' => 'fa-question', 'sql' => "phone_call_direction <> 'local' AND phone_call_contact_id = 0", 'title' => 'With numbers that aren\'t a contact\'s'],
+];
+$show = isset($shows[$_GET['show'] ?? '']) ? (string) ($_GET['show'] ?? '') : '';
+
+$scope = clientScopeSql('phone_call_client_id') . " $client_query $contact_query";
+$view_counts = [];
+foreach ($shows as $key => $view) {
+ $view_counts[$key] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM phone_calls WHERE {$view['sql']} $scope"))[0]);
+}
+$filter_url = function (array $change) {
+ $get = array_merge($_GET, $change);
+ unset($get['page']);
+ $get = array_filter($get, function ($value) {
+ return $value !== null && $value !== '';
+ });
+ return '?' . http_build_query($get);
+};
+
+// Only these sort - an unknown column would take the page down
+$sortable_columns = [
+ 'phone_call_started_at' => "phone_call_started_at $order",
+ 'who' => "COALESCE(contact_name, NULLIF(phone_call_name, ''), phone_call_number) $order, phone_call_started_at DESC",
+ 'client_name' => "client_name IS NULL, client_name $order, phone_call_started_at DESC",
+ 'phone_call_extension' => "phone_call_extension = '', phone_call_extension $order, phone_call_started_at DESC",
+ 'phone_call_talk_seconds' => "phone_call_talk_seconds $order, phone_call_started_at DESC",
+];
+if (!isset($sortable_columns[$sort])) {
+ $sort = 'phone_call_started_at';
+}
+
+$phone_digits = preg_replace('/\D/', '', (string) $q);
+$number_search = strlen($phone_digits) >= 3 ? " OR phone_call_number LIKE '%" . escapeSql($phone_digits) . "%' OR phone_call_dialed LIKE '%" . escapeSql($phone_digits) . "%'" : '';
+
+$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS phone_calls.*, phone_system_kind, phone_system_name, phone_system_web_url,
+ contact_name, client_name, ticket_prefix, ticket_number, ticket_subject, user_name
+ FROM phone_calls
+ LEFT JOIN phone_systems ON phone_system_id = phone_call_system_id
+ LEFT JOIN contacts ON contact_id = phone_call_contact_id AND phone_call_contact_id > 0
+ LEFT JOIN clients ON client_id = phone_call_client_id AND phone_call_client_id > 0
+ LEFT JOIN tickets ON ticket_id = phone_call_ticket_id AND phone_call_ticket_id > 0
+ LEFT JOIN users ON users.user_id = phone_call_user_id AND phone_call_user_id > 0
+ WHERE {$shows[$show]['sql']} $scope
+ AND (contact_name LIKE '%$q%' OR phone_call_name LIKE '%$q%' OR client_name LIKE '%$q%' OR phone_call_extension LIKE '%$q%' OR user_name LIKE '%$q%'$number_search)
+ ORDER BY {$sortable_columns[$sort]}, phone_call_id DESC
+ LIMIT $record_from, $record_to");
+
+$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
+
+?>
+
+
+
+
Calls
+
+ with = escapeHtml($contact_filter_name) ?>
+
+
+
+
+
diff --git a/agent/includes/inc_all_client.php b/agent/includes/inc_all_client.php
index b7deda352..cdbb282c7 100644
--- a/agent/includes/inc_all_client.php
+++ b/agent/includes/inc_all_client.php
@@ -279,6 +279,9 @@ if (isset($_GET['client_id'])) {
// The trips this agent may see - all of them with Financial access, else their own
[$num_trips] = tripTotalsFor('trip_client_id', $client_id);
+ // Calls from the phone systems in the last 30 days (functions/phone.php) - the menu shows Calls once there are any
+ $num_phone_calls = phoneSystemsExist() ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM phone_calls WHERE phone_call_client_id = $client_id AND phone_call_started_at >= NOW() - INTERVAL 30 DAY"))[0]) : 0;
+
}
}
diff --git a/agent/includes/side_nav.php b/agent/includes/side_nav.php
index 1952a0907..54a3b28ed 100644
--- a/agent/includes/side_nav.php
+++ b/agent/includes/side_nav.php
@@ -131,6 +131,20 @@
+
+
';
+}
+
+/** A call by id, with its contact, client, ticket and system - raw, or null */
+function phoneCallRow($phone_call_id): ?array
+{
+ global $mysqli;
+ $phone_call_id = intval($phone_call_id);
+ if (!$phone_call_id || !phoneTablesReady()) {
+ return null;
+ }
+ return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT phone_calls.*, phone_systems.*, phone_domain_name, contact_name, client_name,
+ ticket_prefix, ticket_number, ticket_subject, user_name
+ FROM phone_calls
+ JOIN phone_systems ON phone_system_id = phone_call_system_id
+ LEFT JOIN phone_domains ON phone_domain_id = phone_call_domain_id
+ LEFT JOIN contacts ON contact_id = phone_call_contact_id AND phone_call_contact_id > 0
+ LEFT JOIN clients ON client_id = phone_call_client_id AND phone_call_client_id > 0
+ LEFT JOIN tickets ON ticket_id = phone_call_ticket_id AND phone_call_ticket_id > 0
+ LEFT JOIN users ON users.user_id = phone_call_user_id AND phone_call_user_id > 0
+ WHERE phone_call_id = $phone_call_id")) ?: null;
+}
+
+/**
+ * The client a call belongs to for putting it on a ticket - 0 when it can go on any client's: a
+ * caller nobody knows, on your own company's line or a domain not linked.
+ */
+function phoneCallClientFor(array $call): int
+{
+ global $config_internal_client_id;
+ $client_id = intval($call['phone_call_client_id']);
+ if (!intval($call['phone_call_contact_id']) && ($client_id === 0 || $client_id === intval($config_internal_client_id ?? 0))) {
+ return 0;
+ }
+ return $client_id;
+}
+
+/** Who a call was with, for reading - the contact, the caller ID name, or the number */
+function phoneCallWho(array $call): string
+{
+ if (trim((string) ($call['contact_name'] ?? '')) !== '') {
+ return (string) $call['contact_name'];
+ }
+ if (trim((string) $call['phone_call_name']) !== '') {
+ return (string) $call['phone_call_name'];
+ }
+ return phoneNumberText($call['phone_call_number']) ?: 'Unknown caller';
+}
+
+/** A call in a sentence, for a ticket note - "Inbound call from Marla Whitfield (+1 (412) 555-0100) on ext 101, 4m 12s." Raw */
+function phoneCallSentence(array $call): string
+{
+ $direction = (string) $call['phone_call_direction'];
+ $who = phoneCallWho($call);
+ $number = phoneNumberText($call['phone_call_number']);
+ $with = $who . ($number !== '' && $number !== $who ? " ($number)" : '');
+ $label = $direction === 'outbound' ? "Outbound call to $with" : ($direction === 'local' ? "Internal call with $with" : "Inbound call from $with");
+ if ((string) $call['phone_call_extension'] !== '') {
+ $label .= ' on ext ' . $call['phone_call_extension'];
+ }
+ $status = (string) $call['phone_call_status'];
+ if ($status === 'answered') {
+ $label .= ', ' . phoneSecondsText($call['phone_call_talk_seconds']);
+ } else {
+ $label .= ' - ' . strtolower(phoneCallStatuses()[$status][0] ?? $status);
+ }
+ return $label . '.';
+}
+
+/**
+ * Put a call on a ticket - an internal note saying what the call was, with its talk time as the
+ * time worked (rounded up to the minute) when $count_time, and the call says which ticket it is on.
+ * The note's id.
+ */
+function phoneCallToTicket(array $call, array $ticket, int $user_id, bool $count_time, string $note = ''): int
+{
+ global $mysqli;
+
+ $ticket_id = intval($ticket['ticket_id']);
+ // Time talking to someone - not a voicemail box
+ $talk = $call['phone_call_status'] === 'answered' ? intval($call['phone_call_talk_seconds']) : 0;
+ $time_worked = $count_time && $talk > 0 ? phoneTimeWorked($talk) : '00:00:00';
+ $html = '