From e2431748faa64a96c27c7f2ba7d06bb4b662304e Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 16 Oct 2026 16:13:36 -0400 Subject: [PATCH] Products makeover stage 3: sold hardware becomes client assets - products take an asset type, make, model and warranty in months, invoices with hardware get a Hardware card showing how many units are on the client's assets with their serials, an Add to Assets window with a row per unit for name, serial and assigned contact (Enter between serials for barcode scanning), make, model and warranty from the product counted from the invoice date, status and location for all, linking an asset the client already has or leaving rows for later, assets made this way are bought on the invoice date with its number as the order reference and link back to the invoice and product, a Client asset card and Assets tab on the product page, a Hardware tab and asset type on the products list, a dashboard Needs attention item for hardware sold in the last 90 days not yet on assets linking to a new invoices hardware filter, serials on the packing slip, asset type, make, model and warranty in product import and export, starter and demo hardware seeded with asset types, deleting a line or invoice unlinks its assets without removing them, database 2.9.6 with product asset columns and asset product, invoice and line links, CHANGELOG updated --- CHANGELOG.md | 25 +- admin/database_updates/2.9.6.php | 27 ++ admin/post/demo_data_model.php | 21 +- admin/post/starter_content_model.php | 30 ++- agent/asset.php | 24 +- agent/invoice.php | 61 +++++ agent/invoices.php | 18 +- agent/modals/invoice/invoice_assets.php | 284 ++++++++++++++++++++ agent/modals/product/product_export.php | 1 + agent/modals/product/product_form.php | 56 +++- agent/modals/product/product_import.php | 3 +- agent/post/invoice.php | 43 +++ agent/post/product.php | 15 +- agent/product.php | 105 +++++++- agent/products.php | 8 +- css/itflow_custom.css | 17 ++ db.sql | 11 +- functions/billing.php | 4 + functions/billing_pdf.php | 13 +- functions/dashboard.php | 10 + functions/export.php | 4 + functions/products.php | 338 +++++++++++++++++++++++- 22 files changed, 1069 insertions(+), 49 deletions(-) create mode 100644 admin/database_updates/2.9.6.php create mode 100644 agent/modals/invoice/invoice_assets.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f3dc6da2a..92d9a4861 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 2.9.5) in the same pass. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 2.9.6) in the same pass. Nothing else is required. -This is a big release, with sixteen database steps in one go, so take a backup before you update. +This is a big release, with seventeen database steps in one go, so take a backup before you update. The update also clears out data that deletes in older versions left behind, all of it pointing at something that no longer exists: @@ -17,7 +17,7 @@ The update also clears out data that deletes in older versions left behind, all - the tasks, approvals and history of deleted tickets, the projects of deleted clients, and tickets still pointing at a deleted project - project template entries whose ticket template is gone, and the same service link saved twice -It also gives every existing network a type (LAN, WAN, Guest and so on) guessed from its name or description, which you can change afterwards, and fills in the issue date, names covered and fingerprint of every certificate already on file. Invoices made from a quote before the update are linked to that quote, so each one shows where it came from. Products that ever had stock added keep tracking their stock, and the rest are set to ordered as needed (see Breaking Changes, Products). Their past stock changes are sorted into received, sold and returned from their notes, and linked to the invoice they name. +It also gives every existing network a type (LAN, WAN, Guest and so on) guessed from its name or description, which you can change afterwards, and fills in the issue date, names covered and fingerprint of every certificate already on file. Invoices made from a quote before the update are linked to that quote, so each one shows where it came from. Products that ever had stock added keep tracking their stock, and the rest are set to ordered as needed (see Breaking Changes, Products). Their past stock changes are sorted into received, sold and returned from their notes, and linked to the invoice they name. No product becomes a client asset when it is sold until you give it an asset type (see New Features, Products). If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below. @@ -124,7 +124,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - **Dashboard** (rebuilt) - Needs attention along the top: - tickets past their SLA, unassigned tickets and overdue projects - - overdue and draft invoices, resolved tickets not invoiced yet, and stock to reorder + - overdue and draft invoices, resolved tickets not invoiced yet, stock to reorder, and hardware sold in the last 90 days that isn't on the client's assets yet - domains, certificates, licenses and warranties expiring in the next 30 days - services needing attention and service reviews due @@ -263,8 +263,17 @@ If you are coming from 26.08 or earlier, the database update still has to be run - One Stock window to Receive (at a unit cost, which can become the product's cost, linked to an expense from the last year, the vendor's first), Count (type what is on the shelf and the difference is recorded) or Write off (damaged, lost or stolen, used by us, or sent back to the vendor). It shows what will be on the shelf as you type. - Reorder at and Order on each product. Products at or under their level show on the To reorder tab, with a badge on the list, on Products in the menu and in Needs attention on the dashboard. A Low Stock notification goes out when stock drops to the level or runs out, saying how many to order and from whom. - Count Stock lists every tracked product, or one location's, with what ITFlow has and a box for what you counted. The difference shows as you type, Enter moves to the next box, and blank ones are left alone. Print it as a count sheet to take to the shelf. - - Import takes every field, including Reorder At and Order. Categories, taxes and vendors are matched by name. A new price list can update products by their code, and a file with only Code and Price will do. Download the template for the layout. - - Export adds cost, margin, how it is billed, vendor, part number, stock and its value, and the reorder level, and can export just what is to reorder. + - Hardware becomes client assets: + - Give a product the asset it becomes - a laptop, a switch, an access point and so on - with its make, model and warranty in months. + - An invoice with hardware on it has a Hardware card: each line, how many of it are on the client's assets, and which ones with their serial numbers. + - Add to Assets has a row for each one still to add, named from the model, for its serial number and who has it. Enter after a serial, or a barcode scan, moves to the next one. The make, model and warranty (counted from the invoice date) come from the product and can be changed, and the status and location are set for all of them. A row can be linked to an asset the client already has instead, or taken out and left for later. + - Each asset made this way is bought on the invoice date with the invoice number as its order reference, and its page links to the invoice and the product. + - The product's page shows the asset it becomes and how many are in use, with an Assets tab listing each one with its client, serial number, warranty and invoice. + - Products has a Hardware tab, and each row says the asset it becomes. + - The packing slip lists the serial numbers under each line. + - The starter catalog's hardware comes with its asset type and warranty, and so does the demo data's. + - Import takes every field, including Reorder At, Order, Asset Type, Make, Model and Warranty. Categories, taxes and vendors are matched by name. A new price list can update products by their code, and a file with only Code and Price will do. Download the template for the layout. + - Export adds cost, margin, how it is billed, vendor, part number, stock and its value, the reorder level, and the asset it becomes with its make, model and warranty. It can export just what is to reorder, or just hardware. - Invoices, quotes and recurring invoices show agents their margin on lines from products with a cost, at today's cost. A quote shows it up front and each month. - Our vendors' pages have a Products tab listing what we buy from them. - Search finds products by part number and opens their page. @@ -511,6 +520,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 2.9.3: `quote_items.item_frequency` (NULL for one time, or `month`, `quarter` or `year`), `quotes.quote_monthly_amount`, `invoices.invoice_quote_id` and `recurring_invoices.recurring_invoice_quote_id`. Invoices are linked to their quote from the "Invoice created from quote QUO-n" history the old Make Invoice wrote, matched on the client too. - 2.9.4: `products.product_cost`, `product_vendor_id`, `product_vendor_part`, `product_notes`, `product_frequency` (NULL once, or `month`, `quarter`, `year`), `product_seat_source` (NULL, `contacts` or `assets`) and `product_track_stock`, set for products with any `product_stock` rows. Keys on `item_product_id` in `invoice_items`, `quote_items` and `recurring_invoice_items`, and on `product_stock.stock_product_id`. - 2.9.5: `product_stock.stock_qty` becomes `decimal(15,2)`, with `stock_type` (`received`, `sold`, `returned`, `adjusted` or `written_off`, default `adjusted`), `stock_unit_cost`, `stock_invoice_id` (keyed) and `stock_user_id`. Existing rows take their invoice from a note ending "Invoice n" and their type from the sign and the note. `products.product_reorder_level` and `product_reorder_qty`. + - 2.9.6: `products.product_asset_type` (one of the asset types, NULL for none), `product_make`, `product_model` and `product_warranty_months`. `assets.asset_product_id`, `asset_invoice_id` and `asset_invoice_item_id`, keyed on the product and the invoice. - New shared function files, loaded by `functions.php`: `functions/asset.php`, `asset_interface.php`, `certificate.php`, `client_overview.php`, `contact.php`, `credential.php`, `dashboard.php`, `links.php`, `location.php`, `notifications.php`, `project.php`, `rack.php`, `search.php`, `service.php`, `software.php`, `tags.php`, `ticket.php`, `ticket_fields.php`, `user.php` and `vendor.php`. They hold the queries and rules, so the pages, the API and cron share one definition. - Removed post models: `agent/post/{asset_interface,certificate,credential,domain,event,location,network_ip,network,recurring_ticket,vendor}_model.php`, `admin/post/user_model.php` and `api/v1/certificates/certificate_model.php`. Their handlers call the shared functions above. Interface handlers moved to `agent/post/asset_interface.php`. - New scripts: `js/itflow_select.js`, `quick_pick.js`, `tag_picker.js`, `global_search.js`, `notifications.js`, `dashboard.js`, `client_overview.js`, `client_switcher.js`, `credentials.js` and `autosubmit.js`, and `agent/js/calendar.js`, `calendar_event_modal.js`, `files.js`, `interface_form.js`, `network_form.js`, `project_modal.js` and `ticket_schedule_modal.js`. @@ -631,6 +641,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Handlers: `product_stock_save` (POST `product_id`, `mode` and `note`, with `qty`, `unit_cost`, `update_cost` and `expense` to receive, `counted` to count, or `qty` and `reason` to write off) from `agent/modals/product/product_stock.php?id=&mode=`, and `product_stock_count` (POST `counted[product_id]` and `note`) from the new page `agent/products_count.php`. Removed: `agent/modals/product/product_stock_add.php` and `add_product_stock`. - `productSave()` and `productCopy()` take `reorder_level` and `reorder_qty`, with import aliases and export columns for them and the stock value. The products list and export take `type=reorder`. - `$num_products_reorder` in `agent/includes/get_side_nav_counts.php`, `Stock to reorder` in `dashboardAttention()`, and `inventory` in `reportCatalog()` (Sales & Billing, `module_sales`, accounting) for `agent/reports/inventory.php`. + - Sold hardware, in `functions/products.php`: `productAssetTypes()` (the `$asset_types_array` list), `productAssetType()`, `productAssetIcon()`, `productHardwareSql()`, `productHardwareUnits()` (a line's quantity rounded up, none for a credit), `productWarrantyUntil()`, `productHardwareInvoiceSql()` (not drafts or cancelled, not made by a recurring invoice), `productHardwareShortSql()`, `productHardwarePending($days)`, `productInvoiceHardware($invoice_id)`, `productAssets($product_id)` and `productAssetCandidates()`. `productSaleAssets($invoice_id, $lines, $units, $shared, &$error)` checks every row first, then adds or links them in one transaction, each new one with its primary interface, and each with a history line and an audit log entry. + - Handler `invoice_assets_save` (POST `invoice_id`, `status`, `location`, `lines[item_id][make|model|warranty]` and `units[item_id][n][name|serial|contact|existing]`; needs Sales, and Support at edit) from `agent/modals/invoice/invoice_assets.php?invoice_id=`. `billingItemDelete()` clears `asset_invoice_item_id` on the line's assets and `delete_invoice` clears both invoice links - the assets stay. + - `productSave()` and `productCopy()` take `asset_type`, `make`, `model` and `warranty_months`, with import aliases and export columns for them. The products list and export take `type=hardware`, and `invoices.php` takes `hardware=1`. `dashboardAttention()` adds Hardware not on assets for agents with Support access, `billingPdfRender()` reads the serials for the packing slip, and the asset page joins the invoice and the product. Seeds: columns 12 to 15 on `demoDataProducts()` and an eighth and ninth on `starterContentProducts()`. CSS: `.itflow-hw-*`. - The billing helpers (`billingTimeInvoice()`, `quoteConvert()`, `recurringInvoiceGenerate()` and the rest) take the agent's name as plain text. Their handlers now pass `stripslashes($session_name)`, so a name with an apostrophe no longer shows a backslash in history and the audit log. - Sidebar brand: `agent/css/sidebar_brand_fix.css` and `agent/js/sidebar_brand_fix.js` from 26.10 are replaced by CSS in `css/itflow_custom.css`. `includes/load_company_settings.php` now sets `$session_company_logo`. - `alertMessageHtml()` no longer double-encodes, and save messages built from `escapeSql()` values use `stripslashes()` at the flash. diff --git a/admin/database_updates/2.9.6.php b/admin/database_updates/2.9.6.php new file mode 100644 index 000000000..d265eeae1 --- /dev/null +++ b/admin/database_updates/2.9.6.php @@ -0,0 +1,27 @@ + $product[5], 'product_currency_code' => $session_company_currency ?? '', 'product_tax_id' => 0, - ] + ($frequency !== '' ? ['product_frequency' => $frequency] : []) + ($seat !== '' ? ['product_seat_source' => $seat] : [])); + ] + ($frequency !== '' ? ['product_frequency' => $frequency] : []) + ($seat !== '' ? ['product_seat_source' => $seat] : []) + + (!empty($product[7]) ? ['product_asset_type' => $product[7], 'product_warranty_months' => intval($product[8] ?? 0)] : [])); } return $added; @@ -1146,7 +1147,8 @@ function starterContentDocumentTemplates() { // ------------------------------ // starterContentProducts // name, type, code, price, income category, description, billed (a frequency, -// or frequency:contacts per user / frequency:assets per device, empty once). +// or frequency:contacts per user / frequency:assets per device, empty once), +// and for hardware the client asset it becomes and its warranty in months. // Hardware and resold SKUs come in at zero - they are quoted per deal or move // with the vendor price list. // ------------------------------ @@ -1224,25 +1226,25 @@ function starterContentProducts() { ['Equipment Disposal', 'service', 'PRJ-DISP', '25.00', 'Projects', 'Per device. Secure data destruction and certified recycling.', ''], // Hardware - quoted per deal, seeded at zero - ['Desktop', 'product', 'HW-DSK', '0.00', 'Hardware Sales', 'Business class desktop. Priced per quote.', ''], - ['Laptop', 'product', 'HW-LAP', '0.00', 'Hardware Sales', 'Business class laptop. Priced per quote.', ''], + ['Desktop', 'product', 'HW-DSK', '0.00', 'Hardware Sales', 'Business class desktop. Priced per quote.', '', 'Desktop', 36], + ['Laptop', 'product', 'HW-LAP', '0.00', 'Hardware Sales', 'Business class laptop. Priced per quote.', '', 'Laptop', 36], ['Docking Station', 'product', 'HW-DOCK', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Monitor', 'product', 'HW-MON', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Server', 'product', 'HW-SRV', '0.00', 'Hardware Sales', 'Rack or tower server. Priced per quote.', ''], - ['Network Attached Storage', 'product', 'HW-NAS', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Firewall Appliance', 'product', 'HW-FW', '0.00', 'Hardware Sales', 'Priced per quote, excludes subscription.', ''], - ['Switch - 24 Port', 'product', 'HW-SW24', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Switch - 48 Port', 'product', 'HW-SW48', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Wireless Access Point', 'product', 'HW-AP', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Uninterruptible Power Supply', 'product', 'HW-UPS', '0.00', 'Hardware Sales', 'Priced per quote.', ''], + ['Monitor', 'product', 'HW-MON', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Display', 36], + ['Server', 'product', 'HW-SRV', '0.00', 'Hardware Sales', 'Rack or tower server. Priced per quote.', '', 'Server', 36], + ['Network Attached Storage', 'product', 'HW-NAS', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Server', 36], + ['Firewall Appliance', 'product', 'HW-FW', '0.00', 'Hardware Sales', 'Priced per quote, excludes subscription.', '', 'Firewall/Router', 12], + ['Switch - 24 Port', 'product', 'HW-SW24', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Switch', 12], + ['Switch - 48 Port', 'product', 'HW-SW48', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Switch', 12], + ['Wireless Access Point', 'product', 'HW-AP', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Access Point', 12], + ['Uninterruptible Power Supply', 'product', 'HW-UPS', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Other', 24], ['Solid State Drive', 'product', 'HW-SSD', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Memory Upgrade', 'product', 'HW-RAM', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Keyboard and Mouse', 'product', 'HW-KBM', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Headset', 'product', 'HW-HS', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Webcam', 'product', 'HW-CAM', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['Printer', 'product', 'HW-PRT', '0.00', 'Hardware Sales', 'Priced per quote.', ''], + ['Printer', 'product', 'HW-PRT', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Printer', 12], ['Toner Cartridge', 'product', 'HW-TON', '0.00', 'Hardware Sales', 'Priced per quote.', ''], - ['VoIP Handset', 'product', 'HW-PHONE', '0.00', 'Hardware Sales', 'Priced per quote.', ''], + ['VoIP Handset', 'product', 'HW-PHONE', '0.00', 'Hardware Sales', 'Priced per quote.', '', 'Phone', 12], ['Patch Cable', 'product', 'HW-CBL', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Rack Cabinet', 'product', 'HW-RACK', '0.00', 'Hardware Sales', 'Priced per quote.', ''], ['Power Distribution Unit', 'product', 'HW-PDU', '0.00', 'Hardware Sales', 'Priced per quote.', ''], diff --git a/agent/asset.php b/agent/asset.php index 94331899d..e35225a14 100644 --- a/agent/asset.php +++ b/agent/asset.php @@ -37,13 +37,16 @@ $sql = mysqli_query($mysqli, "SELECT asset_archived_at, asset_client_id, asset_c contact_archived_at, contact_email, contact_extension, contact_mobile, contact_mobile_country_code, contact_name, contact_phone, contact_phone_country_code, contact_photo, interface_ip, interface_ipv6, interface_mac, interface_nat_ip, interface_network_id, - location_archived_at, location_name, network_name, network_type, network_description, vendor_name FROM assets + location_archived_at, location_name, network_name, network_type, network_description, vendor_name, + asset_product_id, asset_invoice_id, invoice_prefix, invoice_number, invoice_date, product_name FROM assets LEFT JOIN clients ON client_id = asset_client_id LEFT JOIN contacts ON asset_contact_id = contact_id LEFT JOIN locations ON asset_location_id = location_id LEFT JOIN vendors ON asset_vendor_id = vendor_id LEFT JOIN asset_interfaces ON interface_asset_id = asset_id AND interface_primary = 1 LEFT JOIN networks ON network_id = interface_network_id + LEFT JOIN invoices ON invoice_id = asset_invoice_id AND asset_invoice_id > 0 + LEFT JOIN products ON product_id = asset_product_id AND asset_product_id > 0 WHERE asset_id = $asset_id " . clientScopeSql('asset_client_id') . " $client_query @@ -85,6 +88,13 @@ if (mysqli_num_rows($sql) == 0) { $asset_vendor_id = intval($row['asset_vendor_id']); $asset_contact_id = intval($row['asset_contact_id']); $asset_tone = assetTypeTone($row['asset_type']); + // Sold to the client on one of our invoices, from a catalog product + $can_sales = lookupUserPermission('module_sales') >= 1; + $asset_invoice_id = intval($row['asset_invoice_id']); + $asset_sold_number = $row['invoice_number'] !== null ? escapeHtml($row['invoice_prefix'] . $row['invoice_number']) : ''; + $asset_sold_date = escapeHtml((string) $row['invoice_date']); + $asset_product_id = intval($row['asset_product_id']); + $asset_product_name = escapeHtml((string) $row['product_name']); $device_icon = getAssetIcon($row['asset_type']); $asset_ip = escapeHtml($row['interface_ip']); @@ -434,7 +444,17 @@ if (mysqli_num_rows($sql) == 0) {
Vendor
- + +
Sold on
+
+ $asset_sold_number" : $asset_sold_number ?> +
Our invoice,
+
+ + +
Product
$asset_product_name" : $asset_product_name ?>
+ +
Order ref
Added
diff --git a/agent/invoice.php b/agent/invoice.php index 41ff80952..0959153cc 100644 --- a/agent/invoice.php +++ b/agent/invoice.php @@ -8,6 +8,7 @@ * take a payment on one that is owed. The invoice itself is on the left, * as the client sees it, with its lines edited in place while it is open. * On the right: what has been paid and what is left, the payments, the + * hardware sold on it and whether it is on the client's assets yet, the * tickets billed on it and its history. */ @@ -59,6 +60,12 @@ $mail_ready = !empty($config_smtp_provider) && billingEmailableContacts('invoice $saved_card = $can_take_payment && in_array($status, ['Sent', 'Viewed'], true) && invoiceHasSavedCard($client_id); $unbilled_tickets = $can_edit && $can_edit_lines && $config_module_enable_ticketing ? count(billingUnbilledTickets($client_id)) : 0; $guest_url = billingGuestUrl('invoice', $invoice); +// Hardware sold on it, and how much of it is on the client's assets (functions/products.php) +$can_see_assets = lookupUserPermission('module_support') >= 1; +$hardware = $can_see_assets ? productInvoiceHardware($invoice_id) : []; +$hardware_units = array_sum(array_column($hardware, 'units')); +$hardware_to_add = $status === 'Cancelled' ? 0 : array_sum(array_column($hardware, 'to_add')); +$can_add_assets = $hardware_to_add > 0 && lookupUserPermission('module_support') >= 2; $csrf = $_SESSION['csrf_token']; // Made by a recurring invoice? @@ -331,6 +338,60 @@ $paper = [ + +
+
+

Hardware

+ + + +
+
+ +
+
+ +
+
+
· sold
+
+ = $line['units']) { ?> + On assets + + of + +
+ +
    + +
  • + + + + + + + Archived + (moved to another client) +
  • + +
+ +
+ +
+ + + + + +
+ +
diff --git a/agent/invoices.php b/agent/invoices.php index 80d2e69b4..6c3988b3f 100644 --- a/agent/invoices.php +++ b/agent/invoices.php @@ -47,6 +47,11 @@ $recurring_filter = intval($_GET['recurring_invoice_id'] ?? 0); $recurring_query = $recurring_filter ? "AND invoice_recurring_invoice_id = $recurring_filter" : ''; $recurring_filter_row = $recurring_filter ? billingRow('recurring', $recurring_filter) : null; +// Hardware sold on them that isn't on the client's assets yet (functions/products.php) +$hardware_filter = !empty($_GET['hardware']); +$hardware_query = $hardware_filter ? "AND " . productHardwareInvoiceSql() . " AND invoices.invoice_id IN (SELECT invoice_items.item_invoice_id FROM invoice_items + JOIN products ON products.product_id = invoice_items.item_product_id WHERE " . productHardwareShortSql() . ")" : ''; + // Category Filter $category_filter = intval($_GET['category'] ?? 0); $category_query = $category_filter ? "AND invoice_category_id = $category_filter" : ''; @@ -74,7 +79,7 @@ $paid_join = "LEFT JOIN (SELECT payment_invoice_id, SUM(payment_amount) AS paid $scope_query = clientScopeSql('invoice_client_id'); $search_query = "AND (CONCAT(invoice_prefix, invoice_number) LIKE '%$q%' OR invoice_scope LIKE '%$q%' OR client_name LIKE '%$q%' OR invoice_status LIKE '%$q%' OR invoice_amount LIKE '%$q%' OR category_name LIKE '%$q%')"; $date_query = "AND DATE(invoice_date) BETWEEN '$dtf' AND '$dtt'"; -$filters = "$scope_query $client_query $recurring_query $category_query $date_query $search_query"; +$filters = "$scope_query $client_query $recurring_query $hardware_query $category_query $date_query $search_query"; $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS invoices.*, client_name, category_name, category_color, recurring_invoice_prefix, recurring_invoice_number, @@ -214,6 +219,9 @@ $stat_money = function ($amount) use ($session_company_currency) { + + +
@@ -288,6 +296,12 @@ $stat_money = function ($amount) use ($session_company_currency) { Clear
+ +
+ Hardware sold on them isn't on the client's assets yet - open one and use Add to Assets + Clear +
+
@@ -426,7 +440,7 @@ $stat_money = function ($amount) use ($session_company_currency) {
-
+
diff --git a/agent/modals/invoice/invoice_assets.php b/agent/modals/invoice/invoice_assets.php new file mode 100644 index 000000000..2ff07b882 --- /dev/null +++ b/agent/modals/invoice/invoice_assets.php @@ -0,0 +1,284 @@ + 'That invoice no longer exists.'])); +} +$invoice_id = intval($invoice['invoice_id']); +$client_id = intval($invoice['client_id']); +enforceClientAccess(); +$number = billingNumber('invoice', $invoice); +$invoice_date = substr((string) $invoice['invoice_date'], 0, 10); + +if ($invoice['invoice_status'] === 'Cancelled') { + exit(json_encode(['error' => escapeHtml($number) . ' is cancelled - nothing on it was sold.'])); +} +$lines = array_values(array_filter(productInvoiceHardware($invoice_id), function ($line) { + return $line['to_add'] > 0; +})); +if (!$lines) { + exit(json_encode(['error' => 'Every unit of hardware on ' . escapeHtml($number) . ' is on ' . escapeHtml($invoice['client_name']) . "'s assets."])); +} + +$statuses = []; +$sql = mysqli_query($mysqli, "SELECT category_name, category_color FROM categories WHERE category_type = 'asset_status' AND category_archived_at IS NULL ORDER BY category_name ASC"); +while ($row = mysqli_fetch_assoc($sql)) { + $statuses[$row['category_name']] = assetStatusColor($row['category_name'], $row['category_color'] ?? ''); +} +$status_default = isset($statuses['Deployed']) ? 'Deployed' : (isset($statuses['Ready to Deploy']) ? 'Ready to Deploy' : (string) array_key_first($statuses)); + +$locations = []; +$location_default = 0; +$sql = mysqli_query($mysqli, "SELECT location_id, location_name, location_primary FROM locations WHERE location_client_id = $client_id AND location_archived_at IS NULL ORDER BY location_primary DESC, location_name ASC"); +while ($row = mysqli_fetch_assoc($sql)) { + $locations[intval($row['location_id'])] = $row['location_name']; + if (intval($row['location_primary']) && !$location_default) { + $location_default = intval($row['location_id']); + } +} +$contacts = []; +$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL ORDER BY contact_name ASC"); +while ($row = mysqli_fetch_assoc($sql)) { + $contacts[intval($row['contact_id'])] = $row['contact_name']; +} + +$form_id = "invoiceAssets$invoice_id"; +$total = array_sum(array_column($lines, 'to_add')); + +ob_start(); + +?> + + + + + + + + +
+ + + + value="recurring">Billed each month, quarter or year +
diff --git a/agent/modals/product/product_form.php b/agent/modals/product/product_form.php index 704f9e276..83a7b87db 100644 --- a/agent/modals/product/product_form.php +++ b/agent/modals/product/product_form.php @@ -8,8 +8,9 @@ * $form_type service | product - what a new one starts as * * Posts what productSave() reads: type, name, category, tax, price, cost, - * frequency, seat_source, code, vendor, vendor_part, track_stock, location, - * description and notes. + * frequency, seat_source, code, vendor, vendor_part, track_stock, + * reorder_level, reorder_qty, location, asset_type, make, model, + * warranty_months, description and notes. * * Should not be accessed directly. */ @@ -35,6 +36,8 @@ $form_reorder_qty = $form_edit && floatval($form_product['product_reorder_qty']) $form_price = $form_edit ? number_format(floatval($form_product['product_price']), 2, '.', '') : ''; $form_cost = $form_edit && floatval($form_product['product_cost']) > 0 ? number_format(floatval($form_product['product_cost']), 2, '.', '') : ''; $form_currency = $form_edit ? (string) $form_product['product_currency_code'] : (string) $session_company_currency; +$form_asset_type = $form_value('product_asset_type'); +$form_warranty = $form_edit && intval($form_product['product_warranty_months']) > 0 ? intval($form_product['product_warranty_months']) : ''; $form_categories = []; $sql = mysqli_query($mysqli, "SELECT category_id, category_name, category_color, category_icon FROM categories @@ -215,6 +218,49 @@ if ($form_vendor_id && !isset($form_vendors[$form_vendor_id]) && $form_value('ve
+ +
+ +
+ + +
+
+
+ +
+ + + months +
+
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+
When it is sold, the invoice offers to add each one to the client's assets with its serial number, this make and model, and the warranty counted from the invoice date.
+
Pick an asset type for hardware the client keeps - a laptop, a switch, a firewall - and selling it offers to add it to their assets.
+
+
@@ -246,6 +292,7 @@ if ($form_vendor_id && !isset($form_vendors[$form_vendor_id]) && $form_value('ve var frequency = form.querySelector('[data-product-frequency]'); var counted = form.querySelector('[data-product-counted]'); var track = form.querySelector('[data-product-track]'); + var assetType = form.querySelector('[data-product-asset-type]'); function number(value) { var text = String(value || '').replace(/[\s,$€£]/g, ''); @@ -269,6 +316,11 @@ if ($form_vendor_id && !isset($form_vendors[$form_vendor_id]) && $form_value('ve }); form.querySelector('[data-product-track-on]').hidden = !track.checked; form.querySelector('[data-product-track-off]').hidden = track.checked; + form.querySelectorAll('[data-product-asset]').forEach(function (el) { + el.hidden = assetType.value === ''; + }); + form.querySelector('[data-product-asset-on]').hidden = assetType.value === ''; + form.querySelector('[data-product-asset-off]').hidden = assetType.value !== ''; } counted.hidden = frequency.value === ''; diff --git a/agent/modals/product/product_import.php b/agent/modals/product/product_import.php index a2df5a648..a2916404e 100644 --- a/agent/modals/product/product_import.php +++ b/agent/modals/product/product_import.php @@ -21,7 +21,8 @@ ob_start();

