From 79f8f37df456ce3784134569db58ade82ca6f4a8 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 21:28:45 -0500 Subject: [PATCH] Offices: list other offices under Admin > Settings > Company Details with who works from each, pick an agent's office in Admin > Users and on invites, start new trips from the driver's office with From following the driver, and show the agent's office address and contact line at the foot of ticket emails; database 3.9.0 adds the offices table, users.user_office_id and user_invites.invite_office_id --- CHANGELOG.md | 4 +- admin/database_updates/3.9.0.php | 49 ++++ admin/modals/office/office.php | 127 ++++++++++ admin/modals/user/user_form.php | 3 +- admin/post/office.php | 45 ++++ admin/post/users.php | 7 +- admin/settings_company.php | 6 +- agent/modals/trip/trip_form.php | 23 +- api/v1/trips/trip_model.php | 4 +- db.sql | 27 ++ functions.php | 1 + functions/email.php | 9 +- functions/offices.php | 407 +++++++++++++++++++++++++++++++ functions/settings.php | 1 + functions/ticket.php | 6 +- functions/trips.php | 8 +- functions/user_invite.php | 13 +- 17 files changed, 719 insertions(+), 21 deletions(-) create mode 100644 admin/database_updates/3.9.0.php create mode 100644 admin/modals/office/office.php create mode 100644 admin/post/office.php create mode 100644 functions/offices.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 81efcf5da..6e77b0a58 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 twenty-three database changes (3.6.6 to 3.8.9) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, and two settings and a column on tickets for keeping project tickets apart, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's twenty-four database changes (3.6.6 to 3.9.0) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, and a table for your other offices with a column each on agents and invites for which one they work from, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -112,6 +112,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Quotes: a quote line can carry what it costs you, and its price can come from that cost. In a line's Edit window, Your cost has Cost each, Price by - Markup (a % added to the cost), Margin (a % of the price) or Set price - and the %, with buttons for the ones you use most: the Price is worked out as you type, and says what the line makes each. Typing the Price yourself makes it a set price. A line added from a product takes the product's cost and keeps its price. On the quote, while it can be changed, each line with a cost shows it under its name with its markup or margin, and the quote's Margin counts each line's own cost. Only agents see any of it - never the PDF, the guest link, the client portal or the invoice made from the quote. Admin > Settings > Quotes has what a line is priced by to start with, its % and the quick picks. From Mountaineer IT's build of ITFlow. - Quotes: a quote line can have a picture beside its name - on the quote, the guest link, the client portal and the PDF. In the line's Edit window, upload one or paste a link: a picture, or the product's web page, whose main picture is taken. A product keeps a picture too, in its Edit window, and a quote line added from it takes a copy; copying a quote copies them. ITFlow keeps its own copy of each, made smaller, and only fetches from public websites. Admin > Settings > Quotes can switch pictures off. From Mountaineer IT's build of ITFlow. - Projects: a project's tickets can be kept apart from the service desk - switch on Keep project tickets apart under Admin > Settings > Projects. A ticket in a project is then left off the tickets list's Open, Unassigned, Needs reply and other views - it has a Projects view of its own - and out of the dashboard's unassigned count, the count beside Tickets in the menu and the Dispatch queue, and has no SLA: the project's dates are what count. It stays under Mine, Mentioned me, Closed and All, in Dispatch's Workload and on the calendar and Dispatch, drawn in the project's calendar color with the project named under it and, on the calendar, a dot in the agent's color. A ticket taken out of its project gets its SLA back counted from then, so it isn't overdue at once - and so do they all when the setting is switched off. Off to start with, so nothing changes until you switch it on. From Mountaineer IT's build of ITFlow. +- Offices: if you work from more than one place, list the others under Admin > Settings > Company Details, Offices - each with its name, address, phone and email, and who works there. An agent's office can also be picked in Admin > Users, and given with an invite. A new trip starts from the driver's office, From offers every office, and changing the driver on a new trip moves From to theirs unless you typed it. Emails about a ticket show the office of the agent on it - the one assigned, else the one sending - at the foot: its address, and its phone and email, or the main office's phone and the ticket email address when it has none. Invoices, quotes and contracts keep the main address. Removing an office puts those who worked there back in the main one. With no other office, nothing changes. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -244,6 +245,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.8.7: `quote_items.item_cost`, `item_price_method` (`markup`, `margin` or `price`) and `item_price_percent` - the names MountaineerIT's build uses - and `config_quote_price_method`, `config_quote_price_percent` and `config_quote_price_presets` - `quotePricingReady()`. `functions/quote_pricing.php`: `QUOTE_PRICE_METHODS`, `quotePricingSettings()` (read from `settings` directly, not `load_global_settings.php`), `quotePriceFromCost()`, `quotePricingFromInput()`, `quotePricingSetSql()` - `billingItemSave()` takes `pricing` with `cost`, `price_method` and `price_percent` on a quote, and gives a new line from a product its `product_cost` as a set price - `quotePricingCopySql()` (`add_quote_copy`, which now also keeps `item_product_id`, and `billingCopyLines()` to a quote), `quotePricingMethodNow()` (a markup or margin whose price was changed by hand reads as a set price), `quotePricingLineHtml()` (under the line in `includes/billing_paper.php` while `edit`) and `quotePricingFields()` with `itflowBillingPricingForm()` in `js/billing_items.js`. `billingItems()` returns the three columns for a quote; `billingMargin()` uses `item_cost` before the product's cost. The API's quote line read returns them as it returns every column. From Mountaineer IT's build of ITFlow. - Database 3.8.8: `quote_items.item_image`, `products.product_image` (paths under `uploads/`, the names MountaineerIT's build uses; their `uploads/mit_images/` files are taken as they are) and `config_quote_show_images` - `quoteImagesReady()`, `quoteImagesShown()`. `functions/quote_images.php`: `quoteImageStore()` redraws a JPG, PNG, GIF or WebP with GD at up to 800 pixels a side into `uploads/quote_images/<32 hex>.jpg|png`; `quoteImageFromUpload()`, `quoteImageFromUrl()` (the image, or a page's `og:image` / `twitter:image` / `image_src`) through `quoteImageFetch()` - http(s) on ports 80, 443, 8080 and 8443, every resolved address checked by `quoteImageIpIsPublic()` and pinned with `CURLOPT_RESOLVE`, no proxy, three redirects each checked, 8 MB and 25 seconds in all; `quoteImageSave($table, $id, $in, $files)` for `item_image` / `product_image` with `_url` and `_remove`, `quoteImageField()`, `quoteImageThumbHtml()`, `quoteImageFromProduct()` (a new quote line in `billingItemSave()`), `quoteImageCopySql()` (`add_quote_copy`, `billingCopyLines()` to a quote) and `quoteImagesDeleteFor()` (`billingItemDelete()`, `delete_quote`, deleting a client from the page or the API, the API's quote delete, demo data); `productDelete()` throws the product's away. `includes/billing_paper.php` and `billingPdfRender()` show it; the Edit Line and product windows post `multipart/form-data`, and `js/app.js` previews the file picked. From Mountaineer IT's build of ITFlow. - Database 3.8.9: `config_project_tickets_apart` (default 0), `config_project_ticket_color` (NULL is `PROJECT_TICKET_COLOR`) and `tickets.ticket_sla_from` (when the SLA counts from; NULL is `ticket_created_at`) - `projectTicketsReady()`. `functions/project_tickets.php`: `projectTicketsSettings()`, `projectTicketsApart()`, `projectTicketsServiceSql()` (the side menu's count, the dashboard's two unassigned counts, `dispatchQueue()`), `projectTicketsShows()` (`agent/tickets.php`'s views; not with a Project filter), `projectTicketsSlaOff()` - `applyTicketSla()` reads `ticket_project_id`, `ticket_sla_id`, `ticket_closed_at` and `ticket_sla_from`, gives an open project ticket SLA 0, leaves a done one with none, and counts targets from `ticket_sla_from` - `projectTicketLeft()` / `projectTicketMoved()` (`edit_ticket`, `edit_ticket_project`, bulk project, `projectAddTicket()`, `projectRemoveTicket()`, `projectDelete()`, the API's ticket update), `projectTicketsSwitched()` (the settings save) and `projectTicketsCalendarItems()` (the tickets source: `color`, `extendedProps.agent_color`, `project`; `agent/js/calendar.js` draws the dot). No cron job: every way a ticket's project changes calls it. From Mountaineer IT's build of ITFlow. +- Database 3.9.0: the `offices` table (the same `office_` columns as Mountaineer IT's `mit_offices`; `office_archived_at` when removed), `users.user_office_id` and `user_invites.invite_office_id` (0 is the main office - the `companies` row) - `officesReady()`. `functions/offices.php`: `offices()`, `office()`, `officeMain()`, `officesAll()`, `officeIdForUser()`, `officeSetUser()`, `officePeople()`, `officeSave()` / `officeRemove()` (`admin/post/office.php`: `save_office`, `remove_office`; the window is `admin/modals/office/office.php`), `officesSection()` (Company Details), `officeUserField()` / `officeUserSave()` (`add_user`, `edit_user`; `userInviteSave()` takes `office_id` and `userInviteAccept()` sets it), `officeTripStart()` / `officeTripPlaces()` / `officeTripStarts()` (the trip form, `tripStartPlaces()` and the API's trip create), and `officeTicketFoot()` - an `office` key (`address`, `contact`) on the four ticket emails that set `contact`, which `emailHtml()` puts in the foot in place of the company's address and contact line. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.9.0.php b/admin/database_updates/3.9.0.php new file mode 100644 index 000000000..d8a0fcb12 --- /dev/null +++ b/admin/database_updates/3.9.0.php @@ -0,0 +1,49 @@ + Settings > Company Details: + * offices - one row an office: its name, address, phone and email. Removed + * ones are kept (office_archived_at) for the record. + * users.user_office_id - the office an agent works from; 0 (the default) is + * the main one. + * user_invites.invite_office_id - the office an invited agent will work from, + * given to them when they accept. + * + * Re-runnable: the table is made and each column added only where it isn't there yet. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_column = function ($table, $column) use ($mysqli) { + $result = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$table' AND COLUMN_NAME = '$column' LIMIT 1"); + return $result && mysqli_num_rows($result) > 0; + }; + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `offices` ( + `office_id` int(11) NOT NULL AUTO_INCREMENT, + `office_name` varchar(100) NOT NULL, + `office_address` varchar(200) NOT NULL DEFAULT '', + `office_city` varchar(200) NOT NULL DEFAULT '', + `office_state` varchar(200) NOT NULL DEFAULT '', + `office_zip` varchar(200) NOT NULL DEFAULT '', + `office_country` varchar(200) NOT NULL DEFAULT '', + `office_phone_country_code` varchar(10) NOT NULL DEFAULT '', + `office_phone` varchar(200) NOT NULL DEFAULT '', + `office_email` varchar(200) NOT NULL DEFAULT '', + `office_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `office_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + `office_archived_at` datetime DEFAULT NULL, + PRIMARY KEY (`office_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + if (!$itflow_column('users', 'user_office_id')) { + mysqli_query($mysqli, "ALTER TABLE `users` ADD `user_office_id` int(11) NOT NULL DEFAULT 0 AFTER `user_role_id`"); + } + if (!$itflow_column('user_invites', 'invite_office_id')) { + mysqli_query($mysqli, "ALTER TABLE `user_invites` ADD `invite_office_id` int(11) NOT NULL DEFAULT 0 AFTER `invite_role_id`"); + } diff --git a/admin/modals/office/office.php b/admin/modals/office/office.php new file mode 100644 index 000000000..c5c29a1cd --- /dev/null +++ b/admin/modals/office/office.php @@ -0,0 +1,127 @@ + Settings > Company Details, Offices + * (functions/offices.php; saved by save_office and taken away by remove_office + * in admin/post/office.php). ?office_id= to change one. + */ + +require_once '../../includes/modal_header.php'; + +$office_id = intval($_GET['office_id'] ?? 0); +$office = $office_id ? office($office_id) : null; +$office_id = $office ? $office_id : 0; +$company = billingCompany(); +$localization = settingsLocalizationArrays(); +$agents = officeAgents(); +$people = officePeople(); +$offices = officesAll(); +$office_country = (string) ($office['country'] ?? $company['company_country'] ?? ''); +$phone_code = (string) ($office['phone_country_code'] ?? $company['company_phone_country_code'] ?? ''); + +ob_start(); + +if (!officesReady()) { ?> + + + + + + +
+ + + + + + +
+ +
What they can see and change. Roles
+ diff --git a/admin/post/office.php b/admin/post/office.php new file mode 100644 index 000000000..b52a272fc --- /dev/null +++ b/admin/post/office.php @@ -0,0 +1,45 @@ + Settings > Company Details, Offices (functions/offices.php): + * save_office adds or changes an office, and who works there, from its window + * (admin/modals/office/office.php); remove_office takes one away - those in it + * go back to the main office. + */ + +defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); + +if (isset($_POST['save_office'])) { + + validateCSRFToken(); + + $new = !intval($_POST['office_id'] ?? 0); + [$office_id, $error] = officeSave($_POST); + if ($error !== '') { + flashAlert(escapeHtml($error), 'error'); + redirect('settings_company.php#section-offices'); + } + $name = office($office_id)['name'] ?? ''; + + logAudit("Settings", $new ? "Create" : "Edit", "$session_name " . ($new ? 'added' : 'changed') . " the office " . escapeSql($name)); + flashAlert("Office " . escapeHtml($name) . " " . ($new ? 'added' : 'saved')); + redirect('settings_company.php#section-offices'); + +} + +if (isset($_GET['remove_office'])) { + + validateCSRFToken(); + + $office_id = intval($_GET['remove_office']); + $name = office($office_id)['name'] ?? ''; + if (!$office_id || !officeRemove($office_id)) { + flashAlert("That office isn't there any more - it may have been removed", 'error'); + redirect('settings_company.php#section-offices'); + } + + logAudit("Settings", "Delete", "$session_name removed the office " . escapeSql($name)); + flashAlert("Removed the office " . escapeHtml($name) . " - those who worked there are in the main office now"); + redirect('settings_company.php#section-offices'); + +} diff --git a/admin/post/users.php b/admin/post/users.php index ecbcd0e62..469a06759 100644 --- a/admin/post/users.php +++ b/admin/post/users.php @@ -62,7 +62,7 @@ if (isset($_POST['add_user'])) { if ($how === 'invite') { $saved = userInviteSave(['name' => $name, 'email' => $email, 'role_id' => $role_id, 'force_mfa' => $force_mfa, - 'access' => intval($role['role_is_admin']) ? [] : ($_POST['client_permission'] ?? [])], $_FILES['avatar'] ?? null); + 'access' => intval($role['role_is_admin']) ? [] : ($_POST['client_permission'] ?? []), 'office_id' => $_POST['office_id'] ?? 0], $_FILES['avatar'] ?? null); $invite_id = $saved['invite_id']; $mail = userInviteMailReady(); $send_error = ''; @@ -121,6 +121,7 @@ if (isset($_POST['add_user'])) { } $service_change = serviceAccountSave($user_id, $_POST); + officeUserSave($user_id, $_POST); logAudit("User", "Create", "$session_name created user " . escapeSql($name) . ($service_change !== '' ? ' as an API / service account' : ''), 0, $user_id); @@ -241,6 +242,10 @@ if (isset($_POST['edit_user'])) { if ($service_change !== '') { $changes[] = $service_change; } + $office_change = officeUserSave($user_id, $_POST); + if ($office_change !== '') { + $changes[] = $office_change; + } logAudit("User", "Edit", "$session_name edited user " . escapeSql($name) . ($changes ? ' - ' . escapeSql(implode(', ', $changes)) : ''), 0, $user_id); diff --git a/admin/settings_company.php b/admin/settings_company.php index d62b536f3..610203ac1 100644 --- a/admin/settings_company.php +++ b/admin/settings_company.php @@ -5,7 +5,9 @@ * quotes and emails: its name and tax ID, address, phone (with its country * code, following the country picked), email, website and logo, and the * client record that stands for it. Saved by edit_company; the logo is taken - * off by remove_company_logo (admin/post/settings_company.php). + * off by remove_company_logo (admin/post/settings_company.php). Its Offices + * section lists the other places you work from (functions/offices.php), each + * changed in its own window. */ require_once "includes/inc_all_admin.php"; @@ -74,6 +76,8 @@ echo settingsPageStart('company'); 'help' => 'Kept without its https://.']) ?> + + @@ -286,6 +288,9 @@ $unit = tripUnit(); var purpose = root.querySelector('[data-trip-purpose]'); var autoTo = ''; var autoMiles = false; + var starts = ; + var offices = ; + var autoFrom = true; function number(value) { var n = Number(String(value || '').replace(/[\s,]/g, '')); @@ -433,6 +438,22 @@ $unit = tripUnit(); autoBill = false; update(); }); + // A new trip starts from the driver's office - another driver moves From to theirs, unless it was typed + if (driver && offices.length) { + from.addEventListener('input', function (e) { + if (e.isTrusted) { + autoFrom = false; + } + }); + driver.addEventListener('change', function () { + var next = starts[driver.value] || ''; + var now = from.value.trim(); + if (next !== '' && next !== now && (autoFrom || now === '' || offices.indexOf(now) >= 0)) { + from.value = next; + routeChanged(); + } + }); + } // Their own vehicle, or not, as the driver's last trip was if (driver && own) { driver.addEventListener('change', function () { diff --git a/api/v1/trips/trip_model.php b/api/v1/trips/trip_model.php index d55adc81a..e6dd9776e 100644 --- a/api/v1/trips/trip_model.php +++ b/api/v1/trips/trip_model.php @@ -15,8 +15,8 @@ $sent = function ($field, $current) { $trip_in = [ 'date' => $sent('trip_date', $trip_row['trip_date'] ?? date('Y-m-d')), - // From the office, unless it says otherwise - 'source' => $sent('trip_source', $trip_row['trip_source'] ?? tripOfficeAddress()), + // From the driver's office, unless it says otherwise + 'source' => $sent('trip_source', $trip_row['trip_source'] ?? (officeTripStart($sent('trip_user_id', $session_user_id)) ?: tripOfficeAddress())), 'destination' => $sent('trip_destination', $trip_row['trip_destination'] ?? ''), 'purpose' => $sent('trip_purpose', $trip_row['trip_purpose'] ?? ''), // The distance one way - a round trip is twice it diff --git a/db.sql b/db.sql index cdaa0d41e..0567e77e2 100644 --- a/db.sql +++ b/db.sql @@ -2217,6 +2217,31 @@ CREATE TABLE `notifications` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `offices` +-- + +DROP TABLE IF EXISTS `offices`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `offices` ( + `office_id` int(11) NOT NULL AUTO_INCREMENT, + `office_name` varchar(100) NOT NULL, + `office_address` varchar(200) NOT NULL DEFAULT '', + `office_city` varchar(200) NOT NULL DEFAULT '', + `office_state` varchar(200) NOT NULL DEFAULT '', + `office_zip` varchar(200) NOT NULL DEFAULT '', + `office_country` varchar(200) NOT NULL DEFAULT '', + `office_phone_country_code` varchar(10) NOT NULL DEFAULT '', + `office_phone` varchar(200) NOT NULL DEFAULT '', + `office_email` varchar(200) NOT NULL DEFAULT '', + `office_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `office_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + `office_archived_at` datetime DEFAULT NULL, + PRIMARY KEY (`office_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `payment_methods` -- @@ -4532,6 +4557,7 @@ CREATE TABLE `user_invites` ( `invite_email` varchar(200) NOT NULL, `invite_name` varchar(200) NOT NULL, `invite_role_id` int(11) NOT NULL DEFAULT 0, + `invite_office_id` int(11) NOT NULL DEFAULT 0, `invite_force_mfa` tinyint(1) NOT NULL DEFAULT 0, `invite_client_access` text DEFAULT NULL, `invite_avatar` varchar(200) DEFAULT NULL, @@ -4636,6 +4662,7 @@ CREATE TABLE `users` ( `user_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), `user_archived_at` datetime DEFAULT NULL, `user_role_id` int(11) DEFAULT 0, + `user_office_id` int(11) NOT NULL DEFAULT 0, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/functions.php b/functions.php index 71a55ebad..d9fb955dd 100644 --- a/functions.php +++ b/functions.php @@ -74,6 +74,7 @@ require_once __DIR__ . '/functions/ticket_helpers.php'; require_once __DIR__ . '/functions/user_timezone.php'; require_once __DIR__ . '/functions/dispatch.php'; require_once __DIR__ . '/functions/project_tickets.php'; +require_once __DIR__ . '/functions/offices.php'; require_once __DIR__ . '/functions/ticket_status.php'; require_once __DIR__ . '/functions/ticket_template.php'; require_once __DIR__ . '/functions/ticket_template_transfer.php'; diff --git a/functions/email.php b/functions/email.php index 1f504ba1c..edc03352f 100644 --- a/functions/email.php +++ b/functions/email.php @@ -47,6 +47,8 @@ const EMAIL_REPLY_MARKER = '##- Please type your reply above this line -##'; * each item ['by', 'org', 'action', 'when', 'text' => plain text, 'client' => true for * the client's side] or ['gap' => how many are left out here] (ticketEmailHistory()) * contact the foot's contact line, in place of the company's phone, email and website + * office ['address', 'contact'] - the foot of another office (officeTicketFoot()), in place + * of the company's address and contact line; null for the company's own * footnote a line under the card - why they got it */ function emailHtml(array $email) { @@ -171,12 +173,13 @@ function emailHtml(array $email) { . $items . ''; } - $contact = array_key_exists('contact', $email) + $office = is_array($email['office'] ?? null) ? $email['office'] : null; + $contact = $office ? (string) ($office['contact'] ?? '') : (array_key_exists('contact', $email) ? (string) $email['contact'] - : implode(' · ', array_filter([$company['phone_display'] ?? '', $company['company_email'] ?? '', $company['company_website'] ?? ''])); + : implode(' · ', array_filter([$company['phone_display'] ?? '', $company['company_email'] ?? '', $company['company_website'] ?? '']))); $foot = array_filter([ $company_name, - formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '), + $office ? (string) ($office['address'] ?? '') : formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '), $contact, ]); diff --git a/functions/offices.php b/functions/offices.php new file mode 100644 index 000000000..ddac82e6a --- /dev/null +++ b/functions/offices.php @@ -0,0 +1,407 @@ + Settings > Company Details + * has it (office 0); the others are the offices table, listed and changed in + * the Offices section of that page (admin/modals/office/office.php, handled in + * admin/post/office.php). Contact details only - name, address, phone and + * email. The company name, logo, invoices, quotes and contracts stay the main + * company's. + * + * Each agent works from one (users.user_office_id; 0 is the main one), picked + * in the office's window or in Admin > Users - an invite carries it until it is + * accepted (user_invites.invite_office_id). Where it shows: + * - Trips: a new trip starts From the driver's office, From offers every + * office, and on a new trip changing the driver moves an untouched From to + * theirs (agent/modals/trip/trip_form.php). + * - Ticket emails: the foot shows the address, phone and email of the office + * of the agent on the ticket - the one assigned, else the one sending it + * ('office' on the email, read by emailHtml in functions/email.php). + * With no other office, everything is as it was. + */ + +/** Whether the 3.9.0 update has run. */ +function officesReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '3.9.0', '>='); + } + return $ready; +} + +/** What is read once a request - the offices, and who works where. officesForget() after a change. */ +function &officesCache() { + static $cache = []; + return $cache; +} + +function officesForget() { + $cache = &officesCache(); + $cache = []; +} + +/** The other offices - office_id => office, by name. $archived takes in the removed ones. */ +function offices($archived = false) { + global $mysqli; + $cache = &officesCache(); + if (!isset($cache['offices'])) { + $cache['offices'] = []; + if (officesReady()) { + $sql = mysqli_query($mysqli, "SELECT office_id, office_name, office_address, office_city, office_state, office_zip, office_country, + office_phone_country_code, office_phone, office_email, office_archived_at FROM offices ORDER BY office_name"); + while ($row = mysqli_fetch_assoc($sql)) { + $cache['offices'][intval($row['office_id'])] = officeShape($row); + } + } + } + return $archived ? $cache['offices'] : array_filter($cache['offices'], function ($office) { + return $office['archived_at'] === null; + }); +} + +/** An office in one shape - an offices row, or the company for the main one. */ +function officeShape(array $row) { + $office = [ + 'office_id' => intval($row['office_id'] ?? 0), + 'name' => (string) ($row['office_name'] ?? ''), + 'address' => (string) ($row['office_address'] ?? ''), + 'city' => (string) ($row['office_city'] ?? ''), + 'state' => (string) ($row['office_state'] ?? ''), + 'zip' => (string) ($row['office_zip'] ?? ''), + 'country' => (string) ($row['office_country'] ?? ''), + 'phone_country_code' => (string) ($row['office_phone_country_code'] ?? ''), + 'phone' => (string) ($row['office_phone'] ?? ''), + 'email' => (string) ($row['office_email'] ?? ''), + 'archived_at' => $row['office_archived_at'] ?? null, + ]; + $office['phone_display'] = $office['phone'] !== '' ? formatPhoneNumber($office['phone'], $office['phone_country_code']) : ''; + return $office; +} + +/** The main office - the company, as Company Details has it. */ +function officeMain() { + $company = billingCompany(); + return officeShape([ + 'office_id' => 0, + 'office_name' => 'Main office', + 'office_address' => $company['company_address'] ?? '', + 'office_city' => $company['company_city'] ?? '', + 'office_state' => $company['company_state'] ?? '', + 'office_zip' => $company['company_zip'] ?? '', + 'office_country' => $company['company_country'] ?? '', + 'office_phone_country_code' => $company['company_phone_country_code'] ?? '', + 'office_phone' => $company['company_phone'] ?? '', + 'office_email' => $company['company_email'] ?? '', + ]); +} + +/** An office by id (0 is the main one) - null when there is none, or it was removed (unless $archived). */ +function office($office_id, $archived = false) { + $office_id = intval($office_id); + return $office_id === 0 ? officeMain() : (offices($archived)[$office_id] ?? null); +} + +/** Every office, the main one first - office_id => office. */ +function officesAll() { + return [0 => officeMain()] + offices(); +} + +/** An office's address on one line, without the country. */ +function officeAddressLine(array $office, $separator = ' ') { + return formatAddress($office['address'], $office['city'], $office['state'], $office['zip'], '', $separator); +} + +/** The office an agent works from - 0 for the main one, and when theirs was removed. */ +function officeIdForUser($user_id) { + global $mysqli; + $cache = &officesCache(); + if (!isset($cache['users'])) { + $cache['users'] = []; + if (officesReady()) { + $sql = mysqli_query($mysqli, "SELECT user_id, user_office_id FROM users WHERE user_office_id > 0"); + while ($row = mysqli_fetch_row($sql)) { + $cache['users'][intval($row[0])] = intval($row[1]); + } + } + } + $office_id = $cache['users'][intval($user_id)] ?? 0; + return $office_id && isset(offices()[$office_id]) ? $office_id : 0; +} + +/** The office an agent works from - the main one when none. */ +function officeForUser($user_id) { + return office(officeIdForUser($user_id)) ?? officeMain(); +} + +/** An office picked in a form - its id when it is there (0 for the main one), else 0. */ +function officeIdFrom($value) { + $office_id = intval($value); + return $office_id && isset(offices()[$office_id]) ? $office_id : 0; +} + +/** Put an agent in an office (0 is the main one). */ +function officeSetUser($user_id, $office_id) { + global $mysqli; + $user_id = intval($user_id); + if (!$user_id || !officesReady()) { + return; + } + mysqli_query($mysqli, "UPDATE users SET user_office_id = " . officeIdFrom($office_id) . " WHERE user_id = $user_id"); + officesForget(); +} + +/** The agents an office can have - user_id => row (name and avatar): not archived, no API / service accounts. */ +function officeAgents() { + global $mysqli; + $agents = []; + $sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1 AND user_archived_at IS NULL" . serviceAccountsOutSql('users.user_service_account') . " ORDER BY user_name"); + while ($row = mysqli_fetch_assoc($sql)) { + $agents[intval($row['user_id'])] = $row; + } + return $agents; +} + +/** Who works where - office_id => [user_id, ...]; those in no other office are under 0. */ +function officePeople() { + $people = [0 => []]; + foreach (array_keys(officeAgents()) as $user_id) { + $people[officeIdForUser($user_id)][] = $user_id; + } + return $people; +} + +/* + * ---------- Admin > Settings > Company Details ---------- + */ + +/** The Offices section of Company Details - the main office and the others, who works in each, and Add an office. */ +function officesSection() { + if (!officesReady()) { + return ''; + } + $agents = officeAgents(); + $people = officePeople(); + ob_start(); ?> + +
+
+ + + + + + $office) { + $contact = array_filter([officeAddressLine($office, ', '), $office['phone_display'], $office['email']]); + $who = array_map(function ($user_id) use ($agents) { + return escapeHtml($agents[$user_id]['user_name'] ?? ''); + }, $people[$office_id] ?? []); + $more = count($who) > 8 ? count($who) - 6 : 0; ?> + + + + + + + +
OfficeWho works there
+
+ + + + Above + +
+
+
Nobody' ?> + + + +
+
+ +
Agents not put in another office work from the main one. An agent's office can be changed in Users too.
+
+ + 100) { + return [0, 'An office needs a name, up to 100 characters.']; + } + $email = trim((string) ($post['office_email'] ?? '')); + if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) { + return [0, 'That is not an email address.']; + } + $country = trim((string) ($post['office_country'] ?? '')); + if ($country !== '' && !in_array($country, settingsLocalizationArrays()['countries'], true)) { + return [0, 'Pick the country from the list.']; + } + $phone = mb_substr(preg_replace('/[^0-9]/', '', (string) ($post['office_phone'] ?? '')), 0, 200); + $code = $phone === '' ? '' : mb_substr(preg_replace('/[^0-9]/', '', (string) ($post['office_phone_country_code'] ?? '')), 0, 10); + $text = function ($key) use ($post) { + return escapeSql(mb_substr(trim((string) ($post[$key] ?? '')), 0, 200)); + }; + $set = "office_name = '" . escapeSql($name) . "', office_address = '" . $text('office_address') . "', office_city = '" . $text('office_city') . "', + office_state = '" . $text('office_state') . "', office_zip = '" . $text('office_zip') . "', office_country = '" . escapeSql($country) . "', + office_phone_country_code = '$code', office_phone = '$phone', office_email = '" . escapeSql($email) . "'"; + if ($office_id) { + mysqli_query($mysqli, "UPDATE offices SET $set WHERE office_id = $office_id"); + } else { + mysqli_query($mysqli, "INSERT INTO offices SET $set"); + $office_id = intval(mysqli_insert_id($mysqli)); + } + officesForget(); + + // Who works there: those picked move here, those taken off go back to the main office + if (isset($post['office_people_shown'])) { + $picked = array_map('intval', (array) ($post['office_people'] ?? [])); + foreach (officePeople() as $at => $user_ids) { + foreach ($user_ids as $user_id) { + if (in_array($user_id, $picked, true)) { + if ($at !== $office_id) { + officeSetUser($user_id, $office_id); + } + } elseif ($at === $office_id) { + officeSetUser($user_id, 0); + } + } + } + } + return [$office_id, '']; +} + +/** Remove an office - those in it go back to the main one, and invites waiting with it too. Kept, archived, for the record. */ +function officeRemove($office_id) { + global $mysqli; + $office_id = intval($office_id); + if (!$office_id || !isset(offices()[$office_id])) { + return false; + } + mysqli_query($mysqli, "UPDATE offices SET office_archived_at = NOW() WHERE office_id = $office_id"); + mysqli_query($mysqli, "UPDATE users SET user_office_id = 0 WHERE user_office_id = $office_id"); + mysqli_query($mysqli, "UPDATE user_invites SET invite_office_id = 0 WHERE invite_office_id = $office_id AND invite_accepted_at IS NULL"); + officesForget(); + return true; +} + +/* + * ---------- Admin > Users ---------- + */ + +/** The Office picker in the New / Edit user window - only once there is another office. $office_id is theirs. */ +function officeUserField($office_id) { + if (!officesReady() || !offices()) { + return ''; + } + $office_id = officeIdFrom($office_id); + ob_start(); ?> +
+ +
+ + +
+
Where they work from - their trips start there, and the emails about their tickets show its address and phone.
+
+ officeMain()] as $office) { + $line = officeAddressLine($office); + if ($line !== '' && !in_array($line, $places, true)) { + $places[] = $line; + } + } + return $places; +} + +/** Each driver's office address - driver id => address - for a new trip's From to follow the driver. Empty with no other office. */ +function officeTripStarts(array $driver_ids) { + if (!officesReady() || !offices()) { + return []; + } + $starts = []; + foreach ($driver_ids as $driver_id) { + $starts[intval($driver_id)] = officeAddressLine(officeForUser($driver_id)); + } + return $starts; +} + +/* + * ---------- Ticket emails ---------- + */ + +/** + * The foot of an email about a ticket, when the agent on it works from another + * office - the one assigned, else the agent sending it: ['address', 'contact'], + * the office's phone and email standing in for the company's (the company's + * when it has none). null for the main office - the company's foot then. + */ +function officeTicketFoot($row) { + global $session_user_id; + if (!is_array($row) || !officesReady() || !offices()) { + return null; + } + $user_id = intval($row['ticket_assigned_to'] ?? 0) ?: intval($session_user_id ?? 0); + $office_id = $user_id ? officeIdForUser($user_id) : 0; + if (!$office_id) { + return null; + } + $office = office($office_id); + $company = billingCompany(); + return [ + 'address' => formatAddress($office['address'], $office['city'], $office['state'], $office['zip'], $office['country'] !== '' ? $office['country'] : (string) ($company['company_country'] ?? ''), ', '), + 'contact' => implode(' · ', array_filter([ + $office['phone_display'] !== '' ? $office['phone_display'] : (string) ($company['phone_display'] ?? ''), + $office['email'] !== '' ? $office['email'] : (string) (ticketEmailFrom()['email'] ?? ''), + (string) ($company['company_website'] ?? ''), + ])), + ]; +} diff --git a/functions/settings.php b/functions/settings.php index 87572eac4..320cb6279 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -117,6 +117,7 @@ function settingsFields() { 'company_phone' => ['page' => 'company', 'section' => 'Contact', 'label' => 'Phone', 'words' => 'telephone number call'], 'company_email' => ['page' => 'company', 'section' => 'Contact', 'label' => 'Email', 'words' => 'email address contact'], 'company_website' => ['page' => 'company', 'section' => 'Contact', 'label' => 'Website', 'words' => 'web site url domain'], + 'offices' => ['page' => 'company', 'section' => 'Offices', 'label' => 'Offices', 'words' => 'office branch location site other offices second office where agents work'], 'company_logo' => ['page' => 'company', 'section' => 'Logo', 'label' => 'Logo', 'kind' => 'file', 'words' => 'logo image picture branding invoice'], 'config_internal_client_id' => ['page' => 'company', 'section' => 'Your own client record', 'label' => 'Your company\'s client record', 'kind' => 'client', 'words' => 'internal client own company msp internal tickets'], diff --git a/functions/ticket.php b/functions/ticket.php index 781bee9d5..2c60dfb11 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -325,7 +325,7 @@ function ticketGuestPath(array $row) { return 'guest_view_ticket.php?ticket_id=' . intval($row['ticket_id']) . '&url_key=' . rawurlencode((string) $row['ticket_url_key']); } -/** The foot's contact line on a ticket email - the company's phone and the support address. */ +/** The foot's contact line on a ticket email - the company's phone and the support address. Another office's is officeTicketFoot(). */ function ticketEmailContactLine() { $company = billingCompany(); return implode(' · ', array_filter([$company['phone_display'] ?? '', ticketEmailFrom()['email'], $company['company_website'] ?? ''])); @@ -467,6 +467,7 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { 'preview' => "$reference - $subject", 'tone' => 'primary', 'contact' => ticketEmailContactLine(), + 'office' => officeTicketFoot($row), 'button' => ['label' => 'View the ticket', 'url' => $url], ]; @@ -701,6 +702,7 @@ function ticketMailColleaguesNew($ticket_id) { 'summary' => ['Ticket' => $reference, 'Subject' => (string) $ticket['ticket_subject'], 'Priority' => (string) $ticket['ticket_priority'], 'Raised by' => $raised_by === 'We' ? 'Us' : $raised_by], 'button' => ['label' => $colleague['portal'] ? 'View it in the portal' : 'View the ticket', 'url' => $url], 'contact' => ticketEmailContactLine(), + 'office' => officeTicketFoot($ticket), ], ['from' => ticketEmailFrom()])); } return $sent; @@ -1094,6 +1096,7 @@ function ticketMailTaskApproval($approval_id, $by) { 'button' => ['label' => 'Review and approve', 'url' => "https://$config_base_url/guest/guest_approve_ticket_task.php?task_approval_id=" . intval($approval['approval_id']) . '&url_key=' . rawurlencode((string) $approval['approval_url_key'])], 'after' => ['Want to know more first? Just reply to this email.'], 'contact' => ticketEmailContactLine(), + 'office' => officeTicketFoot($row), ], ['from' => ticketEmailFrom(), 'sensitive' => true])); } @@ -1113,6 +1116,7 @@ function ticketMailClosedReply($ticket_id, $from_email) { 'intro' => ["You replied to ticket " . ticketReference($closed) . " - \"" . $closed['ticket_subject'] . "\" - which is closed, so your reply won't reach us.", "To raise a new ticket, send a new email to $support."], 'button' => ['label' => 'Email us', 'url' => "mailto:$support"], 'contact' => ticketEmailContactLine(), + 'office' => officeTicketFoot($closed), ], ['from' => ticketEmailFrom()])); } diff --git a/functions/trips.php b/functions/trips.php index 0ad72d428..aa58f0c78 100644 --- a/functions/trips.php +++ b/functions/trips.php @@ -317,14 +317,10 @@ function tripKnownRoutes($limit = 400) { return $routes; } -/** Where this agent has started from lately, most used first - for the From box to offer, with the office first. */ +/** Where this agent has started from lately, most used first - for the From box to offer, with every office first. */ function tripStartPlaces($limit = 6) { global $mysqli, $session_user_id; - $places = []; - $office = tripOfficeAddress(); - if ($office !== '') { - $places[] = $office; - } + $places = officeTripPlaces(); // the company's address, and every other office's (functions/offices.php) $sql = mysqli_query($mysqli, "SELECT trip_source, COUNT(*) AS n FROM trips WHERE trip_user_id = " . intval($session_user_id) . " AND trip_archived_at IS NULL GROUP BY trip_source ORDER BY n DESC LIMIT " . intval($limit)); while ($row = mysqli_fetch_row($sql)) { diff --git a/functions/user_invite.php b/functions/user_invite.php index d587fa893..0982e60b2 100644 --- a/functions/user_invite.php +++ b/functions/user_invite.php @@ -274,8 +274,9 @@ function userInviteAvatar(array $row, $size = '') { /** * Keep an invite for someone, from New User or Get started - $in name and - * email (checked already), role_id, force_mfa and access (the Client access - * radios: client_id => allow / deny / ''). One already waiting for the + * email (checked already), role_id, force_mfa, access (the Client access + * radios: client_id => allow / deny / '') and office_id (functions/offices.php, + * 0 or left out for the main office). One already waiting for the * address is changed to this, and keeps its picture unless $avatar has a new * one. ['invite_id', 'again' => true when one was waiting, 'avatar_error']. */ @@ -287,6 +288,7 @@ function userInviteSave(array $in, $avatar = null) { $role_id = intval($in['role_id']); $force_mfa = !empty($in['force_mfa']) ? 1 : 0; $by = intval($session_user_id); + $office_sql = officesReady() ? ', invite_office_id = ' . officeIdFrom($in['office_id'] ?? 0) : ''; // The rules for clients that exist $rules = ['allow' => [], 'deny' => []]; @@ -308,10 +310,10 @@ function userInviteSave(array $in, $avatar = null) { if ($open) { $invite_id = intval($open['invite_id']); mysqli_query($mysqli, "UPDATE user_invites SET invite_name = '$name_sql', invite_email = '$email_sql', invite_role_id = $role_id, invite_force_mfa = $force_mfa, - invite_client_access = $access_sql, invite_created_by = $by WHERE invite_id = $invite_id"); + invite_client_access = $access_sql, invite_created_by = $by$office_sql WHERE invite_id = $invite_id"); } else { mysqli_query($mysqli, "INSERT INTO user_invites SET invite_name = '$name_sql', invite_email = '$email_sql', invite_role_id = $role_id, invite_force_mfa = $force_mfa, - invite_client_access = $access_sql, invite_expires_at = NOW(), invite_created_by = $by"); + invite_client_access = $access_sql, invite_expires_at = NOW(), invite_created_by = $by$office_sql"); $invite_id = intval(mysqli_insert_id($mysqli)); } @@ -493,6 +495,9 @@ function userInviteAccept(array $invite, $token, array $in, &$error = '') { user_auth_method = 'local', user_type = 1, user_status = 1, user_role_id = $role_id"); $user_id = intval(mysqli_insert_id($mysqli)); mysqli_query($mysqli, "INSERT INTO user_settings SET user_id = $user_id, user_config_force_mfa = " . (intval($invite['invite_force_mfa']) ? 1 : 0)); + if (intval($invite['invite_office_id'] ?? 0)) { + officeSetUser($user_id, $invite['invite_office_id']); // the main office when theirs was removed since + } if (!intval($invite['role_is_admin'])) { $access = userInviteClientAccess($invite); userSetClientAccess($user_id, array_fill_keys(array_keys($access['allow']), 'allow') + array_fill_keys(array_keys($access['deny']), 'deny'));