From bd62f4af22dc92fe27c5ce9139fb5580e082df06 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 21:24:27 -0500 Subject: [PATCH] Quotes: a line can carry its cost each and a markup, margin or set price in the Edit Line window, with quick-pick percentages and what the line makes, a line added from a product takes the product's cost, the cost shows under the line while the quote can be changed and the quote's Margin counts each line's own cost, all for agents only; Admin Settings Quotes sets the starting method, percent and quick picks; Copy Quote keeps each line's product; database 3.8.7 adds quote_items.item_cost, item_price_method and item_price_percent and the pricing settings; 26.11.9 changelog entries --- CHANGELOG.md | 5 +- admin/database_updates/3.8.7.php | 46 +++++ admin/post/settings_quote.php | 27 ++- admin/settings_quote.php | 15 +- agent/modals/billing/billing_item.php | 10 +- agent/post/quote.php | 10 +- db.sql | 6 + functions.php | 1 + functions/billing.php | 16 +- functions/products.php | 33 +-- functions/quote_pricing.php | 276 ++++++++++++++++++++++++++ functions/settings.php | 3 + includes/billing_paper.php | 5 +- js/billing_items.js | 104 ++++++++++ 14 files changed, 531 insertions(+), 26 deletions(-) create mode 100644 admin/database_updates/3.8.7.php create mode 100644 functions/quote_pricing.php diff --git a/CHANGELOG.md b/CHANGELOG.md index e3fc2efa6..3786d0071 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 database changes (3.6.6 to 3.8.6) 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, 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-one database changes (3.6.6 to 3.8.7) 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, and three columns on quote lines with three settings for what a quote line costs and how it is priced, 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 @@ -109,9 +109,11 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Tickets: the tickets list and board show +1, +2 after the lead when others are helping - Helping when one of them is you. A helper's booking is on the calendar in their color, can be dragged to a time of their own, shows in their calendar link, and counts when someone books them for something else at the same time. From Mountaineer IT's build of ITFlow. - Time zones: an agent who works away from the company can pick My time zone under Account > Preferences. The calendar, the ticket's booking, the Schedule window, New Event and Edit, and the event's quick look are then on their own clock, with a note saying so, and their booking emails give their time with the company's beside it. Bookings are still kept in the company's time, so the client's emails and calendar files, and everyone else's view, don't change. From Mountaineer IT's build of ITFlow. - Dispatch: a new page under Support puts each agent's booked work beside the tickets still to give out. The queue on the left has three tabs - No agent, Not booked (with an agent, nothing booked) and Left behind - most urgent first, with a search, a client and a priority filter. Day shows a column for each agent through the day; Week a row for each agent with a column for each day. Drag a ticket from the queue onto an agent and a time, or drag a booking to another agent or time, and the Schedule window opens with the agent, the time, how long and onsite or remote filled in - Schedule it gives the ticket to that agent and books it, emailing them the calendar file, the agent who had it the cancellation, and the contact and watchers unless you switch that off. Drag a booking back onto the queue to take it off the schedule. One-off events move the same way, to another time or agent. Workload shows each agent's open tickets (leading and helping), SLAs breached or close to it, tickets past due, not booked or gone quiet, and the hours booked today and this week against the working hours in Admin > SLA - flagged Falling behind, Watch, Overloaded or Has room against the team. Click an agent for their tickets, or drop a ticket from the queue on one to give it to them. Under it, This week shows tickets in and closed each day, against last week and the last four, the week's SLA results and each agent's share. Which agents show, the view and weekends are kept to your account, and an agent on their own time zone sees it on their clock. Seeing Dispatch takes Support in your role; booking from it takes Support at Modify. From Mountaineer IT's build of ITFlow. +- 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. ### Bug Fixes +- Quotes: Copy Quote dropped each line's link to the product it came from, so the copy's Margin left those lines out. The copy now keeps it. Found by Mountaineer IT. - Backups: restoring a backup rewrote the uploads folder's settings in a form Apache with PHP-FPM refuses - as HestiaCP, cPanel and Plesk run it - so your logo, avatars and photos stopped loading after a restore. Found by Mountaineer IT. - Contacts: archiving several contacts at once left the client's primary contact in place, as it should, but archived its client portal login, so they could no longer sign in. Found by Mountaineer IT. - Sign-in: an authenticator code of 000000 was taken as no code. Found by Mountaineer IT. @@ -237,6 +239,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.8.5: `ticket_helpers` (`ticket_id`, `user_id`, `follows_lead`, `schedule_start`, `schedule_end`, `added_by`, `added_at`; the lead stays `ticket_assigned_to`) - `functions/ticket_helpers.php`: `ticketHelpersReady()`, `ticketHelpers()`, `ticketHelperNames()`, `ticketHelpersTidy()` (a row for whoever is now the lead is cleared once a request, its booking cancelled and `ticketHelperLeadInvite()` sent), `ticketAssignedSql()` (Mine, the assigned filter and the dashboard's My tickets), `ticketHelperSave()`, `ticketHelperRemove()`, `ticketHelperMail()` (`ticketAgentEmailContent()`'s new `helper` kind; its own UID, `ticketHelperUid()`), `ticketHelpersLeadMoved()` from `ticketSetSchedule()` (their clashes join its conflicts), `ticketHelpersLeadCancelled()` from `ticketCancelSchedule()`, `ticketHelpersMailReplied()` from `ticketMailAssigneeReplied()`, `ticketHelperCalendarItems()` (kind `helper`, in the tickets source), `ticketHelperFeedItems()`, `ticketHelperDashboardItems()` and `ticketHelperConflicts()` (in `ticketScheduleConflicts()`). Helpers are `ticketMentionAgents()`. `agent/modals/ticket/ticket_helper.php`, `agent/post/ticket_helper.php` (`save_ticket_helper`, `remove_ticket_helper`), `ticketHelpersBadge()` in the list and board, and `calendar_move` with `kind` `helper` (their own time). From Mountaineer IT's build of ITFlow. - Database 3.8.6: `user_settings.user_config_timezone` (NULL is the company's) - `functions/user_timezone.php`: `timezoneUsersReady()`, `timezoneOwn()`, `timezoneOf()`, `timezoneView()`, `timezoneShifted()`, `timezoneConvert()`, `timezoneToView()` and `timezoneFromView()`; `timezoneField()` and `timezoneSave()` (`edit_your_user_preferences`, posting `timezone`). Times go out on the viewer's clock and come back in the company's: `calendar_items` and `calendar_day` turn the days asked for with `timezoneFromView()` and the items with `timezoneItems()`, `calendar_move` takes `timezoneMovePost()`, `add_event` and `edit_event` take `timezoneEventPost()`, `edit_ticket_schedule`, `add_ticket` and `save_ticket_helper` turn `scheduled_date_time` and `schedule` back, and the event form, Schedule window and helper window show `timezoneToView()` with `timezoneFormHint()`. `ticketScheduleShortText()` is on the viewer's clock with `timezoneAbbr()`; `timezoneEventWhenText()` is the quick look's; `agent/calendar.php` has `data-zone` and `timezoneNote()`, and `agent/js/calendar.js` sets `now` from it. `ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start, $end)` and the helper emails give the agent's time with `timezoneWhenFor()`. From Mountaineer IT's build of ITFlow. - Dispatch (`agent/dispatch.php`, `agent/js/dispatch.js`, `functions/dispatch.php`): `dispatchCan()` (Support at View), `dispatchCanEdit()` (`calendarCanScheduleTickets()`), `dispatchAgents()` (active agents who are admins or have Support at Modify, with `calendarAgentColor()`), `dispatchState()` / `dispatchStateSave()` (the `dispatch` key of `user_settings.user_config_calendar_state`, which `calendarUserStateSave()` now keeps: `view`, `hidden`, `weekends`), `dispatchBusinessHours()` and `dispatchWorkingDay()` from `getSlaSettings()`, `dispatchQueue($tab, $filters)` (`unassigned`, `unbooked`, `left_behind` via `calendarLeftBehindSql()`, with each tab's count), `dispatchItems($from, $to, $agent_ids)` (the tickets, helper bookings, events and holidays sources per agent, `extendedProps.agent` and `reference` added, only tickets and one-off events editable, through `timezoneItems()`), `dispatchBook()` (`ticketChangeAssignee()`, `ticketMailScheduleAgentCancelled()` for the agent who had it, then `ticketSetSchedule()`), `dispatchUnbook()` (`ticketCancelSchedule()`), `dispatchAssign()` (refused for a booked ticket), `dispatchEventMove()` (a one-off event in time and from one agent to another with `calendarEventSetAgents()`, `calendarSendInvites()` with `update` to those who have it), `dispatchWorkload()` with `dispatchWorkloadFlags()`, and `dispatchWeekStats()` (tickets given this week read from the `assigned the ticket to ` history lines). `agent/ajax.php`: GET `dispatch_queue`, `dispatch_items`, `dispatch_workload`, `dispatch_week`; POST (CSRF) `dispatch_state`, and with `dispatchCanEdit()`, after `timezoneMovePost()`, `dispatch_book`, `dispatch_unbook`, `dispatch_assign` and `dispatch_event_move` - JSON `{ok, message, conflicts}` or `{error}` with 400/403. `ticketSetSchedule()` and `ticketMailSchedule()` take `$tell_client` (default true) to leave the contact and watchers out. Day is a FullCalendar `timeGridDay` per agent in one scroller (`drop` for the queue's `FullCalendar.Interaction.Draggable`, `eventReceive` between columns, `eventDragStop` over the queue to unbook); Week and Workload use SortableJS. From Mountaineer IT's build of ITFlow. +- 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. ## [26.11.8] diff --git a/admin/database_updates/3.8.7.php b/admin/database_updates/3.8.7.php new file mode 100644 index 000000000..cd1a7827a --- /dev/null +++ b/admin/database_updates/3.8.7.php @@ -0,0 +1,46 @@ + 0; + }; + + if (!$itflow_column('quote_items', 'item_cost')) { + mysqli_query($mysqli, "ALTER TABLE `quote_items` ADD `item_cost` decimal(15,2) DEFAULT NULL AFTER `item_price`"); + } + if (!$itflow_column('quote_items', 'item_price_method')) { + mysqli_query($mysqli, "ALTER TABLE `quote_items` ADD `item_price_method` varchar(10) DEFAULT NULL AFTER `item_cost`"); + } + if (!$itflow_column('quote_items', 'item_price_percent')) { + mysqli_query($mysqli, "ALTER TABLE `quote_items` ADD `item_price_percent` decimal(7,2) DEFAULT NULL AFTER `item_price_method`"); + } + + if (!$itflow_column('settings', 'config_quote_price_method')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_quote_price_method` varchar(10) NOT NULL DEFAULT 'markup' AFTER `config_quote_notification_email`"); + } + if (!$itflow_column('settings', 'config_quote_price_percent')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_quote_price_percent` decimal(7,2) NOT NULL DEFAULT 20.00 AFTER `config_quote_price_method`"); + } + if (!$itflow_column('settings', 'config_quote_price_presets')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_quote_price_presets` varchar(100) NOT NULL DEFAULT '15,20,25,35' AFTER `config_quote_price_percent`"); + } diff --git a/admin/post/settings_quote.php b/admin/post/settings_quote.php index 90c6a8fde..874ce10c6 100644 --- a/admin/post/settings_quote.php +++ b/admin/post/settings_quote.php @@ -2,9 +2,10 @@ /* * Admin > Settings > Quotes (admin/settings_quote.php): - * edit_quote_settings saves the numbering, the footer and who is emailed a - * client's answer. A next number already in use, or an email address that - * isn't one, comes back to the page saying so - nothing is saved. + * edit_quote_settings saves the numbering, the footer, who is emailed a + * client's answer and the pricing a line starts with. A next number already + * in use, an email address that isn't one, or a % that can't be used, comes + * back to the page saying so - nothing is saved. */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); @@ -13,7 +14,8 @@ if (isset($_POST['edit_quote_settings'])) { validateCSRFToken(); - $before = settingsCurrent(['config_quote_prefix', 'config_quote_next_number', 'config_quote_footer', 'config_quote_notification_email']); + $pricing_columns = quotePricingReady() ? ['config_quote_price_method', 'config_quote_price_percent', 'config_quote_price_presets'] : []; + $before = settingsCurrent(array_merge(['config_quote_prefix', 'config_quote_next_number', 'config_quote_footer', 'config_quote_notification_email'], $pricing_columns)); // What was sent, and what is saved for anything that wasn't $in = $_POST + array_map(function ($value) { return (string) $value; }, $before); @@ -28,6 +30,23 @@ if (isset($_POST['edit_quote_settings'])) { if ($problem = settingsEmailProblem($after['config_quote_notification_email'])) { $errors['config_quote_notification_email'] = $problem; } + // How a line's price comes from its cost (functions/quote_pricing.php) + if ($pricing_columns) { + $method = quotePriceMethod($in['config_quote_price_method']); + $percent = quotePricingNumber($in['config_quote_price_percent']); + $presets = quotePricePresets($in['config_quote_price_presets']); + $after['config_quote_price_method'] = in_array($method, ['markup', 'margin'], true) ? $method : 'markup'; + $after['config_quote_price_percent'] = $percent === null ? '' : number_format($percent, 2, '.', ''); + $after['config_quote_price_presets'] = implode(',', array_map('quotePricePercentText', $presets)); + if ($percent === null || $percent < 0 || $percent >= 1000) { + $errors['config_quote_price_percent'] = 'A number from 0 to 999.'; + } elseif ($after['config_quote_price_method'] === 'margin' && $percent >= 100) { + $errors['config_quote_price_percent'] = 'A margin has to be under 100%.'; + } + if (!$presets) { + $errors['config_quote_price_presets'] = 'At least one %, such as 15, 20, 25.'; + } + } if ($errors) { settingsRefuse('quote', $errors); } diff --git a/admin/settings_quote.php b/admin/settings_quote.php index 38651770f..b25733213 100644 --- a/admin/settings_quote.php +++ b/admin/settings_quote.php @@ -2,7 +2,8 @@ /* * Admin > Settings > Quotes - how quotes are numbered, the footer under each - * one, and who hears when a client accepts or declines one online. Saved by + * one, who hears when a client accepts or declines one online, and how a + * line's price comes from its cost (functions/quote_pricing.php). Saved by * edit_quote_settings (admin/post/settings_quote.php). */ @@ -31,6 +32,18 @@ echo settingsPageStart('quote'); 'placeholder' => 'sales@company.com', 'help' => 'A shared mailbox or list works best. Empty, nobody is emailed - the quote still shows the answer.']) ?> + + + 'Markup - a % added to the cost', 'margin' => 'Margin - a % of the price'], ['icon' => 'fa-calculator', + 'help' => 'What a line is priced by when a cost is typed in. Markup 25% on a cost of 80.00 is 100.00; margin 25% on 80.00 is 106.67.']) ?> + 'fa-percent', 'inputmode' => 'decimal', 'maxlength' => 8, + 'help' => 'The % a line starts with.']) ?> + 'fa-hand-pointer', 'maxlength' => 100, + 'placeholder' => '15, 20, 25, 35', 'help' => 'The % buttons in a quote line\'s Edit window, to pick one in a click - up to eight, separated by commas.']) ?> + + + diff --git a/agent/modals/billing/billing_item.php b/agent/modals/billing/billing_item.php index 3246c878d..121e72719 100644 --- a/agent/modals/billing/billing_item.php +++ b/agent/modals/billing/billing_item.php @@ -8,7 +8,9 @@ * A line from a product keeps its link to the product; on an invoice, * changing the quantity of a stocked product moves the stock with it. On a * recurring invoice, the quantity can come from the client instead - their - * users, devices or a license's seats, counted again for each invoice. + * users, devices or a license's seats, counted again for each invoice. On a + * quote, what the line costs you and how its price comes from that - a + * markup, a margin or a set price (functions/quote_pricing.php). */ require_once '../../../includes/modal_header.php'; @@ -254,6 +256,9 @@ ob_start();
+ + +
@@ -303,6 +308,9 @@ ob_start(); if (typeof itflowBillingSeatForm === 'function') { itflowBillingSeatForm(form, ); } + if (typeof itflowBillingPricingForm === 'function') { + itflowBillingPricingForm(form, { currency: , locale: }); + } })(); diff --git a/agent/post/quote.php b/agent/post/quote.php index ffcc6756f..51abf1308 100644 --- a/agent/post/quote.php +++ b/agent/post/quote.php @@ -105,7 +105,7 @@ if (isset($_POST['add_quote_copy'])) { mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Quote copied!', history_quote_id = $new_quote_id"); $sql_items = mysqli_query($mysqli,"SELECT item_description, item_id, item_name, item_order, item_price, item_quantity, item_subtotal, - item_tax, item_tax_id, item_total, item_frequency FROM quote_items WHERE item_quote_id = $quote_id"); + item_tax, item_tax_id, item_total, item_frequency, item_product_id" . (quotePricingReady() ? ', item_cost, item_price_method, item_price_percent' : '') . " FROM quote_items WHERE item_quote_id = $quote_id"); while($row = mysqli_fetch_assoc($sql_items)) { $item_id = intval($row['item_id']); $item_name = escapeSql($row['item_name']); @@ -119,8 +119,14 @@ if (isset($_POST['add_quote_copy'])) { $tax_id = intval($row['item_tax_id']); $item_frequency = quoteFrequency($row['item_frequency']); $item_frequency = $item_frequency === '' ? 'NULL' : "'$item_frequency'"; + // The product it came from, while there is one, and its cost and how it is priced (functions/quote_pricing.php) + $item_product_id = intval($row['item_product_id']); + if ($item_product_id && !getFieldById('products', $item_product_id, 'product_id')) { + $item_product_id = 0; + } + $item_pricing = quotePricingCopySql($row); - mysqli_query($mysqli,"INSERT INTO quote_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $item_quantity, item_price = $item_price, item_subtotal = $item_subtotal, item_tax = $item_tax, item_total = $item_total, item_order = $item_order, item_tax_id = $tax_id, item_frequency = $item_frequency, item_quote_id = $new_quote_id"); + mysqli_query($mysqli,"INSERT INTO quote_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $item_quantity, item_price = $item_price, item_subtotal = $item_subtotal, item_tax = $item_tax, item_total = $item_total, item_order = $item_order, item_tax_id = $tax_id, item_frequency = $item_frequency, item_product_id = $item_product_id$item_pricing, item_quote_id = $new_quote_id"); } billingRecalc('quote', $new_quote_id); diff --git a/db.sql b/db.sql index 047a55e7a..64349d6f6 100644 --- a/db.sql +++ b/db.sql @@ -2527,6 +2527,9 @@ CREATE TABLE `quote_items` ( `item_description` text DEFAULT NULL, `item_quantity` decimal(15,2) NOT NULL DEFAULT 0.00, `item_price` decimal(15,2) NOT NULL DEFAULT 0.00, + `item_cost` decimal(15,2) DEFAULT NULL, + `item_price_method` varchar(10) DEFAULT NULL, + `item_price_percent` decimal(7,2) DEFAULT NULL, `item_subtotal` decimal(15,2) NOT NULL DEFAULT 0.00, `item_tax` decimal(15,2) NOT NULL DEFAULT 0.00, `item_total` decimal(15,2) NOT NULL DEFAULT 0.00, @@ -3354,6 +3357,9 @@ CREATE TABLE `settings` ( `config_quote_from_name` varchar(200) DEFAULT NULL, `config_quote_from_email` varchar(200) DEFAULT NULL, `config_quote_notification_email` varchar(200) DEFAULT NULL, + `config_quote_price_method` varchar(10) NOT NULL DEFAULT 'markup', + `config_quote_price_percent` decimal(7,2) NOT NULL DEFAULT 20.00, + `config_quote_price_presets` varchar(100) NOT NULL DEFAULT '15,20,25,35', `config_ticket_prefix` varchar(200) DEFAULT NULL, `config_ticket_next_number` int(11) DEFAULT NULL, `config_ticket_from_name` varchar(200) DEFAULT NULL, diff --git a/functions.php b/functions.php index 4425a1af1..c86dfc0a6 100644 --- a/functions.php +++ b/functions.php @@ -93,6 +93,7 @@ require_once __DIR__ . '/functions/contract_signature.php'; require_once __DIR__ . '/functions/contract_hours.php'; require_once __DIR__ . '/functions/contract_billing.php'; require_once __DIR__ . '/functions/products.php'; +require_once __DIR__ . '/functions/quote_pricing.php'; require_once __DIR__ . '/functions/billing_email.php'; require_once __DIR__ . '/functions/billing_pay.php'; require_once __DIR__ . '/functions/payment_provider.php'; diff --git a/functions/billing.php b/functions/billing.php index a053c3ae0..0e8f48042 100644 --- a/functions/billing.php +++ b/functions/billing.php @@ -114,6 +114,10 @@ function billingItems($type, $id) { return $items; } $seat_columns = $type === 'recurring' ? ', item_seat_source, item_seat_filter, item_seat_minimum' : ($type === 'quote' ? ', item_frequency' : ''); + // A quote line's cost and how it is priced (functions/quote_pricing.php) - agents only + if ($type === 'quote' && quotePricingReady()) { + $seat_columns .= ', item_cost, item_price_method, item_price_percent'; + } $sql = mysqli_query($mysqli, "SELECT item_id, item_name, item_description, item_quantity, item_price, item_subtotal, item_tax, item_total, item_order, item_tax_id, item_product_id, item_created_at, tax_name, tax_percent $seat_columns FROM {$t['items']} @@ -319,7 +323,8 @@ function billingCanEditItems($type, $row) { /** * Add a line to a document, or change one. $in: name, description, qty, - * price, tax_id, product_id. For an invoice, a tracked product's stock goes + * price, tax_id, product_id; on a quote, pricing with cost, price_method and + * price_percent (quotePricingSetSql()). For an invoice, a tracked product's stock goes * down by what the line takes (and back up if the quantity drops). The * document's total follows. The line's id, or null with $error. */ @@ -409,6 +414,11 @@ function billingItemSave($type, $doc_id, array $in, $item_id = 0, &$error = '') $product_id = 0; } + // A quote line's cost and how its price comes from it - as sent, or a new line from a product takes its cost (functions/quote_pricing.php) + if ($type === 'quote') { + $seat_set .= quotePricingSetSql($in, !$item_id, $product_id); + } + // Stock moves only with invoices, and only for products whose stock is tracked $stock_change = 0; if ($type === 'invoice' && $product_id && intval(getFieldById('products', $product_id, 'product_track_stock')) === 1) { @@ -1573,9 +1583,11 @@ function billingCopyLines(array $items, $to_type, $to_id, $suffix = '') { if ($product_id && !getFieldById('products', $product_id, 'product_id')) { $product_id = 0; } + // A quote line's cost and pricing go with it to another quote - an invoice is made from the price alone + $pricing = $to_type === 'quote' ? quotePricingCopySql($item) : ''; mysqli_query($mysqli, "INSERT INTO {$t['items']} SET item_name = '$name', item_description = '$description', item_quantity = " . floatval($item['item_quantity']) . ", item_price = " . floatval($item['item_price']) . ", item_subtotal = " . floatval($item['item_subtotal']) . ", item_tax = " . floatval($item['item_tax']) . ", - item_total = " . floatval($item['item_total']) . ", item_order = $order, item_tax_id = " . intval($item['item_tax_id']) . ", item_product_id = $product_id, {$t['item_fk']} = $to_id"); + item_total = " . floatval($item['item_total']) . ", item_order = $order, item_tax_id = " . intval($item['item_tax_id']) . ", item_product_id = $product_id$pricing, {$t['item_fk']} = $to_id"); $new_item_id = intval(mysqli_insert_id($mysqli)); // On an invoice, a tracked product comes off the shelf - check first with productStockShortfall() if ($to_type === 'invoice' && $product_id && floatval($item['item_quantity']) > 0 && intval(getFieldById('products', $product_id, 'product_track_stock')) === 1) { diff --git a/functions/products.php b/functions/products.php index f218d5594..506bc0294 100644 --- a/functions/products.php +++ b/functions/products.php @@ -1113,11 +1113,12 @@ function productRepriceApply(array $changes, &$error = '') { } /** - * The margin on a document's lines that come from a product with a cost, at - * today's cost - for the agent's eyes only. By how often each line is billed - * for a quote ('' once, month, quarter, year), otherwise under ''. Each: - * ['cost', 'revenue', 'margin', 'percent', 'lines']. Empty when no line has a - * cost to go on. + * The margin on a document's lines that have a cost - a quote line's own cost + * (functions/quote_pricing.php), else the cost of the product it came from, + * at today's cost - for the agent's eyes only. By how often each line is + * billed for a quote ('' once, month, quarter, year), otherwise under ''. + * Each: ['cost', 'revenue', 'margin', 'percent', 'lines']. Empty when no line + * has a cost to go on. */ function billingMargin($type, array $items) { global $mysqli; @@ -1127,23 +1128,24 @@ function billingMargin($type, array $items) { $ids[intval($item['item_product_id'])] = true; } } - if (!$ids) { - return []; - } $costs = []; - $sql = mysqli_query($mysqli, "SELECT product_id, product_cost FROM products WHERE product_cost > 0 AND product_id IN (" . implode(',', array_keys($ids)) . ")"); - while ($row = mysqli_fetch_assoc($sql)) { - $costs[intval($row['product_id'])] = floatval($row['product_cost']); + if ($ids) { + $sql = mysqli_query($mysqli, "SELECT product_id, product_cost FROM products WHERE product_cost > 0 AND product_id IN (" . implode(',', array_keys($ids)) . ")"); + while ($row = mysqli_fetch_assoc($sql)) { + $costs[intval($row['product_id'])] = floatval($row['product_cost']); + } } $groups = []; foreach ($items as $item) { $id = intval($item['item_product_id'] ?? 0); - if (!isset($costs[$id])) { + // The line's own cost, when it has one - 0 is a cost too (a freebie) + $line_cost = isset($item['item_cost']) && $item['item_cost'] !== '' ? floatval($item['item_cost']) : ($costs[$id] ?? null); + if ($line_cost === null) { continue; } $key = $type === 'quote' ? quoteFrequency($item['item_frequency'] ?? '') : ''; $groups[$key] = $groups[$key] ?? ['cost' => 0.0, 'revenue' => 0.0, 'lines' => 0]; - $groups[$key]['cost'] += round(floatval($item['item_quantity']) * $costs[$id], 2); + $groups[$key]['cost'] += round(floatval($item['item_quantity']) * $line_cost, 2); $groups[$key]['revenue'] += floatval($item['item_subtotal']); $groups[$key]['lines']++; } @@ -1173,5 +1175,8 @@ function billingMarginHtml($type, array $items, $currency, $period = '') { $tone = $group['margin'] < 0 ? 'text-danger-emphasis' : ''; $parts[] = '' . escapeHtml(billingMoney($group['margin'], $currency)) . '' . $percent . escapeHtml($when); } - return '' . implode(', ', $parts) . ''; + $total = count($items); + $without = $total - $lines; + return '' . implode(', ', $parts) . ''; } diff --git a/functions/quote_pricing.php b/functions/quote_pricing.php new file mode 100644 index 000000000..44b3af9a7 --- /dev/null +++ b/functions/quote_pricing.php @@ -0,0 +1,276 @@ + Settings > Quotes has what + * a line is priced by when a cost is typed, its % and the % buttons offered. + * + * Columns (database 3.8.7): quote_items.item_cost, item_price_method and + * item_price_percent - the names and meanings MountaineerIT's build uses - and + * settings.config_quote_price_method, _percent and _presets. + */ + +/** How a line's price comes from its cost. */ +const QUOTE_PRICE_METHODS = ['markup' => 'Markup', 'margin' => 'Margin', 'price' => 'Set price']; + +/** Whether the 3.8.7 update has run. */ +function quotePricingReady() { + 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.8.7', '>='); + } + return $ready; +} + +/** A method as stored - markup, margin or price - or '' for anything else. */ +function quotePriceMethod($method) { + $method = strtolower(trim((string) $method)); + return isset(QUOTE_PRICE_METHODS[$method]) ? $method : ''; +} + +/** A % as it is read - 25, 12.5 - without trailing zeros. */ +function quotePricePercentText($percent) { + return rtrim(rtrim(number_format(floatval($percent), 2, '.', ''), '0'), '.'); +} + +/** The presets a comma list holds - each above 0 and under 1000, in the order typed, at most eight. */ +function quotePricePresets($text) { + $presets = []; + foreach (explode(',', (string) $text) as $part) { + $part = trim(str_replace('%', '', $part)); + if (is_numeric($part) && floatval($part) > 0 && floatval($part) < 1000) { + $presets[quotePricePercentText($part)] = round(floatval($part), 2); + } + } + return array_slice(array_values($presets), 0, 8); +} + +/** Admin > Settings > Quotes' pricing: method (markup or margin), percent, presets. Read once a request. */ +function quotePricingSettings() { + global $mysqli; + static $settings = null; + if ($settings !== null) { + return $settings; + } + $row = quotePricingReady() ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_quote_price_method, config_quote_price_percent, config_quote_price_presets FROM settings WHERE company_id = 1")) : null; + $method = quotePriceMethod($row['config_quote_price_method'] ?? ''); + $presets = quotePricePresets($row['config_quote_price_presets'] ?? ''); + $settings = [ + 'method' => in_array($method, ['markup', 'margin'], true) ? $method : 'markup', + 'percent' => isset($row['config_quote_price_percent']) && is_numeric($row['config_quote_price_percent']) ? floatval($row['config_quote_price_percent']) : 20.0, + 'presets' => $presets ?: [15, 20, 25, 35], + ]; + return $settings; +} + +/** The price a cost comes to - markup 25% on 80 is 100, margin 25% on 80 is 106.67. Null when it can't be worked out. */ +function quotePriceFromCost($cost, $method, $percent) { + $cost = floatval($cost); + $percent = floatval($percent); + if ($cost <= 0 || $percent < 0) { + return null; + } + if ($method === 'markup') { + return round($cost * (1 + $percent / 100), 2); + } + if ($method === 'margin' && $percent < 100) { + return round($cost / (1 - $percent / 100), 2); + } + return null; +} + +/** A typed amount or %, or null when left empty or not a number. */ +function quotePricingNumber($value) { + $value = trim(str_replace([',', '%', '$'], '', (string) $value)); + return $value === '' || !is_numeric($value) ? null : round(floatval($value), 2); +} + +/* + * What a form sent - cost, price_method and price_percent - made sense of: + * a negative cost or % is dropped, a margin of 100% or more (no price gives + * it) is dropped, and a set price has no %. [cost|null, method|'', percent|null]. + */ +function quotePricingFromInput(array $in) { + $cost = quotePricingNumber($in['cost'] ?? ''); + $method = quotePriceMethod($in['price_method'] ?? ''); + $percent = quotePricingNumber($in['price_percent'] ?? ''); + if ($cost !== null && ($cost < 0 || $cost >= 1e11)) { + $cost = null; + } + if ($method === 'price' || ($percent !== null && ($percent < 0 || $percent >= 100000)) || ($method === 'margin' && $percent !== null && $percent >= 100)) { + $percent = null; + } + if ($cost === null && $method !== 'price') { + // Nothing to price from + $method = ''; + $percent = null; + } + return [$cost, $method, $percent]; +} + +/* + * The SET for a quote line's pricing, for billingItemSave(): what the Edit + * Line window sent (pricing = 1 with cost, price_method, price_percent), or - + * for a new line from a product with a cost - that cost and the product's + * price as a set price. '' leaves the line's pricing as it is (a change made + * where the line sits on the quote). + */ +function quotePricingSetSql(array $in, $is_new, $product_id) { + global $mysqli; + if (!quotePricingReady()) { + return ''; + } + if (!empty($in['pricing'])) { + [$cost, $method, $percent] = quotePricingFromInput($in); + } elseif ($is_new && intval($product_id)) { + $product_cost = floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT product_cost FROM products WHERE product_id = " . intval($product_id)))[0] ?? 0); + if ($product_cost <= 0) { + return ''; + } + [$cost, $method, $percent] = [round($product_cost, 2), 'price', null]; + } else { + return ''; + } + return ", item_cost = " . ($cost === null ? 'NULL' : $cost) + . ", item_price_method = " . ($method === '' ? 'NULL' : "'$method'") + . ", item_price_percent = " . ($percent === null ? 'NULL' : $percent); +} + +/** The SET that gives a copied quote line the pricing of the one it came from ($item a billingItems() row). '' before 3.8.7. */ +function quotePricingCopySql(array $item) { + if (!quotePricingReady() || !array_key_exists('item_cost', $item)) { + return ''; + } + $method = quotePriceMethod($item['item_price_method'] ?? ''); + return ", item_cost = " . ($item['item_cost'] === null ? 'NULL' : floatval($item['item_cost'])) + . ", item_price_method = " . ($method === '' ? 'NULL' : "'$method'") + . ", item_price_percent = " . ($item['item_price_percent'] === null ? 'NULL' : floatval($item['item_price_percent'])); +} + +/* + * How a line is priced now: its markup or margin while its price still comes + * from its cost; a price changed by hand since then is a set price. + */ +function quotePricingMethodNow($cost, $method, $percent, $price) { + $method = quotePriceMethod($method); + if (in_array($method, ['markup', 'margin'], true)) { + $worked = quotePriceFromCost($cost, $method, $percent); + if ($worked === null || abs($worked - floatval($price)) >= 0.01) { + return 'price'; + } + } + return $method; +} + +/* + * Under a line on the quote page, while it can be changed - its cost and how + * it is priced: "Cost $80.00 · Markup 25% · 20% margin". Agents only (never + * printed). '' for a line with no cost. + */ +function quotePricingLineHtml(array $item, $currency) { + if (!array_key_exists('item_cost', $item) || $item['item_cost'] === null || $item['item_cost'] === '') { + return ''; + } + $cost = floatval($item['item_cost']); + $price = floatval($item['item_price']); + $method = quotePricingMethodNow($cost, $item['item_price_method'] ?? '', $item['item_price_percent'] ?? 0, $price); + $parts = ['Cost ' . escapeHtml(billingMoney($cost, $currency))]; + if (in_array($method, ['markup', 'margin'], true)) { + $parts[] = QUOTE_PRICE_METHODS[$method] . ' ' . escapeHtml(quotePricePercentText($item['item_price_percent'])) . '%'; + } + $tone = 'bg-body-secondary text-body-secondary'; + if ($cost > 0 && $price > 0) { + $profit = $price - $cost; + $parts[] = $method === 'margin' + ? escapeHtml(number_format($profit / $cost * 100, 1)) . '% markup' + : escapeHtml(number_format($profit / $price * 100, 1)) . '% margin'; + if ($profit < 0) { + $tone = 'bg-danger-subtle text-danger-emphasis'; + } + } + return '
' + . '' . implode(' · ', $parts) . '
'; +} + +/* + * The Edit Line window's pricing, on a quote ($item a billingItems() row): + * your cost, Price by, the %, the % buttons and what the price comes to - + * itflowBillingPricingForm() (js/billing_items.js) works the Price out as + * they change. + */ +function quotePricingFields(array $item, $currency) { + if (!quotePricingReady()) { + return ''; + } + $settings = quotePricingSettings(); + $cost = $item['item_cost'] ?? null; + $has_cost = $cost !== null && $cost !== ''; + $method = $has_cost ? quotePricingMethodNow($cost, $item['item_price_method'] ?? '', $item['item_price_percent'] ?? 0, $item['item_price']) : ''; + if ($method === '') { + $method = $has_cost ? 'price' : $settings['method']; + } + $percent = in_array($method, ['markup', 'margin'], true) && $has_cost && $item['item_price_percent'] !== null + ? quotePricePercentText($item['item_price_percent']) : quotePricePercentText($settings['percent']); + ob_start(); ?> +
+
+ +
+ Your cost + Only agents see this - never the PDF, the guest link or the portal. +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
> + +
+ + +
+
+
+
> + + + +
+
+
+
+ ['page' => 'quote', 'section' => 'Numbering', 'label' => 'Next quote number', 'words' => 'quote number counter'], 'config_quote_footer' => ['page' => 'quote', 'section' => 'Footer', 'label' => 'Quote footer', 'kind' => 'long', 'words' => 'quote footer terms text'], 'config_quote_notification_email' => ['page' => 'quote', 'section' => 'Answers', 'label' => 'Email quote answers to', 'words' => 'accepted declined notification email'], + 'config_quote_price_method' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Price lines by', 'kind' => 'select', 'words' => 'markup margin cost price profit'], + 'config_quote_price_percent' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Markup or margin %', 'words' => 'markup margin percent percentage cost'], + 'config_quote_price_presets' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Quick picks', 'words' => 'markup margin presets buttons percent'], // Invoices and billing 'config_invoice_prefix' => ['page' => 'invoice', 'section' => 'Numbering', 'label' => 'Invoice prefix', 'words' => 'invoice number inv prefix'], diff --git a/includes/billing_paper.php b/includes/billing_paper.php index 0abd40b3c..377fc78ca 100644 --- a/includes/billing_paper.php +++ b/includes/billing_paper.php @@ -14,7 +14,7 @@ * edit the lines can be changed here (agent pages): drag handles, * a menu on each line, the add field, and a line's name, * description, quantity, price and tax changed where they sit - * (js/billing_items.js) + * (js/billing_items.js); a quote line's cost under it * notes_edit the notes save in place (agent pages) * taxes billingTaxes(), the rates a line's tax is picked from * logo_url the company logo, relative to the page @@ -233,6 +233,9 @@ $paper_bill_lines = array_filter([
+ + + diff --git a/js/billing_items.js b/js/billing_items.js index 07157a242..819ec3b6d 100644 --- a/js/billing_items.js +++ b/js/billing_items.js @@ -147,6 +147,110 @@ function itflowBillingLineForm(root, options) { } } +/* + * A quote line's cost in the Edit Line window (functions/quote_pricing.php): + * Cost each, Price by (markup, margin or set price), the % and its buttons. + * A markup or margin works the Price out from the cost; typing the Price + * yourself makes it a set price. Under it, what the line makes each. + */ +function itflowBillingPricingForm(root, options) { + var box = root ? root.querySelector('[data-quote-pricing]') : null; + if (!box) { + return; + } + var opts = options || {}; + var cost = box.querySelector('[data-pricing-cost]'); + var method = box.querySelector('[data-pricing-method]'); + var percent = box.querySelector('[data-pricing-percent]'); + var percentWrap = box.querySelector('[data-pricing-percent-wrap]'); + var presets = box.querySelector('[data-pricing-presets]'); + var hint = box.querySelector('[data-pricing-hint]'); + var price = root.querySelector('[data-line-price]'); + if (!cost || !method || !price) { + return; + } + var currency = box.getAttribute('data-currency') || opts.currency; + + function num(el) { + var n = el && el.value !== '' ? itflowBillingNumber(el.value) : NaN; + return isNaN(n) ? null : n; + } + + function update(fromPrice) { + var how = method.value; + var c = num(cost); + var pct = num(percent); + var setPrice = how === 'price'; + if (percentWrap) { + percentWrap.hidden = setPrice; + } + if (presets) { + presets.hidden = setPrice; + presets.querySelectorAll('[data-pricing-preset]').forEach(function (button) { + var on = pct !== null && Number(button.getAttribute('data-pricing-preset')) === pct; + button.classList.toggle('btn-secondary', on); + button.classList.toggle('btn-outline-secondary', !on); + }); + } + if (!fromPrice && !setPrice && c !== null && c > 0 && pct !== null && pct >= 0) { + var worked = how === 'markup' ? c * (1 + pct / 100) : (pct < 100 ? c / (1 - pct / 100) : null); + if (worked !== null) { + price.value = (Math.round(worked * 100) / 100).toFixed(2); + price.dispatchEvent(new Event('change', { bubbles: true })); + } + } + if (!hint) { + return; + } + var p = num(price); + hint.classList.remove('text-danger'); + if (c === null) { + hint.textContent = setPrice ? '' : 'Type the cost to work the price out.'; + return; + } + if (how === 'margin' && pct !== null && pct >= 100) { + hint.textContent = 'A margin has to be under 100%.'; + hint.classList.add('text-danger'); + return; + } + if (c <= 0 || p === null || p <= 0) { + hint.textContent = ''; + return; + } + var profit = p - c; + var markup = profit / c * 100; + var margin = profit / p * 100; + hint.textContent = 'Makes ' + itflowBillingMoney(profit, currency, opts.locale) + ' each - ' + + (how === 'margin' ? markup.toFixed(1) + '% markup' : (how === 'markup' ? margin.toFixed(1) + '% margin' : markup.toFixed(1) + '% markup, ' + margin.toFixed(1) + '% margin')); + hint.classList.toggle('text-danger', profit < 0); + } + + [cost, percent].forEach(function (el) { + if (el) { + el.addEventListener('input', function () { update(false); }); + } + }); + method.addEventListener('change', function () { update(false); }); + // Typing the price yourself makes it a set price - the hint still says what it makes + price.addEventListener('input', function (e) { + if (e.isTrusted && method.value !== 'price') { + method.value = 'price'; + method.dispatchEvent(new Event('change', { bubbles: true })); + } + update(true); + }); + if (presets) { + presets.addEventListener('click', function (e) { + var button = e.target.closest('[data-pricing-preset]'); + if (button && percent) { + percent.value = button.getAttribute('data-pricing-preset'); + update(false); + } + }); + } + update(true); +} + function itflowBillingItems(options) { var opts = options || {}; var paper = document.querySelector('.itflow-paper[data-billing-type]');