A CSV with a heading row. Columns can be in any order, and only Name is needed:

Name, Type (Service or Product), Code, Category, Description, Price, Cost, Tax, Billed (One time, Monthly, Quarterly, Yearly), - Counted (Per user, Per device), Vendor, Part Number, Track Stock (Yes or No), Reorder At, Order, Location, Notes. + Counted (Per user, Per device), Vendor, Part Number, Track Stock (Yes or No), Reorder At, Order, Location, + Asset Type (Laptop, Switch, Access Point and so on), Make, Model, Warranty (in months), Notes. Categories, taxes and vendors are matched by name to the ones you have.

diff --git a/agent/post/invoice.php b/agent/post/invoice.php index 5a272603a..755b07015 100644 --- a/agent/post/invoice.php +++ b/agent/post/invoice.php @@ -305,6 +305,9 @@ if (isset($_GET['delete_invoice'])) { //unlink tickets from invoice mysqli_query($mysqli,"UPDATE tickets SET ticket_invoice_id = 0 WHERE ticket_invoice_id = $invoice_id"); + // Assets made from its hardware stay on the client's assets, unlinked + mysqli_query($mysqli, "UPDATE assets SET asset_invoice_id = 0, asset_invoice_item_id = 0 WHERE asset_invoice_id = $invoice_id"); + logAudit("Invoice", "Delete", "$session_name deleted invoice $invoice_prefix$invoice_number", $client_id); flashAlert("Invoice $invoice_prefix$invoice_number deleted", 'error'); @@ -895,6 +898,46 @@ if (isset($_GET['remove_ticket_from_invoice'])) { } +if (isset($_POST['invoice_assets_save'])) { + + validateCSRFToken(); + + enforceUserPermission('module_sales'); + enforceUserPermission('module_support', 2); + + $invoice = billingRow('invoice', intval($_POST['invoice_id'] ?? 0)); + if (!$invoice) { + flashAlert('That invoice no longer exists.', 'error'); + redirect('invoices.php'); + } + $invoice_id = intval($invoice['invoice_id']); + $client_id = intval($invoice['client_id']); + + enforceClientAccess(); + + // functions/products.php - checks every row before it adds or links any + $done = productSaleAssets($invoice_id, (array) ($_POST['lines'] ?? []), (array) ($_POST['units'] ?? []), [ + 'status' => (string) ($_POST['status'] ?? ''), + 'location' => intval($_POST['location'] ?? 0), + ], $error); + if ($done === null) { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } + + $parts = []; + if ($done['added']) { + $parts[] = "{$done['added']} added"; + } + if ($done['linked']) { + $parts[] = "{$done['linked']} linked"; + } + flashAlert(escapeHtml(billingNumber('invoice', $invoice)) . " hardware on " . escapeHtml($invoice['client_name']) . "'s assets - " . implode(', ', $parts)); + + redirect(); + +} + if (isset($_GET['export_invoice_pdf'])) { validateCSRFToken(); diff --git a/agent/post/product.php b/agent/post/product.php index 9e342227b..dbb26f856 100644 --- a/agent/post/product.php +++ b/agent/post/product.php @@ -12,7 +12,8 @@ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); /** The product fields from a posted form, raw. */ function productFormInput() { $in = []; - foreach (['name', 'type', 'category', 'price', 'cost', 'tax', 'frequency', 'seat_source', 'code', 'vendor', 'vendor_part', 'reorder_level', 'reorder_qty', 'location', 'description', 'notes'] as $key) { + foreach (['name', 'type', 'category', 'price', 'cost', 'tax', 'frequency', 'seat_source', 'code', 'vendor', 'vendor_part', 'reorder_level', 'reorder_qty', 'location', + 'asset_type', 'make', 'model', 'warranty_months', 'description', 'notes'] as $key) { if (array_key_exists($key, $_POST)) { $in[$key] = (string) $_POST[$key]; } @@ -317,6 +318,7 @@ if (isExportRequest('export_products')) { 'recurring' => ["AND product_frequency IS NOT NULL", 'Billed each month, quarter or year'], 'stocked' => ["AND product_track_stock = 1", 'Stock tracked'], 'reorder' => ["AND " . productReorderSql(), 'To reorder'], + 'hardware' => ["AND " . productHardwareSql(), 'Become client assets'], ]; $type_query = ''; if (isset($type_queries[$type_filter])) { @@ -383,6 +385,7 @@ if (isExportRequest('export_products')) { $row['product_reorder_display'] = intval($row['product_track_stock']) && floatval($row['product_reorder_level']) > 0 ? billingQuantity($row['product_reorder_level']) : ''; $row['product_order_display'] = intval($row['product_track_stock']) && floatval($row['product_reorder_qty']) > 0 ? billingQuantity($row['product_reorder_qty']) : ''; $row['product_stock_value'] = intval($row['product_track_stock']) && floatval($row['product_stock']) > 0 ? round(floatval($row['product_stock']) * floatval($row['product_cost']), 2) : ''; + $row['product_warranty_display'] = intval($row['product_warranty_months']) > 0 ? intval($row['product_warranty_months']) : ''; addExportRow($export, $row); } @@ -592,6 +595,10 @@ if (isset($_POST["import_products_csv"])) { 'reorder_level' => ['reorder at', 'reorder level', 'reorder point', 'minimum stock'], 'reorder_qty' => ['order', 'order qty', 'reorder qty', 'reorder quantity'], 'location' => ['location'], + 'asset_type' => ['asset type', 'asset', 'client asset'], + 'make' => ['make', 'manufacturer', 'brand'], + 'model' => ['model'], + 'warranty_months' => ['warranty', 'warranty months', 'warranty (months)'], 'notes' => ['notes', 'internal notes'], ]; $columns = []; @@ -708,9 +715,9 @@ if (isset($_POST["import_products_csv"])) { if (isset($_GET['download_products_csv_template'])) { $f = fopen('php://memory', 'w'); - fputcsv($f, ['Name', 'Type', 'Code', 'Category', 'Description', 'Price', 'Cost', 'Tax', 'Billed', 'Counted', 'Vendor', 'Part Number', 'Track Stock', 'Reorder At', 'Order', 'Location', 'Notes'], ',', '"', '\\'); - fputcsv($f, ['Managed Workstation', 'Service', 'MS-WKS', 'Managed Services', 'Per workstation, per month. Monitoring, patching and support.', '65.00', '18.00', '', 'Monthly', 'Per device', '', '', '', '', '', '', ''], ',', '"', '\\'); - fputcsv($f, ['24 Port PoE Switch', 'Product', 'HW-SW24', 'Hardware Sales', '24 port managed PoE switch.', '785.00', '520.00', '', 'One time', '', '', 'USW-PRO-24-POE', 'Yes', '2', '5', 'Shelf B2', 'Order from the distributor, 2 day lead time'], ',', '"', '\\'); + fputcsv($f, ['Name', 'Type', 'Code', 'Category', 'Description', 'Price', 'Cost', 'Tax', 'Billed', 'Counted', 'Vendor', 'Part Number', 'Track Stock', 'Reorder At', 'Order', 'Location', 'Asset Type', 'Make', 'Model', 'Warranty', 'Notes'], ',', '"', '\\'); + fputcsv($f, ['Managed Workstation', 'Service', 'MS-WKS', 'Managed Services', 'Per workstation, per month. Monitoring, patching and support.', '65.00', '18.00', '', 'Monthly', 'Per device', '', '', '', '', '', '', '', '', '', '', ''], ',', '"', '\\'); + fputcsv($f, ['24 Port PoE Switch', 'Product', 'HW-SW24', 'Hardware Sales', '24 port managed PoE switch.', '785.00', '520.00', '', 'One time', '', '', 'USW-PRO-24-POE', 'Yes', '2', '5', 'Shelf B2', 'Switch', 'Ubiquiti', 'USW-Pro-24-PoE', '12', 'Order from the distributor, 2 day lead time'], ',', '"', '\\'); fseek($f, 0); header('Content-Type: text/csv'); diff --git a/agent/product.php b/agent/product.php index d2ad7ad86..05e7ebf89 100644 --- a/agent/product.php +++ b/agent/product.php @@ -6,11 +6,13 @@ * What it sells for and costs us, so its margin; how it is billed by default; * who we buy it from and their part number; for a product, its stock - on the * shelf, where, what that is worth and when to reorder - or that it is - * ordered as needed. Internal notes save as you click away. + * ordered as needed, and for hardware the client asset it becomes. Internal + * notes save as you click away. * * Then in tabs with counts: its stock moves with what was on the shelf after * each, the recurring invoices it is on (what that brings in a month), open - * quotes, the invoices it was sold on, and its history. Figures are for the clients the agent can see. + * quotes, the invoices it was sold on, the client assets made from it, and + * its history. Figures are for the clients the agent can see. */ require_once "includes/inc_all.php"; @@ -46,6 +48,13 @@ if (!$product) { $can_delete = lookupUserPermission('module_sales') >= 3 && !empty($config_destructive_deletes_enable); $csrf = $_SESSION['csrf_token']; + // Hardware - the client asset it becomes when sold, and the ones it became + $asset_type = $type === 'product' ? (string) $product['product_asset_type'] : ''; + $warranty_months = intval($product['product_warranty_months']); + $can_see_assets = lookupUserPermission('module_support') >= 1; + $assets = $can_see_assets ? productAssets($product_id, 200) : []; + $asset_clients = count(array_unique(array_column($assets, 'client_id'))); + $usage = productUsage($product_id); $moves = $type === 'product' ? productStockMoves($product_id, 200) : []; $history = productHistory($product_id, 100); @@ -61,6 +70,17 @@ if (!$product) { if (!$product['product_frequency']) { $tabs = ['invoices' => $tabs['invoices'], 'quotes' => $tabs['quotes'], 'recurring' => $tabs['recurring'], 'history' => $tabs['history']]; } + // The client assets made from it, after the invoices it was sold on + if ($can_see_assets && ($asset_type !== '' || $assets)) { + $with_assets = []; + foreach ($tabs as $tab_key => $tab) { + $with_assets[$tab_key] = $tab; + if ($tab_key === 'invoices') { + $with_assets['assets'] = ['label' => 'Assets', 'icon' => 'fa-laptop', 'count' => count($assets)]; + } + } + $tabs = $with_assets; + } // Its stock moves - first for a product that tracks stock if ($tracked || $moves) { $stock_tab = ['stock' => ['label' => 'Stock', 'icon' => 'fa-warehouse', 'count' => count($moves)]]; @@ -291,6 +311,33 @@ if (!$product) {
+ +
+
+

Client asset

+
+ +
+
+
Becomes
+
Make
Not set' ?>
+
Model
Not set' ?>
+
Warranty
from the invoice date' : 'Not set' ?>
+ +
In use
+
assetat $asset_clients client" . ($asset_clients === 1 ? '' : 's') . '' : '' ?>
+ +
+
+ +
+ Sold as goods - it doesn't go on the client's assets. + Pick an asset type in Edit for hardware the client keeps, and selling it offers to add it to their assets. +
+ +
+ +

On invoices and quotes

@@ -422,6 +469,60 @@ if (!$product) {
+ + +
+ +
+ + + + + + + + + + + + + + + +
AssetClientSerialWarrantySold on
+
+ +
+ + Archived +
+
+
+
-' ?> + + + + Not recorded + + + + +
+ + + +
+
+ = 200) { ?> +
The latest 200.
+ + +
Not on any client's assets yet. When it is sold, the invoice offers to add it.
+ +
+ +
diff --git a/agent/products.php b/agent/products.php index f61ac08e5..d4d1402dd 100644 --- a/agent/products.php +++ b/agent/products.php @@ -29,6 +29,7 @@ $views = [ 'all' => ['label' => 'All', 'icon' => 'fa-th-list', 'sql' => ''], 'service' => ['label' => 'Services', 'icon' => 'fa-wrench', 'sql' => "AND product_type = 'service'"], 'product' => ['label' => 'Products', 'icon' => 'fa-box-open', 'sql' => "AND product_type = 'product'"], + 'hardware' => ['label' => 'Hardware', 'icon' => 'fa-laptop', 'sql' => "AND " . productHardwareSql(), 'title' => 'Becomes a client asset when it is sold'], 'recurring' => ['label' => 'Recurring', 'icon' => 'fa-redo-alt', 'sql' => "AND product_frequency IS NOT NULL", 'title' => 'Billed each month, quarter or year by default'], 'stocked' => ['label' => 'Stocked', 'icon' => 'fa-warehouse', 'sql' => "AND product_track_stock = 1", 'title' => 'Stock tracked'], 'reorder' => ['label' => 'Reorder', 'icon' => 'fa-shopping-basket', 'sql' => "AND " . productReorderSql(), 'title' => 'Stock at or under its reorder level, or out'], @@ -79,7 +80,7 @@ while ($row = mysqli_fetch_assoc($sql)) { $counts = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(*) AS `all`, COALESCE(SUM(product_type = 'service'), 0) AS service, COALESCE(SUM(product_type = 'product'), 0) AS product, COALESCE(SUM(product_frequency IS NOT NULL), 0) AS recurring, COALESCE(SUM(product_track_stock = 1), 0) AS stocked, - COALESCE(SUM(" . productReorderSql() . "), 0) AS reorder + COALESCE(SUM(" . productReorderSql() . "), 0) AS reorder, COALESCE(SUM(" . productHardwareSql() . "), 0) AS hardware $from $where")); // The catalog at work - recurring, sold, on the shelf @@ -117,7 +118,7 @@ $filter_url = function ($changes) { $money = function ($amount, $currency = null) use ($session_company_currency) { return escapeHtml(billingMoney($amount, $currency ?: $session_company_currency)); }; -$add_type = in_array($view, ['product', 'stocked', 'reorder'], true) ? 'product' : 'service'; +$add_type = in_array($view, ['product', 'hardware', 'stocked', 'reorder'], true) ? 'product' : 'service'; ?> @@ -331,7 +332,8 @@ $add_type = in_array($view, ['product', 'stocked', 'reorder'], true) ? 'product' $row_margin = productMargin($row['product_price'], $row['product_cost']); $row_currency = (string) $row['product_currency_code']; $row_url = "product.php?product_id=$product_id"; - $row_meta = array_filter([$row['product_code'] ? '' . escapeHtml($row['product_code']) . '' : '', escapeHtml((string) $row['category_name'])]); + $row_meta = array_filter([$row['product_code'] ? '' . escapeHtml($row['product_code']) . '' : '', escapeHtml((string) $row['category_name']), + $row_type === 'product' && $row['product_asset_type'] ? '' . escapeHtml($row['product_asset_type']) . '' : '']); ?> diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 6e2479040..995b07c9b 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -6178,6 +6178,23 @@ a.itflow-report-stat:focus-visible { background-color: var(--bs-primary-bg-subtle); border-color: var(--bs-primary-border-subtle); } + +/* Sold hardware - Add to Assets, a block per invoice line with a row per unit */ +.itflow-hw-line { + padding: .75rem; + border: 1px solid var(--bs-border-color-translucent); + border-radius: var(--bs-border-radius-lg); + background-color: var(--bs-tertiary-bg); +} +.itflow-hw-unit + .itflow-hw-unit { + margin-top: .375rem; +} +.itflow-hw-linking .input-group:has([data-hw-new]) { + opacity: .45; +} +.itflow-hw-assets { + padding-left: 2.25rem; +} .itflow-money { font-variant-numeric: tabular-nums; white-space: nowrap; diff --git a/db.sql b/db.sql index ce2ac373c..1b041390b 100644 --- a/db.sql +++ b/db.sql @@ -331,8 +331,13 @@ CREATE TABLE `assets` ( `asset_location_id` int(11) NOT NULL DEFAULT 0, `asset_contact_id` int(11) NOT NULL DEFAULT 0, `asset_client_id` int(11) NOT NULL DEFAULT 0, + `asset_product_id` int(11) NOT NULL DEFAULT 0, + `asset_invoice_id` int(11) NOT NULL DEFAULT 0, + `asset_invoice_item_id` int(11) NOT NULL DEFAULT 0, PRIMARY KEY (`asset_id`), - KEY `asset_client_id` (`asset_client_id`,`asset_archived_at`) + KEY `asset_client_id` (`asset_client_id`,`asset_archived_at`), + KEY `asset_product_id` (`asset_product_id`), + KEY `asset_invoice_id` (`asset_invoice_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -1800,6 +1805,10 @@ CREATE TABLE `products` ( `product_track_stock` tinyint(1) NOT NULL DEFAULT 0, `product_reorder_level` decimal(15,2) NOT NULL DEFAULT 0.00, `product_reorder_qty` decimal(15,2) NOT NULL DEFAULT 0.00, + `product_asset_type` varchar(200) DEFAULT NULL, + `product_make` varchar(200) DEFAULT NULL, + `product_model` varchar(200) DEFAULT NULL, + `product_warranty_months` int(11) NOT NULL DEFAULT 0, `product_created_at` datetime NOT NULL DEFAULT current_timestamp(), `product_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), `product_archived_at` datetime DEFAULT NULL, diff --git a/functions/billing.php b/functions/billing.php index e28687713..80fc6408a 100644 --- a/functions/billing.php +++ b/functions/billing.php @@ -332,6 +332,10 @@ function billingItemDelete($type, $doc_id, $item_id) { 'invoice_id' => $doc_id, 'item_id' => $item_id, 'note' => billingNumber('invoice', billingRow('invoice', $doc_id, false)) . ' - line taken off', ]); } + // Assets made from the line stay, still bought on the invoice + if ($type === 'invoice') { + mysqli_query($mysqli, "UPDATE assets SET asset_invoice_item_id = 0 WHERE asset_invoice_id = $doc_id AND asset_invoice_item_id = $item_id"); + } billingRecalc($type, $doc_id); return $item; } diff --git a/functions/billing_pdf.php b/functions/billing_pdf.php index f4607314f..eed62228b 100644 --- a/functions/billing_pdf.php +++ b/functions/billing_pdf.php @@ -43,7 +43,7 @@ class BillingPdf extends TCPDF { * ($variant 'packing') - and return ['name' => file name, 'data' => the PDF]. */ function billingPdfRender($type, array $row, $variant = 'document') { - global $config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id; + global $mysqli, $config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id; $t = billingType($type); $c = $t['col']; @@ -207,11 +207,20 @@ function billingPdfRender($type, array $row, $variant = 'document') { $th = 'font-size:6.5pt; color:' . $grey . '; font-weight:bold; border-bottom:0.6px solid #adb5bd;'; $td = 'border-bottom:0.3px solid ' . $line . ';'; if ($packing) { + // The serials of hardware already on the client's assets, under its line + $serials = []; + $sql = mysqli_query($mysqli, "SELECT asset_invoice_item_id, asset_serial FROM assets + WHERE asset_invoice_id = $id AND asset_invoice_item_id > 0 AND COALESCE(asset_serial, '') <> '' ORDER BY asset_name ASC, asset_id ASC"); + while ($serial = mysqli_fetch_assoc($sql)) { + $serials[intval($serial['asset_invoice_item_id'])][] = $serial['asset_serial']; + } $html = ''; foreach ($items as $item) { + $item_serials = $serials[intval($item['item_id'])] ?? []; $html .= ' + . (trim((string) $item['item_description']) !== '' ? '
' . nl2br($e($item['item_description'])) . '' : '') + . ($item_serials ? '
' . (count($item_serials) === 1 ? 'Serial' : 'Serials') . ': ' . $e(implode(', ', $item_serials)) . '' : '') . ''; } diff --git a/functions/dashboard.php b/functions/dashboard.php index cead0d431..64767ba0a 100644 --- a/functions/dashboard.php +++ b/functions/dashboard.php @@ -269,6 +269,16 @@ function dashboardAttention($access) { 'label' => 'Stock to reorder', 'icon' => 'shopping-basket', 'tone' => 'warning', 'detail' => 'At or under the reorder level', 'url' => '/agent/products.php?type=reorder', ]; + // Hardware sold in the last 90 days that isn't on the client's assets yet + if ($access['support']) { + $hardware = productHardwarePending(90); + $items[] = [ + 'count' => $hardware['units'], + 'label' => 'Hardware not on assets', 'icon' => 'laptop', 'tone' => 'info', + 'detail' => $hardware['units'] ? 'Sold on ' . $hardware['invoices'] . ' invoice' . ($hardware['invoices'] === 1 ? '' : 's') . ' in 90 days' : null, + 'url' => '/agent/invoices.php?hardware=1&dtf=' . date('Y-m-d', strtotime('-90 days')) . '&dtt=' . date('Y-m-d'), + ]; + } if ($access['tickets']) { $items[] = [ 'count' => dashboardCount("SELECT COUNT(ticket_id) FROM tickets WHERE " . billingUnbilledSql() . " $ticket_scope"), diff --git a/functions/export.php b/functions/export.php index c052f3f93..82798a229 100644 --- a/functions/export.php +++ b/functions/export.php @@ -369,6 +369,10 @@ function getExportColumns($export_type) { 'product_reorder_display' => ['label' => 'Reorder At', 'default' => false], 'product_order_display' => ['label' => 'Order', 'default' => false], 'product_location' => ['label' => 'Location', 'default' => false], + 'product_asset_type' => ['label' => 'Asset Type', 'default' => false], + 'product_make' => ['label' => 'Make', 'default' => false], + 'product_model' => ['label' => 'Model', 'default' => false], + 'product_warranty_display' => ['label' => 'Warranty', 'default' => false], 'product_notes' => ['label' => 'Notes', 'weight' => 3, 'default' => false], ], diff --git a/functions/products.php b/functions/products.php index cd3f85646..d23456b52 100644 --- a/functions/products.php +++ b/functions/products.php @@ -10,7 +10,8 @@ * device. Picking it on a quote fills in Billed, on a recurring invoice * Counted. A product can track its stock: tracked ones move stock as they * are invoiced and can't be sold past what is on the shelf, the rest are - * ordered as needed. + * ordered as needed. Hardware can become a client asset when it is sold - + * the invoice offers to add each unit to the client's assets. */ /** Product types => label, plural and icon. */ @@ -109,7 +110,8 @@ function productVendors() { * seat_source ('' as typed, contacts, assets - only when billed recurring), * code, vendor (one of our vendors), vendor_part, track_stock (products * only), reorder_level and reorder_qty (when to buy more, how many), - * location, description, notes. + * asset_type (products only - one of the asset types, '' for none), make, + * model, warranty_months, location, description, notes. * Returns the product id, or 0 with $error. */ function productSave(array $in, $product_id = 0, &$error = '') { @@ -224,7 +226,36 @@ function productSave(array $in, $product_id = 0, &$error = '') { $set[] = "$column = " . round(floatval($raw), 2); } - foreach (['code' => ['product_code', 200], 'vendor_part' => ['product_vendor_part', 200], 'location' => ['product_location', 250]] as $key => [$column, $length]) { + // Hardware that becomes a client asset when sold - products only + if ($has('asset_type') || $has('type')) { + $asset_type = $has('asset_type') ? trim((string) ($in['asset_type'] ?? '')) : (string) ($old['product_asset_type'] ?? ''); + if (in_array(strtolower($asset_type), ['', 'none', 'no', '-'], true)) { + $asset_type = ''; + } else { + $asset_type = productAssetType($asset_type); + if ($asset_type === '') { + $error = "\"" . trim((string) ($in['asset_type'] ?? '')) . "\" isn't an asset type - use one of " . implode(', ', array_keys(productAssetTypes())) . '.'; + return 0; + } + } + if ($type !== 'product') { + $asset_type = ''; + } + $set[] = 'product_asset_type = ' . ($asset_type === '' ? 'NULL' : "'" . escapeSql($asset_type) . "'"); + } + if ($has('warranty_months')) { + $raw = trim((string) ($in['warranty_months'] ?? '')); + if ($raw === '') { + $raw = '0'; + } + if (!ctype_digit($raw) || intval($raw) > 600) { + $error = 'Warranty is a number of months, up to 600.'; + return 0; + } + $set[] = 'product_warranty_months = ' . intval($raw); + } + + foreach (['code' => ['product_code', 200], 'vendor_part' => ['product_vendor_part', 200], 'location' => ['product_location', 250], 'make' => ['product_make', 200], 'model' => ['product_model', 200]] as $key => [$column, $length]) { if ($has($key)) { $value = trim((string) ($in[$key] ?? '')); $set[] = "$column = " . ($value === '' ? 'NULL' : "'" . escapeSql(mb_substr($value, 0, $length)) . "'"); @@ -263,6 +294,7 @@ function productCopy($product_id) { 'frequency' => $product['product_frequency'], 'seat_source' => $product['product_seat_source'], 'code' => '', 'vendor' => $product['product_vendor_id'], 'vendor_part' => $product['product_vendor_part'], 'track_stock' => $product['product_track_stock'], 'reorder_level' => $product['product_reorder_level'], 'reorder_qty' => $product['product_reorder_qty'], + 'asset_type' => $product['product_asset_type'], 'make' => $product['product_make'], 'model' => $product['product_model'], 'warranty_months' => $product['product_warranty_months'], 'location' => $product['product_location'], 'description' => $product['product_description'], 'notes' => $product['product_notes'], ], 0, $error); } @@ -535,6 +567,306 @@ function productStockQty($qty) { return ($qty > 0 ? '+' : '') . billingQuantity($qty); } +/* + * Sold hardware becomes client assets. A product with an asset type is + * hardware: when it is sold on an invoice, each unit can go on the client's + * assets - as a new asset, or one already on file linked to the sale - with + * its serial and who has it, the make and model, bought on the invoice date + * and under warranty for the product's months from it. The asset keeps the + * product, the invoice and the line, so each line knows how many of its + * units are recorded. + */ + +/** Asset types => icon class (fa-laptop) - the list in load_global_settings.php. */ +function productAssetTypes() { + global $asset_types_array; + return is_array($asset_types_array ?? null) ? $asset_types_array : []; +} + +/** An asset type as the list spells it, matched without case - '' when it isn't one. */ +function productAssetType($value) { + $value = trim((string) $value); + foreach (array_keys(productAssetTypes()) as $asset_type) { + if (strcasecmp($asset_type, $value) === 0) { + return $asset_type; + } + } + return ''; +} + +/** An asset type's round icon, as on the assets list - $size '' or sm. */ +function productAssetIcon($asset_type, $size = '') { + return ''; +} + +/** Hardware, in SQL - with products in the FROM. */ +function productHardwareSql() { + return "products.product_type = 'product' AND products.product_asset_type IS NOT NULL AND products.product_asset_type <> ''"; +} + +/** How many units a line stands for - its quantity rounded up, none for a credit. */ +function productHardwareUnits($qty) { + $qty = round(floatval($qty), 2); + return $qty > 0 ? (int) ceil($qty) : 0; +} + +/** When a warranty of $months from $date (Y-m-d) runs out - the 31st becomes the month's last day. Null for none. */ +function productWarrantyUntil($date, $months) { + $months = intval($months); + if ($months <= 0 || !preg_match('/^(\d{4})-(\d{2})-(\d{2})/', (string) $date, $m)) { + return null; + } + $month = intval($m[2]) - 1 + $months; + $year = intval($m[1]) + intdiv($month, 12); + $month = $month % 12 + 1; + $day = min(intval($m[3]), intval(date('t', mktime(0, 0, 0, $month, 1, $year)))); + return sprintf('%04d-%02d-%02d', $year, $month, $day); +} + +/** + * The invoices whose hardware counts as sold and waiting to be recorded, in + * SQL with invoices in the FROM: not drafts or cancelled, and not made by a + * recurring invoice (hardware billed each month is rented, not sold). + */ +function productHardwareInvoiceSql() { + return "invoices.invoice_status NOT IN ('Draft', 'Cancelled') AND invoices.invoice_recurring_invoice_id = 0"; +} + +/** Lines with units still to add to assets - a condition on invoice_items joined to products. */ +function productHardwareShortSql() { + return productHardwareSql() . " AND invoice_items.item_quantity > 0 + AND CEIL(ROUND(invoice_items.item_quantity, 2)) > (SELECT COUNT(*) FROM assets + WHERE assets.asset_invoice_id = invoice_items.item_invoice_id AND assets.asset_invoice_item_id = invoice_items.item_id)"; +} + +/** + * Hardware sold in the last $days days, up to today, that isn't on the + * client's assets yet: ['units', 'invoices']. Scoped to the agent's clients. + */ +function productHardwarePending($days = 90) { + global $mysqli; + $days = max(1, intval($days)); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COALESCE(SUM(units - made), 0) AS units, COUNT(DISTINCT invoice_id) AS invoices FROM ( + SELECT invoice_id, CEIL(ROUND(item_quantity, 2)) AS units, + (SELECT COUNT(*) FROM assets WHERE asset_invoice_id = invoice_id AND asset_invoice_item_id = item_id) AS made + FROM invoice_items + JOIN invoices ON invoice_id = item_invoice_id + JOIN products ON product_id = item_product_id + WHERE " . productHardwareSql() . " AND item_quantity > 0 AND " . productHardwareInvoiceSql() . " + AND invoice_date BETWEEN CURDATE() - INTERVAL $days DAY AND CURDATE() " . clientScopeSql('invoice_client_id') . " + ) AS hardware WHERE units > made")); + return ['units' => intval($row['units'] ?? 0), 'invoices' => intval($row['invoices'] ?? 0)]; +} + +/** + * An invoice's hardware lines and the assets made from each - for its + * Hardware card and the Add to Assets window. Each line: item_id, item_name, + * item_description, item_quantity, units, product_id, product_name, + * product_asset_type, product_make, product_model, product_warranty_months, + * assets (asset_id, asset_name, asset_serial, asset_type, asset_status, + * asset_client_id, asset_archived_at) and to_add. + */ +function productInvoiceHardware($invoice_id) { + global $mysqli; + $invoice_id = intval($invoice_id); + $lines = []; + $sql = mysqli_query($mysqli, "SELECT item_id, item_name, item_description, item_quantity, product_id, product_name, + product_asset_type, product_make, product_model, product_warranty_months + FROM invoice_items + JOIN products ON product_id = item_product_id + WHERE item_invoice_id = $invoice_id AND " . productHardwareSql() . " + ORDER BY item_order ASC, item_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $row['units'] = productHardwareUnits($row['item_quantity']); + $row['assets'] = []; + $lines[intval($row['item_id'])] = $row; + } + if ($lines) { + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_serial, asset_type, asset_status, asset_client_id, asset_archived_at, asset_invoice_item_id + FROM assets + WHERE asset_invoice_id = $invoice_id AND asset_invoice_item_id IN (" . implode(', ', array_keys($lines)) . ") + ORDER BY asset_name ASC, asset_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $lines[intval($row['asset_invoice_item_id'])]['assets'][] = $row; + } + } + foreach ($lines as &$line) { + $line['to_add'] = max(0, $line['units'] - count($line['assets'])); + } + unset($line); + return array_values($lines); +} + +/** Assets made from a product, newest first - its installed base. Scoped to the agent's clients. */ +function productAssets($product_id, $limit = 200) { + global $mysqli; + $product_id = intval($product_id); + $limit = max(1, intval($limit)); + $assets = []; + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_serial, asset_type, asset_status, asset_warranty_expire, asset_purchase_date, asset_archived_at, + client_id, client_name, invoice_id, invoice_prefix, invoice_number, invoice_date + FROM assets + JOIN clients ON client_id = asset_client_id + LEFT JOIN invoices ON invoice_id = asset_invoice_id AND asset_invoice_id > 0 + WHERE asset_product_id = $product_id " . clientScopeSql('asset_client_id') . " + ORDER BY asset_archived_at IS NOT NULL, asset_purchase_date DESC, asset_id DESC + LIMIT $limit"); + while ($row = mysqli_fetch_assoc($sql)) { + $assets[] = $row; + } + return $assets; +} + +/** The client's assets that could be the hardware sold - not archived, not from a sale already. Same type first. */ +function productAssetCandidates($client_id, $asset_type = '') { + global $mysqli; + $client_id = intval($client_id); + $asset_type = escapeSql($asset_type); + $assets = []; + $sql = mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_type, asset_serial, asset_make, asset_model + FROM assets + WHERE asset_client_id = $client_id AND asset_archived_at IS NULL AND asset_invoice_item_id = 0 + ORDER BY asset_type = '$asset_type' DESC, asset_type ASC, asset_name ASC + LIMIT 300"); + while ($row = mysqli_fetch_assoc($sql)) { + $assets[] = $row; + } + return $assets; +} + +/** + * Put an invoice's hardware on the client's assets. Raw input: + * $lines item_id => ['make', 'model', 'warranty' (Y-m-d, '' for none)] + * $units item_id => list of ['name', 'serial', 'contact', 'existing'] + * - existing is one of the client's assets to link instead of adding one + * $shared ['status', 'location'] for every one added + * Only hardware lines still short are used, and no more units than each is + * short. Returns ['added' => n, 'linked' => n], or null with $error. + */ +function productSaleAssets($invoice_id, array $lines, array $units, array $shared, &$error = '') { + global $mysqli, $session_name; + $error = ''; + $invoice = billingRow('invoice', $invoice_id); + if (!$invoice) { + $error = 'That invoice no longer exists.'; + return null; + } + $invoice_id = intval($invoice['invoice_id']); + $client_id = intval($invoice['client_id']); + $number = billingNumber('invoice', $invoice); + if ($invoice['invoice_status'] === 'Cancelled') { + $error = "$number is cancelled - nothing on it was sold."; + return null; + } + $date = substr((string) $invoice['invoice_date'], 0, 10); + + $status = trim((string) ($shared['status'] ?? '')); + if ($status !== '' && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM categories WHERE category_type = 'asset_status' AND category_name = '" . escapeSql($status) . "'"))) { + $status = ''; + } + $location_id = assetClientOwnedId('location', $shared['location'] ?? 0, $client_id); + + // Check it all before anything is written + $plan = []; + $picked = []; + foreach (productInvoiceHardware($invoice_id) as $line) { + $item_id = intval($line['item_id']); + $rows = array_values(array_filter((array) ($units[$item_id] ?? []), 'is_array')); + if (!$rows || !$line['to_add']) { + continue; + } + $rows = array_slice($rows, 0, $line['to_add']); + $line_in = (array) ($lines[$item_id] ?? []); + $make = trim((string) ($line_in['make'] ?? $line['product_make'])); + $model = trim((string) ($line_in['model'] ?? $line['product_model'])); + $warranty = trim((string) ($line_in['warranty'] ?? '')); + if ($warranty !== '' && (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $warranty) || !strtotime($warranty))) { + $error = "The warranty date for {$line['item_name']} isn't a date."; + return null; + } + foreach ($rows as $n => $row) { + $existing = intval($row['existing'] ?? 0); + if ($existing) { + $asset = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT asset_id, asset_name, asset_invoice_item_id FROM assets WHERE asset_id = $existing AND asset_client_id = $client_id")); + if (!$asset || intval($asset['asset_invoice_item_id']) || isset($picked[$existing])) { + $error = isset($picked[$existing]) ? "{$asset['asset_name']} is picked twice." : "An asset picked for {$line['item_name']} isn't one of {$invoice['client_name']}'s, or came from another sale."; + return null; + } + $picked[$existing] = true; + $plan[] = ['line' => $line, 'existing' => $existing, 'name' => $asset['asset_name'], 'make' => $make, 'model' => $model, 'warranty' => $warranty]; + continue; + } + $name = trim((string) ($row['name'] ?? '')); + if ($name === '') { + $error = "Each new asset needs a name - " . ($n + 1) . " of {$line['item_name']} has none."; + return null; + } + $plan[] = ['line' => $line, 'existing' => 0, 'name' => mb_substr($name, 0, 200), 'serial' => mb_substr(trim((string) ($row['serial'] ?? '')), 0, 200), + 'contact' => assetClientOwnedId('contact', $row['contact'] ?? 0, $client_id), 'make' => $make, 'model' => $model, 'warranty' => $warranty]; + } + } + if (!$plan) { + $error = "Nothing to add - every unit of hardware on $number is on {$invoice['client_name']}'s assets."; + return null; + } + + $by = stripslashes((string) $session_name); + $ref = escapeSql(mb_substr($number, 0, 200)); + $number_sql = escapeSql($number); + $done = ['added' => 0, 'linked' => 0]; + mysqli_begin_transaction($mysqli); + try { + foreach ($plan as $unit) { + $line = $unit['line']; + $item_id = intval($line['item_id']); + $product_id = intval($line['product_id']); + $name = escapeSql($unit['name']); + $make = escapeSql(mb_substr($unit['make'], 0, 200)); + $model = $unit['model'] === '' ? 'NULL' : "'" . escapeSql(mb_substr($unit['model'], 0, 200)) . "'"; + $warranty = $unit['warranty'] === '' ? 'NULL' : "'" . escapeSql($unit['warranty']) . "'"; + $status_sql = escapeSql($status); + + if ($unit['existing']) { + $asset_id = $unit['existing']; + mysqli_query($mysqli, "UPDATE assets SET asset_product_id = $product_id, asset_invoice_id = $invoice_id, asset_invoice_item_id = $item_id, + asset_purchase_date = COALESCE(asset_purchase_date, '$date'), + asset_warranty_expire = COALESCE(asset_warranty_expire, $warranty), + asset_purchase_reference = IF(COALESCE(asset_purchase_reference, '') = '', '$ref', asset_purchase_reference), + asset_make = IF(asset_make = '', '$make', asset_make), + asset_model = IF(COALESCE(asset_model, '') = '', $model, asset_model) + WHERE asset_id = $asset_id"); + $history = escapeSql(mb_substr("$by linked {$unit['name']} to $number, where it was sold", 0, 255)); + mysqli_query($mysqli, "INSERT INTO asset_history SET asset_history_status = COALESCE((SELECT asset_status FROM assets WHERE asset_id = $asset_id), ''), asset_history_description = '$history', asset_history_asset_id = $asset_id"); + logAudit("Asset", "Edit", "$session_name linked asset $name to invoice $number_sql", $client_id, $asset_id); + $done['linked']++; + continue; + } + + $type = escapeSql($line['product_asset_type']); + $serial = $unit['serial'] === '' ? 'NULL' : "'" . escapeSql($unit['serial']) . "'"; + $description = trim((string) $line['item_description']); + $description = $description === '' ? 'NULL' : "'" . escapeSql(mb_substr($description, 0, 255)) . "'"; + $contact_id = intval($unit['contact']); + mysqli_query($mysqli, "INSERT INTO assets SET asset_type = '$type', asset_name = '$name', asset_description = $description, asset_make = '$make', asset_model = $model, + asset_serial = $serial, asset_status = '$status_sql', asset_purchase_reference = '$ref', asset_purchase_date = '$date', asset_warranty_expire = $warranty, + asset_location_id = $location_id, asset_contact_id = $contact_id, asset_client_id = $client_id, + asset_product_id = $product_id, asset_invoice_id = $invoice_id, asset_invoice_item_id = $item_id"); + $asset_id = intval(mysqli_insert_id($mysqli)); + mysqli_query($mysqli, "INSERT INTO asset_interfaces SET interface_name = '01', interface_primary = 1, interface_asset_id = $asset_id"); + $history = escapeSql(mb_substr("$by created {$unit['name']} from $number", 0, 255)); + mysqli_query($mysqli, "INSERT INTO asset_history SET asset_history_status = '$status_sql', asset_history_description = '$history', asset_history_asset_id = $asset_id"); + logAudit("Asset", "Create", "$session_name created asset $name from invoice $number_sql", $client_id, $asset_id); + $done['added']++; + } + mysqli_commit($mysqli); + } catch (Throwable $e) { + mysqli_rollback($mysqli); + throw $e; + } + return $done; +} + /** * 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
ITEMQTYPACKED
' . $e($item['item_name']) . '' - . (trim((string) $item['item_description']) !== '' ? '
' . nl2br($e($item['item_description'])) . '' : '') . '
' . $e(billingQuantity($item['item_quantity'])) . ' ☐