From 70af6a0f0e50c11644b47178a3f17f7ef5fd369e Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 18 Nov 2026 00:45:43 -0500 Subject: [PATCH] Purchasing: new To Order, Purchase Orders and Receiving pages under a Purchasing side menu section, with invoicing on and the new Purchasing role permission (module_procurement, Read, Modify, Full); items go on To Order by hand, from a product's Order button or from low-stock products, purchase orders are made from ticked items with their own prefix and next number, edited as drafts, downloaded as a PDF or emailed to the vendor and marked ordered, with optional approval over an amount that notifies the approvers by notice and email, carrier tracking links, receiving into stock or into client assets with serials, undoing a receipt, and recording the vendor bill as an expense linked to the received stock; agents only see purchase orders for clients they can reach, the Full access refusal says what Full allows for Purchasing, new functions/purchase_orders.php and a Purchase orders settings page, database 3.9.3 adds order_items, purchase_orders, po_items, po_receipts and po_tracking with four settings columns, 26.11.9 changelog entries --- CHANGELOG.md | 11 +- admin/database_updates/3.9.3.php | 155 +++ admin/post/settings_purchase_order.php | 41 + admin/settings_purchase_order.php | 47 + agent/includes/get_side_nav_counts.php | 3 + agent/includes/side_nav.php | 24 + agent/modals/purchasing/order_item.php | 169 +++ agent/modals/purchasing/po_add_items.php | 100 ++ agent/modals/purchasing/po_bill.php | 118 ++ agent/modals/purchasing/po_decide.php | 60 + agent/modals/purchasing/po_details.php | 107 ++ agent/modals/purchasing/po_email.php | 74 ++ agent/modals/purchasing/po_line.php | 147 ++ agent/modals/purchasing/po_new.php | 75 ++ agent/modals/purchasing/po_ordered.php | 59 + agent/modals/purchasing/po_tracking.php | 68 + agent/post/purchase_order.php | 327 +++++ agent/product.php | 6 + agent/purchase_order.php | 356 +++++ agent/purchase_orders.php | 257 ++++ agent/receiving.php | 169 +++ agent/to_order.php | 267 ++++ db.sql | 145 ++ functions.php | 1 + functions/audit_log.php | 1 + functions/auth.php | 4 +- functions/purchase_orders.php | 1547 ++++++++++++++++++++++ functions/roles.php | 8 +- functions/settings.php | 7 + js/purchase_orders.js | 39 + setup/seed_data.php | 1 + 31 files changed, 4390 insertions(+), 3 deletions(-) create mode 100644 admin/database_updates/3.9.3.php create mode 100644 admin/post/settings_purchase_order.php create mode 100644 admin/settings_purchase_order.php create mode 100644 agent/modals/purchasing/order_item.php create mode 100644 agent/modals/purchasing/po_add_items.php create mode 100644 agent/modals/purchasing/po_bill.php create mode 100644 agent/modals/purchasing/po_decide.php create mode 100644 agent/modals/purchasing/po_details.php create mode 100644 agent/modals/purchasing/po_email.php create mode 100644 agent/modals/purchasing/po_line.php create mode 100644 agent/modals/purchasing/po_new.php create mode 100644 agent/modals/purchasing/po_ordered.php create mode 100644 agent/modals/purchasing/po_tracking.php create mode 100644 agent/post/purchase_order.php create mode 100644 agent/purchase_order.php create mode 100644 agent/purchase_orders.php create mode 100644 agent/receiving.php create mode 100644 agent/to_order.php create mode 100644 functions/purchase_orders.php create mode 100644 js/purchase_orders.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 1907203f5..7f9980ca2 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-six database changes (3.6.6 to 3.9.2) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, and three settings for sending and reading Microsoft 365 mail through Microsoft Graph, and change nothing that is there. Nothing else is required. This release has twelve 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-seven database changes (3.6.6 to 3.9.3) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, and five tables, four settings and a role permission for purchase orders, and change nothing that is there. Nothing else is required. This release has twelve 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 @@ -120,6 +120,14 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Notifications: Admin > Settings > Notifications has Emails and notices to your team - switch off the bell notice or the email an agent gets when someone else assigns them a ticket or recurring ticket, or the copy of a client's reply that goes to the agents helping on a ticket (the agent it is assigned to is still emailed). All on to start with, as before. From Mountaineer IT's build of ITFlow. - Calendar and Dispatch: onsite work is easy to spot - a booking with a visit has an orange Onsite strip with a car across the top, an orange edge on the calendar's Month view and an orange line along the top on Dispatch's Week. Remote work looks as before. From Mountaineer IT's build of ITFlow. - Dispatch: the Schedule window lists the contact's other open tickets under the ticket - with who has each and when it is booked - so a duplicate is noticed before work is booked on it. Merge beside one keeps one ticket and closes the other with a note pointing to it, as the ticket's own Merge does, with a reason and the choice to move its replies over. A booking on the ticket closed is taken off first, so its agent and the client are sent the cancellation. From Mountaineer IT's build of ITFlow. +- Purchasing: a new section in the side menu - To Order, Purchase Orders and Receiving - for buying from your vendors what you sell, install and keep on the shelf. It comes with invoicing. Give roles Purchasing in Admin > Roles: See them; Add items, make and send purchase orders, add tracking and receive; or Full, which also approves and cancels purchase orders and undoes a receipt. Admins have all of it. From Mountaineer IT's build of ITFlow. +- Purchasing: To Order is the list of what needs buying. Add an item by hand - with its vendor, cost and the client it is for - or with Order on a product's page. When products are at or under their reorder level, the alert at the top adds them all in one go. Tick items, then Make a Purchase Order puts them on a new one for their vendor, or Put on a Draft adds them to one already started. From Mountaineer IT's build of ITFlow. +- Purchasing: purchase orders are numbered PO-1, PO-2 and on - the prefix and the next number are in Admin > Settings > Purchase orders. While one is a draft, its lines can be added, changed and taken off, and Edit Details changes the vendor, where it ships - your main office, another of your offices or any address - the shipping and a note for the vendor. Download it as a PDF, or Email to Vendor sends it with the PDF attached and marks it ordered in the same step. Mark Ordered is for one placed by phone or on the vendor's website, with the date and their order number. From Mountaineer IT's build of ITFlow. +- Purchasing: approval is off to start with. Switch on Purchase orders need approval in Admin > Settings > Purchase orders and give an amount: a purchase order over it, or with a line that has no cost, is sent for approval before it can be ordered. The admins and the agents with Full Purchasing get a notice and an email, and one of them approves it or sends it back with a note - whoever made it is told either way. Nobody approves their own purchase order, unless they are an admin or nobody else can. From Mountaineer IT's build of ITFlow. +- Purchasing: add tracking numbers to an ordered purchase order, with when it should arrive. UPS, FedEx, USPS, DHL, Canada Post and Royal Mail numbers link to the carrier's tracking page. From Mountaineer IT's build of ITFlow. +- Purchasing: Receiving lists everything on its way. Enter how many came in of each line: what was bought for your own stock goes on the shelf, and what was bought for a client becomes that client's assets - one for each unit, with the serial numbers you enter, the purchase order as the purchase reference, and the warranty from the product. Putting stock on the shelf takes Sales at Modify, and making assets takes Support at Modify. A short delivery leaves the purchase order part received until the rest comes in. A receipt entered by mistake can be undone on the purchase order, which takes its stock back off the shelf and deletes the assets it made - deleting assets takes Full on Support. From Mountaineer IT's build of ITFlow. +- Purchasing: Record Bill on an ordered purchase order records the vendor's bill as an expense - the amount, vendor and description filled in from the purchase order - and links the two, along with the stock it put on the shelf. It takes Financial at Modify. From Mountaineer IT's build of ITFlow. +- Purchasing: an agent who can only see some clients only sees the purchase orders whose lines are all for clients they can see. A purchase order's History shows who made, sent, approved, ordered, received and billed it, and it is in the audit log. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -261,6 +269,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Dispatch: `ajax.php` `dispatch_contact_tickets=` (`dispatchContactTickets()` - up to 15, newest first, the same client) and `dispatch_merge` (`dispatchMerge()` - Support at Modify; both tickets open and reachable, the same client; `ticketCancelSchedule()` on a booked child first). `ticketMergeInto()` moved from `agent/post/ticket.php` to `functions/ticket.php`, unchanged but for its uploads path, so both use it. From Mountaineer IT's build of ITFlow. - Database 3.9.1: `config_notify_assigned_app`, `config_notify_assigned_email` and `config_notify_helper_replies` in `settings` (default 1), read by `ticketTeamNotifyOn($key)` in `functions/ticket.php` (on before the update). `ticketMailAssigned()` and `ticketHelpersMailReplied()` send nothing when theirs is off - unless `emailCapturing()`, so the email preview still shows them - and every "assigned to you" bell notice checks `assigned_app`: `add_ticket`, `edit_ticket`, `bulk_assign_ticket`, the ticket and recurring ticket assign fields (`functions/ticket_fields.php`), bulk-assigning recurring tickets, a portal ticket from a template, and the API's ticket and recurring ticket create. From Mountaineer IT's build of ITFlow. - Microsoft Graph mail: database 3.9.2 adds `config_mail_graph_token`, `config_mail_graph_token_expires_at` and `config_mail_graph_scopes` to `settings`. New `functions/mail_graph.php`: `mailGraphToken($permission, $fresh)` trades the mailbox's refresh token for a Graph token (scope `offline_access https://graph.microsoft.com/.default`), keeps it with the scopes it carries and the new refresh token Microsoft hands back, and returns it when it carries `Mail.Send` or `Mail.ReadWrite` - otherwise null, and SMTP or IMAP are used. An app that can't use Graph is asked again after `MAIL_GRAPH_RECHECK_MINUTES` (60), or after `mailGraphForget()` (the OAuth tab's save and Connect). When the cached scopes already had a mail permission and the renewal fails, it throws with Microsoft's reason, so the email or the run stops with it rather than falling back. `mailGraphSend()` posts the finished MIME to `/me/sendMail`, or past `MAIL_GRAPH_MIME_LIMIT` (3 MB) makes a draft, adds the attachments (upload sessions over 3 MB) and sends it, deleting the draft on failure. `mailGraphMailbox()` returns `MailGraphMailbox` (`functions/mail_graph_mailbox.php`), standing in for the parts of ImapEngine `cron/ticket_email_parser.php` uses: unread, unflagged mail oldest first, each read by ImapEngine's `FileMessage` from its MIME, with read, flagged and move done through Graph. `mailGraphMailboxTest()` and `mailGraphState()` serve the Tests and OAuth tabs. The Exchange token renewals (`cron/mail_queue.php`, `cron/ticket_email_parser.php` and the Tests tab) now send `scope` (`MAIL_MICROSOFT_EXCHANGE_SCOPE`), so a refresh token last renewed for Graph still gives an Exchange token. `MAIL_GRAPH_URL` and `MAIL_MICROSOFT_LOGIN_URL` can be defined in config.php to point at a test server. From Mountaineer IT's build of ITFlow. +- Purchase orders: database 3.9.3 adds `order_items` (the To Order list - `order_item_status` waiting / ordered / received, `order_item_source` manual / reorder), `purchase_orders` (UNIQUE `po_prefix`, `po_number`; `po_ship_to_office_id` NULL for another address in `po_ship_to`; `po_expense_id` for the vendor bill), and `po_items`, `po_receipts` and `po_tracking`, each cascading from its purchase order. `settings` gets `config_po_prefix` ('PO-'), `config_po_next_number`, `config_po_approval` (0) and `config_po_approval_over`, and `modules` gets `module_procurement` - the name and the `product_vendor_id` link match Mountaineer IT's build. Everything is in the new `functions/purchase_orders.php`: `poReady()` is false until the update has run and `poLevel()` is 0 while invoicing is off; `poRequireLevel()` and `poForRequest()` stop a page, handler or window with the reason (`poOffReason()`) or the role refusal, and `poForRequest()` also refuses a PO with a line for a client the agent can't reach (`poAccessible()`; lists use `poScopeSql()`). Numbers come from `poNextNumber()` under `GET_LOCK`, with `poCreate()` retrying on a duplicate. `poMarkOrdered()` approves a draft itself when `poNeedsApproval()` says no, noting why; `poSendForApproval()` and `poDecide()` notify through `poTell()` (bell and `emailQueue()`), and `poMayApprove()` keeps a non-admin from approving their own unless they are the only approver. `poReceive()` puts own-stock lines of a tracked product on the shelf with `productStockMove(..., 'received')` (Sales at 2) and turns client lines into assets - an asset, its primary interface '01', an asset_history row and an audit entry each, up to `PO_ASSETS_MAX` (50) a line (Support at 2) - and `poUndoReceipt()` reverses one receipt. `poRecordBill()` records the expense with `expenseSave()` and sets `stock_expense_id` on the stock it received. `poPdf()` draws on `BillingPdf`, and `poEmail()` attaches it with `billingEmailPdf()` and queues it with `emailQueue()`. History is the 'Purchase Order' kind in `auditLogKinds()`. `permissionRefusedText()` reads an optional `full` from `roleModuleInfo()` for a module whose Full level isn't deleting. Pages: `agent/to_order.php`, `purchase_orders.php`, `purchase_order.php`, `receiving.php`; windows in `agent/modals/purchasing/`; handlers in `agent/post/purchase_order.php`; settings in `admin/settings_purchase_order.php`; `js/purchase_orders.js`. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.9.3.php b/admin/database_updates/3.9.3.php new file mode 100644 index 000000000..951110323 --- /dev/null +++ b/admin/database_updates/3.9.3.php @@ -0,0 +1,155 @@ + pending (waiting + * for approval) -> approved -> ordered -> partial -> received, or + * cancelled. Where it ships to (one of our offices, or an address typed + * in), shipping, the total, who approved and ordered it, and the expense + * its vendor bill was recorded as. + * po_items - its lines, each from an item on the list or added on the PO. + * po_receipts - what came in against a line: how many, the serials, and + * what it did - the assets it made for a client, the stock move it made. + * po_tracking - the tracking numbers the vendor sent. + * Settings: config_po_prefix, config_po_next_number, config_po_approval (0 - + * no approval) and config_po_approval_over (approval for a PO over this + * amount - 0 for every one). A Procurement permission for Admin > Roles + * (module_procurement): no role has it until it is given - admins always do. + * + * Re-runnable: each table, column and module is added only where it isn't there yet. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_column = function ($table, $column) use ($mysqli) { + $result = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$table' AND COLUMN_NAME = '$column' LIMIT 1"); + return $result && mysqli_num_rows($result) > 0; + }; + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `order_items` ( + `order_item_id` int(11) NOT NULL AUTO_INCREMENT, + `order_item_name` varchar(255) NOT NULL, + `order_item_description` text DEFAULT NULL, + `order_item_quantity` decimal(15,2) NOT NULL DEFAULT 1.00, + `order_item_cost` decimal(15,2) DEFAULT NULL, + `order_item_status` varchar(20) NOT NULL DEFAULT 'waiting', + `order_item_source` varchar(20) NOT NULL DEFAULT 'manual', + `order_item_note` varchar(255) DEFAULT NULL, + `order_item_product_id` int(11) NOT NULL DEFAULT 0, + `order_item_vendor_id` int(11) NOT NULL DEFAULT 0, + `order_item_client_id` int(11) NOT NULL DEFAULT 0, + `order_item_created_by` int(11) NOT NULL DEFAULT 0, + `order_item_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `order_item_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + PRIMARY KEY (`order_item_id`), + KEY `order_item_status` (`order_item_status`,`order_item_vendor_id`), + KEY `order_item_product_id` (`order_item_product_id`), + KEY `order_item_client_id` (`order_item_client_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `purchase_orders` ( + `po_id` int(11) NOT NULL AUTO_INCREMENT, + `po_prefix` varchar(200) NOT NULL DEFAULT 'PO-', + `po_number` int(11) NOT NULL, + `po_status` varchar(20) NOT NULL DEFAULT 'draft', + `po_vendor_id` int(11) NOT NULL DEFAULT 0, + `po_currency_code` varchar(200) NOT NULL DEFAULT '', + `po_ship_to_office_id` int(11) DEFAULT NULL, + `po_ship_to` text DEFAULT NULL, + `po_note` text DEFAULT NULL, + `po_shipping` decimal(15,2) NOT NULL DEFAULT 0.00, + `po_total` decimal(15,2) NOT NULL DEFAULT 0.00, + `po_vendor_reference` varchar(200) DEFAULT NULL, + `po_order_date` date DEFAULT NULL, + `po_created_by` int(11) NOT NULL DEFAULT 0, + `po_submitted_at` datetime DEFAULT NULL, + `po_approved_by` int(11) NOT NULL DEFAULT 0, + `po_approved_at` datetime DEFAULT NULL, + `po_approval_note` varchar(255) DEFAULT NULL, + `po_ordered_by` int(11) NOT NULL DEFAULT 0, + `po_ordered_at` datetime DEFAULT NULL, + `po_received_at` datetime DEFAULT NULL, + `po_cancelled_at` datetime DEFAULT NULL, + `po_expense_id` int(11) NOT NULL DEFAULT 0, + `po_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `po_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), + PRIMARY KEY (`po_id`), + UNIQUE KEY `po_number` (`po_prefix`,`po_number`), + KEY `po_status` (`po_status`), + KEY `po_vendor_id` (`po_vendor_id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `po_items` ( + `po_item_id` int(11) NOT NULL AUTO_INCREMENT, + `po_item_po_id` int(11) NOT NULL, + `po_item_order_item_id` int(11) NOT NULL DEFAULT 0, + `po_item_product_id` int(11) NOT NULL DEFAULT 0, + `po_item_client_id` int(11) NOT NULL DEFAULT 0, + `po_item_name` varchar(255) NOT NULL, + `po_item_description` text DEFAULT NULL, + `po_item_vendor_part` varchar(200) DEFAULT NULL, + `po_item_quantity` decimal(15,2) NOT NULL DEFAULT 1.00, + `po_item_cost` decimal(15,2) NOT NULL DEFAULT 0.00, + `po_item_received` decimal(15,2) NOT NULL DEFAULT 0.00, + `po_item_order` int(11) NOT NULL DEFAULT 0, + PRIMARY KEY (`po_item_id`), + KEY `po_item_po_id` (`po_item_po_id`), + KEY `po_item_order_item_id` (`po_item_order_item_id`), + KEY `po_item_client_id` (`po_item_client_id`), + CONSTRAINT `po_items_po` FOREIGN KEY (`po_item_po_id`) REFERENCES `purchase_orders` (`po_id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `po_receipts` ( + `po_receipt_id` int(11) NOT NULL AUTO_INCREMENT, + `po_receipt_po_id` int(11) NOT NULL, + `po_receipt_item_id` int(11) NOT NULL, + `po_receipt_quantity` decimal(15,2) NOT NULL, + `po_receipt_serials` text DEFAULT NULL, + `po_receipt_asset_ids` varchar(1000) DEFAULT NULL, + `po_receipt_stock_id` int(11) NOT NULL DEFAULT 0, + `po_receipt_by` int(11) NOT NULL DEFAULT 0, + `po_receipt_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`po_receipt_id`), + KEY `po_receipt_item_id` (`po_receipt_item_id`), + KEY `po_receipt_po_id` (`po_receipt_po_id`), + CONSTRAINT `po_receipts_po` FOREIGN KEY (`po_receipt_po_id`) REFERENCES `purchase_orders` (`po_id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `po_tracking` ( + `po_tracking_id` int(11) NOT NULL AUTO_INCREMENT, + `po_tracking_po_id` int(11) NOT NULL, + `po_tracking_carrier` varchar(30) NOT NULL DEFAULT '', + `po_tracking_number` varchar(100) NOT NULL DEFAULT '', + `po_tracking_eta` date DEFAULT NULL, + `po_tracking_created_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`po_tracking_id`), + KEY `po_tracking_po_id` (`po_tracking_po_id`), + CONSTRAINT `po_tracking_po` FOREIGN KEY (`po_tracking_po_id`) REFERENCES `purchase_orders` (`po_id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + if (!$itflow_column('settings', 'config_po_prefix')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_po_prefix` varchar(200) NOT NULL DEFAULT 'PO-' AFTER `config_recurring_invoice_next_number`"); + } + if (!$itflow_column('settings', 'config_po_next_number')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_po_next_number` int(11) NOT NULL DEFAULT 1 AFTER `config_po_prefix`"); + } + if (!$itflow_column('settings', 'config_po_approval')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_po_approval` tinyint(1) NOT NULL DEFAULT 0 AFTER `config_po_next_number`"); + } + if (!$itflow_column('settings', 'config_po_approval_over')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_po_approval_over` decimal(15,2) NOT NULL DEFAULT 0.00 AFTER `config_po_approval`"); + } + + // The Procurement permission - Mountaineer IT's build names it the same + if (!mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM modules WHERE module_name = 'module_procurement'"))) { + mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_procurement', module_description = 'Access to purchasing - items to order, purchase orders and receiving'"); + } diff --git a/admin/post/settings_purchase_order.php b/admin/post/settings_purchase_order.php new file mode 100644 index 000000000..7ad11a3bd --- /dev/null +++ b/admin/post/settings_purchase_order.php @@ -0,0 +1,41 @@ + Settings > Purchase orders (admin/settings_purchase_order.php): + * edit_purchase_order_settings saves the numbering - a next number already + * in use comes back to the page saying so - and the approval switch and amount. + */ + +defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); + +if (isset($_POST['edit_purchase_order_settings'])) { + + validateCSRFToken(); + + if (!poReady()) { + flashAlert('Run the database update first - Admin > Update.', 'error'); + redirect(); + } + + $before = settingsCurrent(['config_po_prefix', 'config_po_next_number', 'config_po_approval', 'config_po_approval_over']); + + [$prefix, $number, $errors] = settingsNumberingCheck('purchase_order', $_POST + array_map('strval', $before), $before); + $over_text = trim(str_replace([',', ' ', '$'], '', (string) ($_POST['config_po_approval_over'] ?? ''))); + if ($over_text !== '' && (!is_numeric($over_text) || floatval($over_text) < 0 || floatval($over_text) > 9999999999)) { + $errors['config_po_approval_over'] = 'An amount, such as 500 - or empty for every purchase order.'; + } + if ($errors) { + settingsRefuse('purchase_order', $errors); + } + + settingsSave('purchase_order', $before, [ + 'config_po_prefix' => $prefix, + 'config_po_next_number' => $number, + // A switch sends nothing when off + 'config_po_approval' => empty($_POST['config_po_approval']) ? '0' : '1', + 'config_po_approval_over' => $over_text === '' ? '0.00' : number_format(round(floatval($over_text), 2), 2, '.', ''), + ]); + + redirect(); + +} diff --git a/admin/settings_purchase_order.php b/admin/settings_purchase_order.php new file mode 100644 index 000000000..dc777be0b --- /dev/null +++ b/admin/settings_purchase_order.php @@ -0,0 +1,47 @@ + Settings > Purchase orders - how they are numbered, and whether one + * needs approving before it is ordered (functions/purchase_orders.php). + * Saved by edit_purchase_order_settings (admin/post/settings_purchase_order.php). + */ + +require_once "includes/inc_all_admin.php"; + +echo settingsPageStart('purchase_order'); + +if (!poReady()) { ?> +
Purchase orders need the database update - run it from Maintenance > Update first.
+ + +
+ + +
+
+ + + + + + Roles.') ?> + 'Purchase orders need approval', + 'help' => 'Off, a purchase order is marked ordered or emailed to the vendor straight from its draft. On, one over the amount below - or with a line that has no cost - goes to the approvers first. Whoever made it can\'t approve it, unless they are an admin or nobody else can.']) ?> + 0 ? number_format($po_settings['approval_over'], 2, '.', '') : '', ['icon' => 'fa-dollar-sign', 'inputmode' => 'decimal', + 'label' => 'Approve purchase orders over', 'placeholder' => '0.00', 'help' => 'Its total, shipping included. Empty or 0 - every purchase order needs approving.']) ?> + + + +
+
+
+ += 1 && lookupUserPermission('module_financial') >= 1 ? tripUnbilledCount()['count'] : 0; +// Purchasing - items waiting to be ordered, purchase orders waiting for this agent's approval, lines still to come in +$num_purchasing = poNavCounts(); + // Products whose stock is at or under the reorder level, or out $num_products_reorder = $config_module_enable_accounting == 1 && lookupUserPermission('module_sales') >= 1 ? productReorderCount() : 0; diff --git a/agent/includes/side_nav.php b/agent/includes/side_nav.php index 3f5f0ab5e..7412ba7d4 100644 --- a/agent/includes/side_nav.php +++ b/agent/includes/side_nav.php @@ -226,6 +226,30 @@ + = 1) { + // Purchasing - with invoicing on, for roles with Purchasing (functions/purchase_orders.php) + $po_nav_page = basename($_SERVER["PHP_SELF"]); + $po_nav_links = [ + ['to_order.php', 'fa-cart-plus', 'To Order', $num_purchasing['to_order'], 'Waiting to go on a purchase order', 'text-light', []], + ['purchase_orders.php', 'fa-file-signature', 'Purchase Orders', $num_purchasing['pending'], 'Waiting for your approval', 'text-bg-warning', ['purchase_order.php']], + ['receiving.php', 'fa-truck-loading', 'Receiving', $num_purchasing['arriving'], 'Lines on ordered purchase orders still to come in', 'text-light', []], + ]; ?> + + + + + + = 1) { ?> diff --git a/agent/modals/purchasing/order_item.php b/agent/modals/purchasing/order_item.php new file mode 100644 index 000000000..81b25d4ff --- /dev/null +++ b/agent/modals/purchasing/order_item.php @@ -0,0 +1,169 @@ + $item ? 'It is on a purchase order already - change it there.' : 'That item is no longer on the list.'])); +} +$product_id = $item ? intval($item['order_item_product_id']) : intval($_GET['product_id'] ?? 0); +$product = $product_id ? productRow($product_id) : null; + +// Defaults for a new item from a product - enough to bring it back over its reorder level +$quantity = $item ? billingQuantity($item['order_item_quantity']) : '1'; +if (!$item && $product) { + $level = floatval($product['product_reorder_level']); + $quantity = billingQuantity(floatval($product['product_reorder_qty']) > 0 ? floatval($product['product_reorder_qty']) : max(1, ceil($level - floatval($product['product_stock']) + 1))); +} +$cost = $item ? ($item['order_item_cost'] !== null ? number_format(floatval($item['order_item_cost']), 2, '.', '') : '') : ($product && floatval($product['product_cost']) > 0 ? number_format(floatval($product['product_cost']), 2, '.', '') : ''); +$vendor_id = $item ? intval($item['order_item_vendor_id']) : ($product ? intval($product['product_vendor_id']) : 0); +$client_id = $item ? intval($item['order_item_client_id']) : intval($_GET['client_id'] ?? 0); + +$products = []; +$sql = mysqli_query($mysqli, "SELECT product_id, product_name, product_cost, product_vendor_id, product_type FROM products WHERE product_archived_at IS NULL" + . ($product_id ? " OR product_id = $product_id" : '') . " ORDER BY product_name"); +while ($row = mysqli_fetch_assoc($sql)) { + $products[] = $row; +} +$clients = []; +$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE (client_archived_at IS NULL" . ($client_id ? " OR client_id = $client_id" : '') . ")" . clientScopeSql('client_id') . " ORDER BY client_name"); +while ($row = mysqli_fetch_assoc($sql)) { + $clients[] = $row; +} +$form_id = 'orderItem' . ($item ? intval($item['order_item_id']) : 'New'); + +ob_start(); + +?> + +
+ + + + + + +
+ + + + $po && $po['po_status'] !== 'draft' ? poNumber($po) . " isn't a draft any more." : 'That purchase order no longer exists.'])); +} + +if ($po) { + // Every waiting item, its vendor's first + $items = orderItemsWaiting(); + usort($items, function ($a, $b) use ($po) { + return (intval($b['order_item_vendor_id']) === intval($po['po_vendor_id'])) <=> (intval($a['order_item_vendor_id']) === intval($po['po_vendor_id'])); + }); +} else { + $items = orderItemsByIds((array) ($_GET['order_item_ids'] ?? [])); + if (!$items) { + exit(json_encode(['error' => 'Those items are no longer waiting - someone may have ordered them.'])); + } + $drafts = []; + $sql = mysqli_query($mysqli, "SELECT po_id, po_prefix, po_number, po_vendor_id, po_total, po_currency_code, vendor_name FROM purchase_orders + LEFT JOIN vendors ON vendors.vendor_id = po_vendor_id WHERE po_status = 'draft'" . poScopeSql('po_id') . " ORDER BY po_id DESC"); + while ($row = mysqli_fetch_assoc($sql)) { + $drafts[] = $row; + } + if (!$drafts) { + exit(json_encode(['error' => 'There is no draft purchase order to put them on - make one instead.'])); + } + $item_vendors = array_filter(array_map('intval', array_column($items, 'order_item_vendor_id'))); + $vendor_id = count(array_unique($item_vendors)) === 1 ? reset($item_vendors) : 0; +} + +ob_start(); + +?> + +
+ + + + + +
+ + 'That purchase order no longer exists.'])); +} +if (poExpense($po)) { + exit(json_encode(['error' => 'Its vendor bill is recorded already.'])); +} +if (!in_array($po['po_status'], ['ordered', 'partial', 'received'], true)) { + exit(json_encode(['error' => 'The vendor bill is recorded once it is ordered.'])); +} +$vendor_id = intval($po['po_vendor_id']); +$defaults = expenseVendorDefaults()[$vendor_id] ?? ['category' => 0, 'account' => 0, 'method' => '']; +$category = intval($defaults['category']); +$account = intval($defaults['account']) ?: intval($config_default_expense_account ?? 0); +$method = (string) ($defaults['method'] !== '' ? $defaults['method'] : ($config_default_expense_payment_method ?? '')); +$accounts = paymentAccounts(0); + +ob_start(); + +?> + +
+ + + + + + +
+ + 'That purchase order no longer exists.'])); +} +if (!poMayApprove($po)) { + exit(json_encode(['error' => $po['po_status'] !== 'pending' ? poNumber($po) . " isn't waiting for approval." : "You can't approve this one - it needs someone else with full Purchasing access."])); +} +$approve = intval($_GET['approve'] ?? 1) === 1; +$own = intval($po['po_created_by']) === intval($session_user_id ?? 0); + +ob_start(); + +?> + +
+ + + + + + + +
+ + 'That purchase order no longer exists.'])); +} +if (in_array($po['po_status'], ['received', 'cancelled'], true)) { + exit(json_encode(['error' => poNumber($po) . ' can no longer be changed.'])); +} +$other = $po['po_ship_to_office_id'] === null; +$form_id = 'poDetails' . intval($po['po_id']); + +ob_start(); + +?> + +
+ + + + + + +
+ + + + 'That purchase order no longer exists.'])); +} +$can_order = poCanOrder($po); +if (!$can_order && !in_array($po['po_status'], ['ordered', 'partial', 'received'], true)) { + exit(json_encode(['error' => $po['po_status'] === 'draft' || $po['po_status'] === 'pending' ? poNumber($po) . ' needs approving before it goes to the vendor.' : poNumber($po) . ' is ' . strtolower(PO_STATUSES[$po['po_status']]['label'] ?? $po['po_status']) . '.'])); +} +$to = (string) ($po['vendor_contact_email'] ?: $po['vendor_email']); +$from = billingEmailFrom('invoice'); + +ob_start(); + +?> + +
+ + + + + + +
+ + 'That purchase order no longer exists.'])); +} +if ($po['po_status'] !== 'draft') { + exit(json_encode(['error' => 'Only a draft can be changed - send it back to draft first.'])); +} +$line = null; +if (intval($_GET['item_id'] ?? 0)) { + $line = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM po_items WHERE po_item_id = " . intval($_GET['item_id']) . " AND po_item_po_id = " . intval($po['po_id']))); + if (!$line) { + exit(json_encode(['error' => 'That line is no longer on the purchase order.'])); + } +} +$product_id = intval($line['po_item_product_id'] ?? 0); +$client_id = intval($line['po_item_client_id'] ?? 0); + +$products = []; +$sql = mysqli_query($mysqli, "SELECT product_id, product_name, product_cost, product_vendor_part, product_vendor_id FROM products WHERE product_archived_at IS NULL" + . ($product_id ? " OR product_id = $product_id" : '') . " ORDER BY product_vendor_id = " . intval($po['po_vendor_id']) . " DESC, product_name"); +while ($row = mysqli_fetch_assoc($sql)) { + $products[] = $row; +} +$clients = []; +$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE (client_archived_at IS NULL" . ($client_id ? " OR client_id = $client_id" : '') . ")" . clientScopeSql('client_id') . " ORDER BY client_name"); +while ($row = mysqli_fetch_assoc($sql)) { + $clients[] = $row; +} +$form_id = 'poLine' . ($line ? intval($line['po_item_id']) : 'New'); + +ob_start(); + +?> + +
+ + + + + + + +
+ + + + 'Those items are no longer waiting - someone may have ordered them.'])); +} +$item_vendors = array_count_values(array_filter(array_map('intval', array_column($items, 'order_item_vendor_id')))); +arsort($item_vendors); +$vendor_id = intval(array_key_first($item_vendors) ?? 0); +$mixed = count($item_vendors) > 1 || ($item_vendors && in_array(0, array_map('intval', array_column($items, 'order_item_vendor_id')), true)); +$total = 0; +foreach ($items as $item) { + $total += round(floatval($item['order_item_quantity']) * floatval($item['order_item_cost'] ?? 0), 2); +} +$office = officeForUser($session_user_id ?? 0); + +ob_start(); + +?> + +
+ + + + + + + + +
+ + 'That purchase order no longer exists.'])); +} +if (!poCanOrder($po)) { + exit(json_encode(['error' => $po['po_status'] === 'draft' ? poNumber($po) . ' needs approving before it is ordered.' : poNumber($po) . ' is ' . strtolower(PO_STATUSES[$po['po_status']]['label'] ?? $po['po_status']) . '.'])); +} + +ob_start(); + +?> + +
+ + + + + + +
+ + 'That purchase order no longer exists.'])); +} +if (in_array($po['po_status'], ['draft', 'pending', 'approved', 'cancelled'], true)) { + exit(json_encode(['error' => 'Tracking goes on a purchase order once it is ordered.'])); +} + +ob_start(); + +?> + +
+ + + + + + +
+ +' . escapeHtml(trim((string) ($_POST['name'] ?? ''))) . ' ' . ($order_item_id ? 'saved' : 'is on To Order')); + redirect(); + +} + +if (isset($_POST['order_items_remove']) || isset($_GET['order_item_remove'])) { + + validateCSRFToken(); + poRequireLevel(2); + + $ids = isset($_GET['order_item_remove']) ? [intval($_GET['order_item_remove'])] : (array) ($_POST['order_item_ids'] ?? []); + $removed = orderItemsRemove($ids); + if ($removed) { + logAudit('Purchase Order', 'Delete', "$session_name took $removed item" . ($removed === 1 ? '' : 's') . " off To Order"); + } + flashAlert($removed ? "$removed item" . ($removed === 1 ? '' : 's') . ' taken off To Order' : 'Nothing was taken off - they may have been ordered already.', $removed ? 'error' : 'warning'); + redirect(); + +} + +if (isset($_POST['order_items_low_stock'])) { + + validateCSRFToken(); + poRequireLevel(2); + + $added = orderItemsAddLowStock(); + if ($added) { + logAudit('Purchase Order', 'Create', "$session_name put $added low-stock product" . ($added === 1 ? '' : 's') . " on To Order"); + } + flashAlert($added ? "$added low-stock product" . ($added === 1 ? ' is' : 's are') . ' on To Order' : 'Nothing is low on stock and not on order.'); + redirect(); + +} + +if (isset($_POST['po_create'])) { + + validateCSRFToken(); + poRequireLevel(2); + + $po_id = poCreate(intval($_POST['vendor'] ?? 0), (array) ($_POST['order_item_ids'] ?? []), $error); + if (!$po_id) { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } + $po = poRow($po_id); + flashAlert('Draft ' . escapeHtml(poNumber($po)) . ' made'); + redirect(poPageUrl($po_id)); + +} + +if (isset($_POST['po_add_items'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + $added = poAddItems($po, (array) ($_POST['order_item_ids'] ?? []), $error); + if (!$added) { + flashAlert(escapeHtml($error ?: 'Tick what goes on it.'), 'error'); + redirect(); + } + flashAlert("$added item" . ($added === 1 ? '' : 's') . ' put on ' . escapeHtml(poNumber($po)) . ''); + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_line_save'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + if (!poLineSave($po, $_POST, intval($_POST['po_item_id'] ?? 0), $error)) { + flashAlert(escapeHtml($error), 'error'); + redirect(poPageUrl($po['po_id'])); + } + flashAlert('' . escapeHtml(trim((string) ($_POST['name'] ?? ''))) . ' ' . (intval($_POST['po_item_id'] ?? 0) ? 'saved' : 'added')); + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_GET['po_line_remove'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_GET['po_id'] ?? 0), 2); + if (!poLineRemove($po, intval($_GET['po_line_remove']), $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('Line taken off', 'error'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_details_save'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + $in = array_intersect_key($_POST, array_flip(['vendor', 'ship_to', 'ship_to_address', 'shipping', 'note'])); + if (!poDetailsSave($po, $in, $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' saved'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_send_approval'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + if (!poSendForApproval($po, $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' sent for approval - the approvers are told'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_decide'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 3); + $approve = intval($_POST['approve'] ?? 0) === 1; + if (!$approve && trim((string) ($_POST['note'] ?? '')) === '') { + flashAlert('Say what to change before it comes back.', 'error'); + redirect(poPageUrl($po['po_id'])); + } + if (!poDecide($po, $approve, $_POST['note'] ?? '', $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' ' . ($approve ? 'approved' : 'sent back to draft')); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_GET['po_back_to_draft'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_GET['po_back_to_draft']), 2); + if (!poBackToDraft($po, $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' is a draft again'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_mark_ordered'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + if (!poMarkOrdered($po, $_POST['order_date'] ?? '', $_POST['vendor_reference'] ?? '', $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' marked ordered - its lines are on Receiving'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_email'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + if (!poCanOrder($po) && !in_array($po['po_status'], ['ordered', 'partial', 'received'], true)) { + flashAlert(escapeHtml(poNumber($po) . ' needs approving before it goes to the vendor.'), 'error'); + redirect(poPageUrl($po['po_id'])); + } + // Marked ordered first, so the PDF that goes is the order itself, not a draft + $marked = ''; + if (!empty($_POST['mark_ordered']) && poCanOrder($po)) { + if (!poMarkOrdered($po, date('Y-m-d'), '', $error)) { + flashAlert(escapeHtml($error), 'error'); + redirect(poPageUrl($po['po_id'])); + } + $po = poRow($po['po_id']); + $marked = ' and marked ordered'; + } + if (!poEmail($po, $_POST['to'] ?? '', $_POST['message'] ?? '', $error)) { + flashAlert(escapeHtml($error) . ($marked ? ' It was marked ordered.' : ''), 'error'); + redirect(poPageUrl($po['po_id'])); + } + flashAlert('' . escapeHtml(poNumber($po)) . ' queued to ' . escapeHtml(trim((string) $_POST['to'])) . $marked . ' - watch it go in Maintenance > Mail Queue'); + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_GET['po_cancel'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_GET['po_cancel']), 2); + if ($po['po_status'] !== 'draft' && poLevel() < 3) { + enforceUserPermission('module_procurement', 3); + } + if (!poCancel($po, $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('' . escapeHtml(poNumber($po)) . ' cancelled - its items are back on To Order', 'error'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_tracking_add'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + if (!poTrackingAdd($po, (string) ($_POST['carrier'] ?? ''), $_POST['tracking_number'] ?? '', $_POST['eta'] ?? '', $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('Tracking added'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_GET['po_tracking_remove'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_GET['po_id'] ?? 0), 2); + poTrackingRemove($po, intval($_GET['po_tracking_remove'])); + flashAlert('Tracking taken off', 'error'); + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_POST['po_receive'])) { + + validateCSRFToken(); + poRequireLevel(2); + + $done = poReceive((array) ($_POST['received'] ?? [])); + if (!$done['lines']) { + flashAlert('Type how many came in on at least one line.', 'error'); + redirect(); + } + $said = $done['lines'] . ' line' . ($done['lines'] === 1 ? '' : 's') . ' received on ' . implode(', ', $done['pos']) + . ($done['stock'] > 0 ? ' - ' . billingQuantity($done['stock']) . ' on the shelf' : '') + . ($done['assets'] ? ' - ' . $done['assets'] . ' asset' . ($done['assets'] === 1 ? '' : 's') . ' made' : ''); + flashAlert(escapeHtml($said) . ($done['skipped'] ? '
' . escapeHtml(implode('. ', $done['skipped'])) . '.' : ''), $done['skipped'] ? 'warning' : 'success'); + // Back to the PO when one was being received, else Receiving + $po_id = intval($_POST['po_id'] ?? 0); + redirect($po_id ? poPageUrl($po_id) : 'receiving.php'); + +} + +if (isset($_GET['po_receipt_undo'])) { + + validateCSRFToken(); + poRequireLevel(3); + + $receipt = mysqli_fetch_row(mysqli_query($mysqli, "SELECT po_receipt_po_id FROM po_receipts WHERE po_receipt_id = " . intval($_GET['po_receipt_undo']))); + if (!poUndoReceipt(intval($_GET['po_receipt_undo']), $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('Receipt undone - it is waiting to come in again'); + } + redirect($receipt ? poPageUrl($receipt[0]) : 'purchase_orders.php'); + +} + +if (isset($_POST['po_bill'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_POST['po_id'] ?? 0), 2); + enforceUserPermission('module_financial', 2); + if (!poRecordBill($po, $_POST, $error)) { + flashAlert(escapeHtml($error), 'error'); + } else { + flashAlert('Vendor bill recorded as an expense'); + } + redirect(poPageUrl($po['po_id'])); + +} + +if (isset($_GET['po_pdf'])) { + + validateCSRFToken(); + + $po = poForRequest(intval($_GET['po_pdf']), 1); + billingPdfSend(poPdf($po)); + +} diff --git a/agent/product.php b/agent/product.php index ef2c32517..6a87cc354 100644 --- a/agent/product.php +++ b/agent/product.php @@ -128,6 +128,12 @@ if (!$product) { + = 2 && $type === 'product' && !$archived_at) { ?> + + +
diff --git a/agent/purchase_order.php b/agent/purchase_order.php new file mode 100644 index 000000000..10fc4ceb7 --- /dev/null +++ b/agent/purchase_order.php @@ -0,0 +1,356 @@ +

That purchase order isn\'t here

' + . '

It may be for a client you can\'t see.

Back to Purchase Orders
'; + +} else { + + $po_id = intval($po['po_id']); + $status = $po['po_status']; + $number = poNumber($po); + $currency = (string) $po['po_currency_code']; + $money = function ($amount) use ($currency) { + return escapeHtml(poMoney($amount, $currency)); + }; + $level = poLevel(); + $can_edit = $level >= 2; + $draft = $status === 'draft'; + $arriving = in_array($status, ['ordered', 'partial'], true); + $ordered_or_after = in_array($status, ['ordered', 'partial', 'received'], true); + $items = poItems($po_id); + $tracking = poTracking($po_id); + $receipts = poReceipts($po_id); + $expense = poExpense($po); + $history = auditLogHistory('Purchase Order', $po_id); + $needs_approval = $draft && poNeedsApproval($po); + $can_order = $can_edit && poCanOrder($po); + $may_approve = poMayApprove($po); + $can_cancel = ($draft && $can_edit) || ($level >= 3 && in_array($status, ['pending', 'approved', 'ordered'], true) && !array_filter($items, function ($item) { + return floatval($item['po_item_received']) > 0; + })); + $can_bill = $can_edit && lookupUserPermission('module_financial') >= 2 && $ordered_or_after && !$expense; + $subtotal = 0; + foreach ($items as $item) { + $subtotal += round(floatval($item['po_item_quantity']) * floatval($item['po_item_cost']), 2); + } + $qty = array_sum(array_map('floatval', array_column($items, 'po_item_quantity'))); + $received = array_sum(array_map(function ($item) { + return min(floatval($item['po_item_received']), floatval($item['po_item_quantity'])); + }, $items)); + $waiting_count = $draft && poReady() ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM order_items WHERE order_item_status = 'waiting'" . clientScopeSql('order_item_client_id')))[0]) : 0; + $csrf = $_SESSION['csrf_token']; + $modal = function ($file, $params = '') use ($po_id) { + return "modals/purchasing/$file.php?po_id=$po_id" . ($params !== '' ? "&$params" : ''); + }; + $vendor_email = (string) ($po['vendor_contact_email'] ?: $po['vendor_email']); + + // Override Tab Title // No Sanitizing needed as this var will only be used in the tab title + $page_title = $number; + + ?> + + + + +
+
+ + +
+

+ + +

+
+ + Made + + Approved by + + Ordered + + 0) { ?> of in +
+
+ +
+ + + + +
+ + + +
+ + + + + Receive + + +
+
+
+ + true]); + $names = array_column($approvers, 'user_name'); ?> +
+ + Sent for approval - 4 ? ' or another approver' : '') . '.' : 'waiting for an admin.') ?> +
+ +
+ Sent back: +
+ +
+ + It needs approving before it is ordered - 0 && floatval($po['po_total']) <= poSettings()['approval_over'] ? 'a line has no cost.' : (poSettings()['approval_over'] > 0 ? 'it is over ' . escapeHtml(poMoney(poSettings()['approval_over'])) . '.' : 'every purchase order does.') ?> +
+ + +
+
+ +
+
+

Lines ()

+ + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ItemQtyInUnit costAmount
+ = 1 ? 'product.php?product_id=' . intval($item['po_item_product_id']) : ''; ?> +
' . escapeHtml($item['po_item_name']) . '' : escapeHtml($item['po_item_name']) ?>
+
+ + + + + Our stock + + + + +
+ +
+ +
0 ? '' : ' ' ?> 0 ? $money($item['po_item_cost']) : 'No cost' ?> + + +
Nothing on it yet
Subtotal
Shipping 0 ? $money($po['po_shipping']) : '-' ?>
Total
+
+
+ + + +
+

Received ()

+ +
+ +
+ +
+ +
+
+

Details

+ + + +
+
+
Vendor
+
+
+
+
+
Our account
+ +
Ship to
+
+ + +
Note for the vendor
+
+ +
+
+ + + +
+
+

Tracking

+ + + +
+
    + +
  • + + + + +
  • + + +
  • None yet - add the numbers the vendor sends.
  • + +
+
+ + +
+

Vendor bill

+
+ +
+ + Recorded as an expense - on . +
+ = 1) { ?> + Open the expense + + +

When the vendor's invoice comes, record it as an expense here - it stays linked to .

+ + + Not recorded yet. + +
+
+ + + 'Nothing logged yet.']) ?> +
+
+ + Purchase Orders - every purchase order the agent can see (one + * for a client they can't see is left out). Along the top, what is waiting to + * be ordered, waiting for approval, on order and in this month. Tabs: Open + * (the default - not received or cancelled), Drafts, Awaiting approval, + * Approved, Ordered (partly received too), Received, Cancelled and All. The + * work is in functions/purchase_orders.php; the handlers are + * agent/post/purchase_order.php. + */ + +// Default Column Sortby/Order Filter +$sort = "po_number"; +$order = "DESC"; + +require_once "includes/inc_all.php"; + +poRequireLevel(1); +$can_edit = poLevel() >= 2; + +$views = [ + 'open' => ['label' => 'Open', 'icon' => '', 'where' => "po_status IN ('draft', 'pending', 'approved', 'ordered', 'partial')"], + 'draft' => ['label' => 'Drafts', 'icon' => 'fa-pencil-alt', 'where' => "po_status = 'draft'"], + 'pending' => ['label' => 'Awaiting approval', 'icon' => 'fa-hourglass-half', 'where' => "po_status = 'pending'"], + 'approved' => ['label' => 'Approved', 'icon' => 'fa-thumbs-up', 'where' => "po_status = 'approved'"], + 'ordered' => ['label' => 'Ordered', 'icon' => 'fa-paper-plane', 'where' => "po_status IN ('ordered', 'partial')", 'title' => 'Ordered, and partly received'], + 'received' => ['label' => 'Received', 'icon' => 'fa-check-double', 'where' => "po_status = 'received'"], + 'cancelled' => ['label' => 'Cancelled', 'icon' => 'fa-ban', 'where' => "po_status = 'cancelled'"], + 'all' => ['label' => 'All', 'icon' => '', 'where' => '1 = 1'], +]; +$view = isset($views[$_GET['show'] ?? '']) ? $_GET['show'] : 'open'; +$vendor_filter = intval($_GET['vendor'] ?? 0); + +$sortable_columns = [ + 'po_number' => "po_number $order", + 'vendor_name' => "vendor_name $order, po_number DESC", + 'po_total' => "po_total $order", + 'po_order_date' => "po_order_date IS NULL, po_order_date $order, po_number DESC", + 'po_status' => "FIELD(po_status, 'pending', 'draft', 'approved', 'ordered', 'partial', 'received', 'cancelled') $order, po_number DESC", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'po_number'; +} + +$scope = poScopeSql('po_id'); +$search = $q !== '' ? " AND (CONCAT(po_prefix, po_number) LIKE '%$q%' OR vendor_name LIKE '%$q%' OR po_vendor_reference LIKE '%$q%' OR po_note LIKE '%$q%' + OR po_id IN (SELECT po_item_po_id FROM po_items LEFT JOIN clients ON client_id = po_item_client_id WHERE po_item_name LIKE '%$q%' OR po_item_vendor_part LIKE '%$q%' OR client_name LIKE '%$q%'))" : ''; +$filters = $scope . $search . ($vendor_filter ? " AND po_vendor_id = $vendor_filter" : ''); +$joins = "LEFT JOIN vendors ON vendors.vendor_id = po_vendor_id LEFT JOIN users ON user_id = po_created_by"; + +$pos = []; +$num_rows = [0]; +$counts = array_fill_keys(array_keys($views), 0); +$stats = ['to_order' => 0, 'pending' => 0, 'on_order' => 0, 'on_order_total' => 0, 'received_month' => 0]; +$lines = []; +if (poReady()) { + $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS purchase_orders.*, vendor_name, user_name AS created_by_name + FROM purchase_orders $joins + WHERE {$views[$view]['where']} $filters + ORDER BY {$sortable_columns[$sort]}, po_id DESC LIMIT $record_from, $record_to"); + $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + while ($row = mysqli_fetch_assoc($sql)) { + $pos[] = $row; + } + + // Each one's lines - how many, who they are for, and how much has come in + if ($pos) { + $ids = implode(',', array_map('intval', array_column($pos, 'po_id'))); + $sql = mysqli_query($mysqli, "SELECT po_item_po_id, COUNT(*) AS lines_count, SUM(po_item_quantity) AS qty, SUM(LEAST(po_item_received, po_item_quantity)) AS received, + GROUP_CONCAT(DISTINCT IF(po_item_client_id > 0, client_name, NULL) ORDER BY client_name SEPARATOR '|') AS clients, SUM(po_item_client_id = 0) AS stock_lines + FROM po_items LEFT JOIN clients ON client_id = po_item_client_id AND po_item_client_id > 0 + WHERE po_item_po_id IN ($ids) GROUP BY po_item_po_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $lines[intval($row['po_item_po_id'])] = $row; + } + } + + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', array_map(function ($v) { + return "COALESCE(SUM({$v['where']}), 0)"; + }, $views)) . " FROM purchase_orders $joins WHERE 1 $filters")); + $counts = array_combine(array_keys($views), array_map('intval', $row)); + + // The figures along the top - everything the agent can see, whatever the search + $stats = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT + COALESCE(SUM(po_status = 'pending'), 0) AS pending, + COALESCE(SUM(po_status IN ('ordered', 'partial')), 0) AS on_order, + COALESCE(SUM(IF(po_status IN ('ordered', 'partial'), po_total, 0)), 0) AS on_order_total, + COALESCE(SUM(po_status = 'received' AND po_received_at >= '" . date('Y-m-01') . "'), 0) AS received_month + FROM purchase_orders WHERE 1 $scope")); + $stats['to_order'] = poNavCounts()['to_order']; +} + +$filter_url = function ($changes) { + $params = array_merge($_GET, $changes); + unset($params['page']); + return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; })); +}; +$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) { + return '' + . $label . ($sort === $column ? " $order_icon" : '') . ''; +}; +$csrf = $_SESSION['csrf_token']; + +?> + + + +
+
+

Purchase Orders

+
+ + + +
+
+ +
+
+ +
+
+
+ + +
+
+
+ +
+
+
+ +
+ +
+ + + + + + + + + + + + + + 0, 'qty' => 0, 'received' => 0, 'clients' => '', 'stock_lines' => 0]; + $clients = array_filter(explode('|', (string) $line['clients'])); + $for = array_merge($clients, intval($line['stock_lines']) ? ['Our stock'] : []); + $arriving = in_array($row['po_status'], ['ordered', 'partial'], true); ?> + + + + + + + + + + + +
For
+
+ +
+ +
line
+
+
+
2 ? ' +' . (count($for) - 2) : '')) : 'Nothing yet' ?> + + 0) { ?> +
of in
+ +
Made
+ +
Not yet' ?> + +
+
+ 'purchase orders', + 'icon' => 'fa-file-signature', + 'filtered' => $q !== '' || $vendor_filter, + 'views' => ['show'], + 'view' => emptyStatePill($views, $view, 'open'), + 'text' => 'What you buy from your vendors - made from To Order, approved when it needs to be, emailed to the vendor and received as it arrives.', + 'actions' => $can_edit ? [['label' => 'New Purchase Order', 'modal' => 'modals/purchasing/po_new.php']] : [], + ]; + require_once "../includes/filter_footer.php"; + ?> +
+ + Receiving - every line still to come in on the purchase orders + * that are ordered, by PO, oldest order first - or one PO's (?po_id=). Type + * how many came in (All fills in what is left) and receive them together. + * Our own stock of a product that tracks it goes on the shelf; a client's + * hardware can become their assets, a unit each, with the serials typed. The + * work is poReceive() in functions/purchase_orders.php. + */ + +require_once "includes/inc_all.php"; + +poRequireLevel(1); +$can_edit = poLevel() >= 2; +$can_assets = lookupUserPermission('module_support') >= 2; +$can_stock = lookupUserPermission('module_sales') >= 2; + +$po_filter = intval($_GET['po_id'] ?? 0); +$vendor_filter = intval($_GET['vendor'] ?? 0); +$by_po = poAwaitingLines($po_filter); +if ($vendor_filter) { + $by_po = array_filter($by_po, function ($lines) use ($mysqli, $vendor_filter) { + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT po_vendor_id FROM purchase_orders WHERE po_id = " . intval($lines[0]['po_item_po_id'])))[0] ?? 0) === $vendor_filter; + }); +} +$tracking = poTrackingFor(array_keys($by_po)); +$asset_types = array_keys(productAssetTypes()); +$line_count = array_sum(array_map('count', $by_po)); + +?> + +
+
+

Receiving

+ +
+ +
+
+
+
+ +
+
+ + Show every purchase order + + line on purchase order still to come in. + +
+
+
+
+ + + 'deliveries', 'icon' => 'fa-truck-loading', 'filtered' => (bool) ($po_filter || $vendor_filter), + 'title' => 'Nothing to receive', 'text' => 'Lines show here once their purchase order is marked ordered, until all of them have come in.']) ?> + +
+ + + $lines) { + $head = $lines[0]; ?> +
+
+ + · + · ordered + · their order + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + +
ItemOrderedIn so farCame inSerials
+
+
+ + + + Our stock - goes on the shelf + + Our stock + + · +
+
+ +
+ + + +
+ + to come + +
+ + + +
+ + +
+ + +
+
+
+ + + + +
+ +
+ + + To Order - what is waiting to go on a purchase order: items + * added by hand, or from products that are low on stock. Each is for a client + * or for our own stock, with who it comes from and what it costs. Tick some + * to make a purchase order to one vendor, put them on a draft one, or take + * them off. The work is in functions/purchase_orders.php; the handlers are + * agent/post/purchase_order.php. + */ + +// Default Column Sortby/Order Filter +$sort = "vendor_name"; +$order = "ASC"; + +require_once "includes/inc_all.php"; + +poRequireLevel(1); +$can_edit = poLevel() >= 2; + +$vendor_filter = intval($_GET['vendor'] ?? 0); +$client_filter = intval($_GET['client'] ?? 0); + +$sortable_columns = [ + 'order_item_name' => "order_item_name $order", + 'client_name' => "order_item_client_id = 0 $order, client_name $order, order_item_name ASC", + 'vendor_name' => "vendor_name IS NULL $order, vendor_name $order, order_item_name ASC", + 'order_item_quantity' => "order_item_quantity $order", + 'order_item_cost' => "order_item_cost IS NULL, order_item_cost $order", + 'order_item_created_at' => "order_item_created_at $order", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'vendor_name'; +} + +$where = "order_item_status = 'waiting'" . clientScopeSql('order_item_client_id') + . ($vendor_filter ? " AND order_item_vendor_id = " . max(0, $vendor_filter) : '') + . ($client_filter ? " AND order_item_client_id = " . max(0, $client_filter) : '') + . ($q !== '' ? " AND (order_item_name LIKE '%$q%' OR order_item_description LIKE '%$q%' OR order_item_note LIKE '%$q%' OR vendor_name LIKE '%$q%' OR client_name LIKE '%$q%' OR product_name LIKE '%$q%')" : ''); +$joins = "LEFT JOIN clients ON client_id = order_item_client_id AND order_item_client_id > 0 + LEFT JOIN vendors ON vendor_id = order_item_vendor_id AND order_item_vendor_id > 0 + LEFT JOIN products ON product_id = order_item_product_id AND order_item_product_id > 0 + LEFT JOIN users ON user_id = order_item_created_by AND order_item_created_by > 0"; + +$items = []; +$num_rows = [0]; +$totals = ['count' => 0, 'amount' => 0, 'no_vendor' => 0, 'no_cost' => 0]; +$low_stock = []; +if (poReady()) { + $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS order_items.*, client_name, vendor_name, product_name, user_name AS created_by_name + FROM order_items $joins + WHERE $where + ORDER BY {$sortable_columns[$sort]}, order_item_id ASC LIMIT $record_from, $record_to"); + $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + while ($row = mysqli_fetch_assoc($sql)) { + $items[] = $row; + } + // Across everything waiting the agent can see, whatever the search + $totals = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(*) AS count, COALESCE(SUM(ROUND(order_item_quantity * COALESCE(order_item_cost, 0), 2)), 0) AS amount, + COALESCE(SUM(order_item_vendor_id = 0), 0) AS no_vendor, COALESCE(SUM(order_item_cost IS NULL OR order_item_cost <= 0), 0) AS no_cost + FROM order_items WHERE order_item_status = 'waiting'" . clientScopeSql('order_item_client_id'))); + $low_stock = $can_edit ? orderItemsLowStock() : []; +} + +$filter_url = function ($changes) { + $params = array_merge($_GET, $changes); + unset($params['page']); + return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null && $v !== 0; })); +}; +$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) { + return '' + . $label . ($sort === $column ? " $order_icon" : '') . ''; +}; +$csrf = $_SESSION['csrf_token']; +$drafts = poReady() ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM purchase_orders WHERE po_status = 'draft'" . poScopeSql('po_id')))[0]) : 0; + +?> + + +
+ + product low on stock and not on order - + 4 ? ' and ' . (count($low_stock) - 4) . ' more' : '')) ?>. +
+ + +
+
+ + +
+
+

To Order

+
+ + + +
+
+ +
+
+ + +
+
+
+ + +
+
+
+ +
+
+ +
+
+
+ + + +
+
+
+
+ +
+ waiting, about + · with no vendor yet + · without a cost +
+ +
+ +
+ +
+ + + + + + + + + + + + + + + + + + 0; ?> + + + + + + + + + + + + + + + +
+
+ +
+
Amount
+
+ +
+
+ = 1 ? 'product.php?product_id=' . intval($row['order_item_product_id']) : ''; ?> +
' . escapeHtml($row['order_item_name']) . '' : escapeHtml($row['order_item_name']) ?> + Restock +
+ +
+ + +
+ + +
+ +
+ + + + Our stock + + + + + + Not set + + No cost' ?> + + + +
+
+
+ 'items to order', + 'icon' => 'fa-cart-plus', + 'filtered' => $q !== '' || $vendor_filter || $client_filter, + 'text' => 'What needs buying - for a client, or for your own stock. Tick items to make a purchase order to their vendor.', + 'actions' => $can_edit ? [['label' => 'Add Item', 'modal' => 'modals/purchasing/order_item.php']] : [], + ]; + require_once "../includes/filter_footer.php"; + ?> +
+ + + ['icon' => 'fa-file-invoice', 'module' => 'module_sales', 'table' => 'invoices', 'id' => 'invoice_id', 'name' => "CONCAT(invoice_prefix, invoice_number)", 'client' => 'invoice_client_id', 'url' => '/agent/invoice.php?invoice_id={id}'], 'Contract' => ['icon' => 'fa-file-contract', 'module' => 'module_sales', 'table' => 'contracts', 'id' => 'contract_id', 'name' => 'contract_name', 'client' => 'contract_client_id', 'url' => '/agent/contract.php?contract_id={id}'], 'Recurring Invoice' => ['icon' => 'fa-redo-alt', 'module' => 'module_sales', 'table' => 'recurring_invoices', 'id' => 'recurring_invoice_id', 'name' => "CONCAT(recurring_invoice_prefix, recurring_invoice_number)", 'client' => 'recurring_invoice_client_id', 'url' => '/agent/recurring_invoice.php?recurring_invoice_id={id}'], + 'Purchase Order' => ['icon' => 'fa-file-signature', 'module' => 'module_procurement', 'table' => 'purchase_orders', 'id' => 'po_id', 'name' => "CONCAT(po_prefix, po_number)", 'url' => '/agent/purchase_order.php?po_id={id}'], 'Product' => ['icon' => 'fa-box-open', 'module' => 'module_sales', 'table' => 'products', 'id' => 'product_id', 'name' => 'product_name', 'url' => '/agent/product.php?product_id={id}'], 'Expense' => ['icon' => 'fa-shopping-cart', 'module' => 'module_financial', 'table' => 'expenses', 'id' => 'expense_id', 'name' => 'expense_description', 'client' => 'expense_client_id', 'url' => '/agent/expenses.php?open={id}'], 'Recurring Expense' => ['icon' => 'fa-redo-alt', 'module' => 'module_financial', 'table' => 'recurring_expenses', 'id' => 'recurring_expense_id', 'name' => 'recurring_expense_description', 'client' => 'recurring_expense_client_id', 'url' => '/agent/recurring_expenses.php?open={id}'], diff --git a/functions/auth.php b/functions/auth.php index 9c6308cb6..ead0abbd0 100644 --- a/functions/auth.php +++ b/functions/auth.php @@ -93,7 +93,9 @@ function permissionRefusedText($module, $level, $has = 0) { } elseif ($level === 2) { $why = "$who can only view $label, not change it."; } else { - $why = "$who can't delete in $label - that takes Full access."; + // What Full adds, for a module where it isn't deleting - roleModuleInfo()'s 'full' + $full = roleModuleInfo()[$module]['full'] ?? "delete in $label"; + $why = "$who can't $full - that takes Full access."; } return "$why An admin can change what your role allows in Admin > Roles."; } diff --git a/functions/purchase_orders.php b/functions/purchase_orders.php new file mode 100644 index 000000000..9faad87f3 --- /dev/null +++ b/functions/purchase_orders.php @@ -0,0 +1,1547 @@ + Settings > + * Purchase orders. + * + * The To Order list holds items added by hand, or from products that are low + * on stock - each for a client or for our own stock, with who it comes from + * and what it costs. Ticked items become a purchase order to one vendor. + * A PO goes draft -> pending (waiting for approval, when approval is on and + * it is over the amount set, or a line has no cost) -> approved -> ordered -> + * partial -> received, or is cancelled - its items go back on the list. + * + * Receiving records what came in against each line. A line for our own stock + * of a product that tracks stock goes on the shelf; a line for a client can + * become the client's assets, one a unit, with its serial. A receipt can be + * undone - what it did is undone with it. The vendor's bill is recorded as an + * expense against the PO. + * + * Permission: Procurement (module_procurement, Admin > Roles). View sees it + * all; Edit adds items, makes and sends POs, adds tracking and receives; + * Full approves, sends back, cancels a PO past its draft and undoes a + * receipt. Admins always have Full. Mountaineer IT's build names the + * permission the same. + */ + +const PO_STATUSES = [ + 'draft' => ['label' => 'Draft', 'tone' => 'secondary', 'icon' => 'fa-pencil-alt'], + 'pending' => ['label' => 'Awaiting approval', 'tone' => 'warning', 'icon' => 'fa-hourglass-half'], + 'approved' => ['label' => 'Approved', 'tone' => 'info', 'icon' => 'fa-thumbs-up'], + 'ordered' => ['label' => 'Ordered', 'tone' => 'primary', 'icon' => 'fa-paper-plane'], + 'partial' => ['label' => 'Partly received', 'tone' => 'warning', 'icon' => 'fa-truck-loading'], + 'received' => ['label' => 'Received', 'tone' => 'success', 'icon' => 'fa-check-double'], + 'cancelled' => ['label' => 'Cancelled', 'tone' => 'dark', 'icon' => 'fa-ban'], +]; +/* Still being worked on - not received or cancelled */ +const PO_OPEN_STATUSES = ['draft', 'pending', 'approved', 'ordered', 'partial']; + +/* Carriers, and where each one's tracking page is ({n} - the tracking number) */ +const PO_CARRIERS = [ + 'ups' => ['UPS', 'https://www.ups.com/track?tracknum={n}'], + 'fedex' => ['FedEx', 'https://www.fedex.com/fedextrack/?trknbr={n}'], + 'usps' => ['USPS', 'https://tools.usps.com/go/TrackConfirmAction?tLabels={n}'], + 'dhl' => ['DHL', 'https://www.dhl.com/global-en/home/tracking/tracking-express.html?tracking-id={n}'], + 'canada_post' => ['Canada Post', 'https://www.canadapost-postescanada.ca/track-reperage/en#/search?searchFor={n}'], + 'royal_mail' => ['Royal Mail', 'https://www.royalmail.com/track-your-item#/tracking-results/{n}'], + 'amazon' => ['Amazon', ''], + 'other' => ['Other', ''], +]; + +/* At most this many assets are made from one line at a time */ +const PO_ASSETS_MAX = 50; + +/** Are the purchasing tables there yet - the 3.9.3 update? */ +function poReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + $result = mysqli_query($mysqli, "SHOW TABLES LIKE 'purchase_orders'"); + $ready = $result && mysqli_num_rows($result) > 0; + } + return $ready; +} + +/** The signed-in agent's Procurement level - 0 none (or invoicing off, or before 3.9.3), 1 view, 2 edit, 3 full. */ +function poLevel() { + global $config_module_enable_accounting; + static $level = null; + if ($level === null) { + $level = poReady() && intval($config_module_enable_accounting ?? 0) === 1 ? intval(lookupUserPermission('module_procurement')) : 0; + } + return $level; +} + +/** The purchase order settings - prefix, next, approval (bool), approval_over (0 - every PO). */ +function poSettings() { + global $mysqli; + static $settings = null; + if ($settings === null) { + $row = poReady() ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_po_prefix, config_po_next_number, config_po_approval, config_po_approval_over FROM settings WHERE company_id = 1")) : null; + $settings = [ + 'prefix' => (string) ($row['config_po_prefix'] ?? 'PO-'), + 'next' => max(1, intval($row['config_po_next_number'] ?? 1)), + 'approval' => intval($row['config_po_approval'] ?? 0) === 1, + 'approval_over' => max(0, floatval($row['config_po_approval_over'] ?? 0)), + ]; + } + return $settings; +} + +/** A PO's number as shown - PO-12. */ +function poNumber(array $po) { + return $po['po_prefix'] . $po['po_number']; +} + +/** A status as a badge. */ +function poStatusBadge($status) { + $s = PO_STATUSES[$status] ?? ['label' => ucfirst((string) $status), 'tone' => 'secondary', 'icon' => 'fa-circle']; + return '' . escapeHtml($s['label']) . ''; +} + +/** Money in the PO's currency (the company's when it has none). */ +function poMoney($amount, $currency = '') { + global $session_company_currency; + return billingMoney(floatval($amount), (string) ($currency !== '' ? $currency : ($session_company_currency ?? ''))); +} + +/** A tracking number's page at its carrier, or '' when there is none to link to. */ +function poTrackingUrl($carrier, $number) { + $pattern = PO_CARRIERS[$carrier][1] ?? ''; + return $pattern === '' ? '' : str_replace('{n}', rawurlencode(trim((string) $number)), $pattern); +} + +/** A money or quantity typed in ("1,200", "$40") as a number rounded to cents - null when empty or not a number. */ +function poNumberIn($value) { + $text = trim(str_replace([',', ' ', '$', '£', '€'], '', (string) $value)); + return $text !== '' && is_numeric($text) ? round(floatval($text), 2) : null; +} + +/** Who the signed-in agent is, raw (the session keeps the name escaped for SQL). */ +function poWho() { + global $session_name; + return stripslashes((string) ($session_name ?? '')); +} + +/** Add to a PO's history - the audit log, where the PO page shows it. $description raw. */ +function poLog(array $po, $action, $description, $client_id = 0) { + logAudit('Purchase Order', $action, escapeSql(mb_substr($description, 0, 1000)), intval($client_id), intval($po['po_id'])); +} + +/* ------------------------------------------------------------- Reading */ + +/** A PO with its vendor and who made, approved and ordered it - or null. Not scoped: see poAccessible(). */ +function poRow($po_id) { + global $mysqli; + $po_id = intval($po_id); + if (!$po_id || !poReady()) { + return null; + } + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT purchase_orders.*, vendor_name, vendor_email, vendor_contact_name, vendor_contact_email, + vendor_phone, vendor_phone_country_code, vendor_account_number, vendor_website, + creator.user_name AS created_by_name, approver.user_name AS approved_by_name, orderer.user_name AS ordered_by_name + FROM purchase_orders + LEFT JOIN vendors ON vendors.vendor_id = po_vendor_id + LEFT JOIN users creator ON creator.user_id = po_created_by + LEFT JOIN users approver ON approver.user_id = po_approved_by AND po_approved_by > 0 + LEFT JOIN users orderer ON orderer.user_id = po_ordered_by AND po_ordered_by > 0 + WHERE po_id = $po_id")) ?: null; +} + +/** A PO's lines, in order, with the client each is for and its product. */ +function poItems($po_id) { + global $mysqli; + $po_id = intval($po_id); + $rows = []; + $sql = mysqli_query($mysqli, "SELECT po_items.*, client_name, product_name, product_track_stock, product_asset_type, product_make, product_model, product_warranty_months + FROM po_items + LEFT JOIN clients ON client_id = po_item_client_id AND po_item_client_id > 0 + LEFT JOIN products ON product_id = po_item_product_id AND po_item_product_id > 0 + WHERE po_item_po_id = $po_id ORDER BY po_item_order ASC, po_item_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** What is still to come in on a line. */ +function poItemLeft(array $item) { + return max(0, round(floatval($item['po_item_quantity']) - floatval($item['po_item_received']), 2)); +} + +/* + * SQL keeping to POs ($po_column) the agent can see every client of - " AND + * ..." or '' for an agent who sees every client. A PO for our own stock is + * everyone's. + */ +function poScopeSql($po_column) { + $scope = clientScopeSql('scope_items.po_item_client_id'); + return $scope === '' ? '' : " AND $po_column NOT IN (SELECT scope_items.po_item_po_id FROM po_items scope_items WHERE scope_items.po_item_client_id > 0 AND NOT (1 = 1 $scope))"; +} + +/** Can the signed-in agent see every client on this PO? */ +function poAccessible($po_id) { + global $mysqli; + $sql = mysqli_query($mysqli, "SELECT DISTINCT po_item_client_id FROM po_items WHERE po_item_po_id = " . intval($po_id) . " AND po_item_client_id > 0"); + while ($row = mysqli_fetch_row($sql)) { + if (!hasClientAccess(intval($row[0]))) { + return false; + } + } + return true; +} + +/** Why nobody can use Purchasing yet - the database update, or invoicing off - or '' when it is on. */ +function poOffReason() { + global $config_module_enable_accounting; + if (!poReady()) { + return 'Purchasing needs the database update - ask an admin to run it from Maintenance > Update.'; + } + if (intval($config_module_enable_accounting ?? 0) !== 1) { + return "Purchasing isn't on - it comes with invoicing, in Admin > Settings > Modules."; + } + return ''; +} + +/** Stop unless the signed-in agent has at least this Purchasing level - and Purchasing is on. A window gets the reason in JSON. */ +function poRequireLevel($level = 1) { + $level = max(1, intval($level)); + if (poLevel() >= $level) { + return; + } + $off = poOffReason(); + if ($off === '') { + enforceUserPermission('module_procurement', $level); // their role - doesn't return + } + if (defined('ITFLOW_MODAL')) { + exit(json_encode(['error' => $off])); + } + flashAlert($off, 'error'); + redirect('dashboard.php'); +} + +/** The PO a request is about, once the agent's level and its clients are checked - or the request stops. */ +function poForRequest($po_id, $level = 1) { + poRequireLevel($level); + $po = poRow($po_id); + if (!$po || !poAccessible($po['po_id'])) { + flashAlert("That purchase order doesn't exist, or it is for a client you can't see.", 'error'); + redirect('purchase_orders.php'); + } + return $po; +} + +/** The clients on a PO - client_id => name. */ +function poClients($po_id) { + global $mysqli; + $clients = []; + $sql = mysqli_query($mysqli, "SELECT DISTINCT client_id, client_name FROM po_items JOIN clients ON client_id = po_item_client_id WHERE po_item_po_id = " . intval($po_id) . " ORDER BY client_name"); + while ($row = mysqli_fetch_row($sql)) { + $clients[intval($row[0])] = $row[1]; + } + return $clients; +} + +/** The client a PO is logged against - its one client, or none. */ +function poLogClient($po_id) { + $clients = poClients($po_id); + return count($clients) === 1 ? array_key_first($clients) : 0; +} + +/** Our vendors - vendor_id => name (the ones on products: not a client's own). */ +function poVendors($keep_id = 0) { + global $mysqli; + $vendors = productVendors(); + $keep_id = intval($keep_id); + if ($keep_id && !isset($vendors[$keep_id])) { + $name = mysqli_fetch_row(mysqli_query($mysqli, "SELECT vendor_name FROM vendors WHERE vendor_id = $keep_id")); + if ($name) { + $vendors[$keep_id] = $name[0]; + } + } + return $vendors; +} + +/* ------------------------------------------------------------- To order */ + +/** An item on the list, scoped to the agent's clients - or null. */ +function orderItemRow($order_item_id) { + global $mysqli; + $order_item_id = intval($order_item_id); + if (!$order_item_id || !poReady()) { + return null; + } + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT order_items.*, client_name, vendor_name, product_name + FROM order_items + LEFT JOIN clients ON client_id = order_item_client_id AND order_item_client_id > 0 + LEFT JOIN vendors ON vendor_id = order_item_vendor_id AND order_item_vendor_id > 0 + LEFT JOIN products ON product_id = order_item_product_id AND order_item_product_id > 0 + WHERE order_item_id = $order_item_id" . clientScopeSql('order_item_client_id'))) ?: null; +} + +/* + * Add an item to the list, or change one still waiting. $in holds raw values: + * product (a product id - its name, vendor and cost fill what is left empty), + * name, description, quantity, cost, vendor, client (0 - our own stock), + * note, source (manual, reorder). The item's id, or 0 with $error. + */ +function orderItemSave(array $in, $order_item_id = 0, &$error = '') { + global $mysqli, $session_user_id; + $error = ''; + $order_item_id = intval($order_item_id); + $existing = $order_item_id ? orderItemRow($order_item_id) : null; + if ($order_item_id && (!$existing || $existing['order_item_status'] !== 'waiting')) { + $error = $existing ? 'It is on a purchase order already - change it there.' : 'That item is no longer on the list.'; + return 0; + } + $product = intval($in['product'] ?? 0) ? productRow(intval($in['product'])) : null; + $name = trim((string) ($in['name'] ?? '')); + if ($name === '' && $product) { + $name = (string) $product['product_name']; + } + if ($name === '') { + $error = 'Say what to order.'; + return 0; + } + $quantity = poNumberIn($in['quantity'] ?? ''); + if ($quantity === null || $quantity <= 0 || $quantity > 9999999) { + $error = 'How many - a number above zero.'; + return 0; + } + $cost_text = trim((string) ($in['cost'] ?? '')); + $cost = poNumberIn($cost_text); + if ($cost_text !== '' && ($cost === null || $cost < 0 || $cost > 9999999999)) { + $error = 'The unit cost is a number, zero or more - or leave it empty.'; + return 0; + } + if ($cost_text === '' && $product && floatval($product['product_cost']) > 0) { + $cost = round(floatval($product['product_cost']), 2); + } + $vendor = intval($in['vendor'] ?? 0); + if (!$vendor && $product) { + $vendor = intval($product['product_vendor_id']); + } + if ($vendor && !isset(poVendors($existing ? $existing['order_item_vendor_id'] : 0)[$vendor])) { + $vendor = 0; + } + $client = intval($in['client'] ?? 0); + if ($client && (!hasClientAccess($client) || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client")))) { + $error = "That client isn't one you can order for."; + return 0; + } + $source = in_array($in['source'] ?? '', ['manual', 'reorder'], true) ? $in['source'] : ($existing ? $existing['order_item_source'] : 'manual'); + $description = trim((string) ($in['description'] ?? '')); + $note = mb_substr(trim((string) ($in['note'] ?? '')), 0, 255); + + $set = "order_item_name = '" . escapeSql(mb_substr($name, 0, 255)) . "', order_item_description = " . ($description === '' ? 'NULL' : "'" . escapeSql($description) . "'") . ", + order_item_quantity = $quantity, order_item_cost = " . ($cost === null ? 'NULL' : $cost) . ", order_item_note = " . ($note === '' ? 'NULL' : "'" . escapeSql($note) . "'") . ", + order_item_product_id = " . ($product ? intval($product['product_id']) : 0) . ", order_item_vendor_id = $vendor, order_item_client_id = $client, order_item_source = '$source'"; + if ($existing) { + mysqli_query($mysqli, "UPDATE order_items SET $set WHERE order_item_id = $order_item_id"); + return $order_item_id; + } + mysqli_query($mysqli, "INSERT INTO order_items SET $set, order_item_status = 'waiting', order_item_created_by = " . intval($session_user_id)); + return intval(mysqli_insert_id($mysqli)); +} + +/** Items waiting to be ordered that the agent can see - $vendor_id -1 for none set yet, $client_id -1 for our own stock. */ +function orderItemsWaiting($vendor_id = 0, $client_id = 0) { + global $mysqli; + $where = "order_item_status = 'waiting'" . clientScopeSql('order_item_client_id'); + $vendor_id = intval($vendor_id); + $client_id = intval($client_id); + if ($vendor_id) { + $where .= " AND order_item_vendor_id = " . max(0, $vendor_id); + } + if ($client_id) { + $where .= " AND order_item_client_id = " . max(0, $client_id); + } + $rows = []; + $sql = mysqli_query($mysqli, "SELECT order_items.*, client_name, vendor_name, product_name, user_name AS created_by_name + FROM order_items + LEFT JOIN clients ON client_id = order_item_client_id AND order_item_client_id > 0 + LEFT JOIN vendors ON vendor_id = order_item_vendor_id AND order_item_vendor_id > 0 + LEFT JOIN products ON product_id = order_item_product_id AND order_item_product_id > 0 + LEFT JOIN users ON user_id = order_item_created_by AND order_item_created_by > 0 + WHERE $where + ORDER BY vendor_name IS NULL, vendor_name ASC, order_item_client_id = 0, client_name ASC, order_item_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** Waiting items by id, that the agent can see. */ +function orderItemsByIds(array $ids) { + global $mysqli; + $ids = array_values(array_unique(array_filter(array_map('intval', $ids)))); + if (!$ids || !poReady()) { + return []; + } + $rows = []; + $sql = mysqli_query($mysqli, "SELECT order_items.*, product_vendor_part FROM order_items + LEFT JOIN products ON product_id = order_item_product_id AND order_item_product_id > 0 + WHERE order_item_id IN (" . implode(',', $ids) . ") AND order_item_status = 'waiting'" . clientScopeSql('order_item_client_id') . " ORDER BY order_item_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** Take waiting items off the list. How many went. */ +function orderItemsRemove(array $ids) { + global $mysqli; + $removed = 0; + foreach (orderItemsByIds($ids) as $item) { + mysqli_query($mysqli, "DELETE FROM order_items WHERE order_item_id = " . intval($item['order_item_id']) . " AND order_item_status = 'waiting'"); + $removed += mysqli_affected_rows($mysqli); + } + return $removed; +} + +/* + * Products that track stock and are at or under their reorder level, with + * nothing for our stock already waiting or on order - what Add low-stock + * products puts on the list. Each with 'want': its reorder quantity, or + * enough to get back over the level. + */ +function orderItemsLowStock() { + global $mysqli; + if (!poReady()) { + return []; + } + $rows = []; + $sql = mysqli_query($mysqli, "SELECT product_id, product_name, product_cost, product_vendor_id, product_reorder_level, product_reorder_qty, vendor_name, " . productStockSql() . " AS on_hand + FROM products LEFT JOIN vendors ON vendor_id = product_vendor_id AND product_vendor_id > 0 + WHERE " . productReorderSql() . " + AND NOT EXISTS (SELECT 1 FROM order_items WHERE order_item_product_id = product_id AND order_item_client_id = 0 AND order_item_status = 'waiting') + AND NOT EXISTS (SELECT 1 FROM po_items JOIN purchase_orders ON po_id = po_item_po_id + WHERE po_item_product_id = product_id AND po_item_client_id = 0 AND po_status IN ('draft', 'pending', 'approved', 'ordered', 'partial') AND po_item_received < po_item_quantity) + ORDER BY product_name"); + while ($row = mysqli_fetch_assoc($sql)) { + $level = max(0, floatval($row['product_reorder_level'])); + $row['want'] = floatval($row['product_reorder_qty']) > 0 ? round(floatval($row['product_reorder_qty']), 2) : max(1, ceil($level - floatval($row['on_hand']) + 1)); + $rows[] = $row; + } + return $rows; +} + +/** Put the low-stock products on the list. How many went on. */ +function orderItemsAddLowStock() { + $added = 0; + foreach (orderItemsLowStock() as $row) { + if (orderItemSave(['product' => $row['product_id'], 'quantity' => $row['want'], 'source' => 'reorder', + 'note' => 'Low on stock - ' . billingQuantity($row['on_hand']) . ' left, reorder at ' . billingQuantity($row['product_reorder_level'])])) { + $added++; + } + } + return $added; +} + +/* ------------------------------------------------------------- Purchase orders */ + +/** Hold a named lock for the rest of the request (or until poUnlock) - false when someone else has it. */ +function poLock($what) { + global $mysqli; + $lock = escapeSql('itflow_po_' . preg_replace('/[^a-z0-9_]/', '', strtolower((string) $what))); + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 10)"))[0] ?? 0) === 1; +} + +function poUnlock($what) { + global $mysqli; + $lock = escapeSql('itflow_po_' . preg_replace('/[^a-z0-9_]/', '', strtolower((string) $what))); + mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')"); +} + +/** The next PO number - taken, so no two get it. */ +function poNextNumber() { + global $mysqli; + mysqli_query($mysqli, "UPDATE settings SET config_po_next_number = LAST_INSERT_ID(config_po_next_number), config_po_next_number = config_po_next_number + 1 WHERE company_id = 1"); + return intval(mysqli_insert_id($mysqli)); +} + +/** An office's address for Ship to - its name (the company's for the main one) and address, raw. */ +function poOfficeShipTo($office_id) { + $office = office(intval($office_id)) ?? officeMain(); + $company = billingCompany(); + $name = intval($office['office_id']) === 0 ? (string) ($company['company_name'] ?? '') : (string) ($company['company_name'] ?? '') . ' - ' . $office['name']; + return trim($name . "\n" . formatAddress($office['address'], $office['city'], $office['state'], $office['zip'], $office['country'], "\n")); +} + +/** Add lines to a PO from items on the list - the items are marked ordered. How many went on. */ +function poAddOrderItems(array $po, array $items) { + global $mysqli; + $po_id = intval($po['po_id']); + $order = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX(po_item_order), 0) + 1 FROM po_items WHERE po_item_po_id = $po_id"))[0]); + $added = 0; + foreach ($items as $item) { + $description = trim((string) $item['order_item_description']); + $part = trim((string) ($item['product_vendor_part'] ?? '')); + mysqli_query($mysqli, "INSERT INTO po_items SET po_item_po_id = $po_id, po_item_order_item_id = " . intval($item['order_item_id']) . ", + po_item_product_id = " . intval($item['order_item_product_id']) . ", po_item_client_id = " . intval($item['order_item_client_id']) . ", + po_item_name = '" . escapeSql($item['order_item_name']) . "', po_item_description = " . ($description === '' ? 'NULL' : "'" . escapeSql($description) . "'") . ", + po_item_vendor_part = " . ($part === '' ? 'NULL' : "'" . escapeSql($part) . "'") . ", + po_item_quantity = " . round(floatval($item['order_item_quantity']), 2) . ", po_item_cost = " . round(floatval($item['order_item_cost'] ?? 0), 2) . ", po_item_order = " . ($order++)); + mysqli_query($mysqli, "UPDATE order_items SET order_item_status = 'ordered', order_item_vendor_id = " . intval($po['po_vendor_id']) . " WHERE order_item_id = " . intval($item['order_item_id'])); + $added++; + } + return $added; +} + +/* + * A draft PO to $vendor_id, from waiting items ($order_item_ids - none for an + * empty one to add lines to). It ships to the agent's office. Under a lock, + * so two buyers can't put the same items on two POs. The PO's id, or 0 with $error. + */ +function poCreate($vendor_id, array $order_item_ids, &$error = '') { + global $mysqli, $session_user_id, $session_company_currency; + $error = ''; + $vendor_id = intval($vendor_id); + if (!$vendor_id || !isset(poVendors()[$vendor_id])) { + $error = 'Pick who it is from.'; + return 0; + } + if (!poLock('order')) { + $error = 'Someone else is making a purchase order right now - try again.'; + return 0; + } + try { + $items = orderItemsByIds($order_item_ids); + if ($order_item_ids && !$items) { + $error = 'Those items are no longer waiting - someone may have ordered them.'; + return 0; + } + $office_id = officeIdForUser($session_user_id); + $settings = poSettings(); + $po_id = 0; + for ($attempt = 0; $attempt < 5 && !$po_id; $attempt++) { + $number = poNextNumber(); + try { + mysqli_query($mysqli, "INSERT INTO purchase_orders SET po_prefix = '" . escapeSql($settings['prefix']) . "', po_number = $number, po_status = 'draft', + po_vendor_id = $vendor_id, po_currency_code = '" . escapeSql((string) $session_company_currency) . "', + po_ship_to_office_id = $office_id, po_ship_to = '" . escapeSql(poOfficeShipTo($office_id)) . "', po_created_by = " . intval($session_user_id)); + $po_id = intval(mysqli_insert_id($mysqli)); + } catch (mysqli_sql_exception $e) { + // That number is taken (the next number was set back) - take the one after + if ($e->getCode() !== 1062) { + throw $e; + } + } + } + if (!$po_id) { + $error = "A purchase order number couldn't be given - check the next number in Admin > Settings > Purchase orders."; + return 0; + } + $po = poRow($po_id); + $added = poAddOrderItems($po, $items); + poRecalc($po_id); + poLog($po, 'Create', poWho() . ' created ' . poNumber($po) . ' to ' . $po['vendor_name'] . ($added ? " with $added item" . ($added === 1 ? '' : 's') . ' from To Order' : ''), poLogClient($po_id)); + return $po_id; + } finally { + poUnlock('order'); + } +} + +/** Put waiting items on a draft PO. How many went on, with $error when none. */ +function poAddItems(array $po, array $order_item_ids, &$error = '') { + $error = ''; + if ($po['po_status'] !== 'draft') { + $error = poNumber($po) . " isn't a draft any more - items go on a draft."; + return 0; + } + if (!poLock('order')) { + $error = 'Someone else is making a purchase order right now - try again.'; + return 0; + } + try { + $added = poAddOrderItems($po, orderItemsByIds($order_item_ids)); + if (!$added) { + $error = 'Those items are no longer waiting - someone may have ordered them.'; + return 0; + } + poRecalc($po['po_id']); + poLog($po, 'Edit', poWho() . " added $added item" . ($added === 1 ? '' : 's') . ' from To Order', poLogClient($po['po_id'])); + return $added; + } finally { + poUnlock('order'); + } +} + +/* + * A line typed on a draft PO, or one changed ($po_item_id). $in raw: product, + * name, description, vendor_part, quantity, cost, client. The line's id, or 0 with $error. + */ +function poLineSave(array $po, array $in, $po_item_id = 0, &$error = '') { + global $mysqli; + $error = ''; + if ($po['po_status'] !== 'draft') { + $error = 'Only a draft can be changed - send it back to draft first.'; + return 0; + } + $po_id = intval($po['po_id']); + $po_item_id = intval($po_item_id); + $line = $po_item_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM po_items WHERE po_item_id = $po_item_id AND po_item_po_id = $po_id")) : null; + if ($po_item_id && !$line) { + $error = 'That line is no longer on the purchase order.'; + return 0; + } + $product = intval($in['product'] ?? 0) ? productRow(intval($in['product'])) : null; + $name = trim((string) ($in['name'] ?? '')); + if ($name === '' && $product) { + $name = (string) $product['product_name']; + } + if ($name === '') { + $error = 'Say what it is.'; + return 0; + } + $quantity = poNumberIn($in['quantity'] ?? ''); + if ($quantity === null || $quantity <= 0 || $quantity > 9999999) { + $error = 'How many - a number above zero.'; + return 0; + } + $cost_text = trim((string) ($in['cost'] ?? '')); + $cost = $cost_text === '' && $product ? round(floatval($product['product_cost']), 2) : poNumberIn($cost_text); + if ($cost === null || $cost < 0 || $cost > 9999999999) { + $error = 'The unit cost is a number, zero or more.'; + return 0; + } + $client = intval($in['client'] ?? 0); + if ($client && !hasClientAccess($client)) { + $error = "That client isn't one you can order for."; + return 0; + } + $part = trim((string) ($in['vendor_part'] ?? '')); + if ($part === '' && $product && !$line) { + $part = trim((string) $product['product_vendor_part']); + } + $description = trim((string) ($in['description'] ?? '')); + $set = "po_item_name = '" . escapeSql(mb_substr($name, 0, 255)) . "', po_item_description = " . ($description === '' ? 'NULL' : "'" . escapeSql($description) . "'") . ", + po_item_vendor_part = " . ($part === '' ? 'NULL' : "'" . escapeSql(mb_substr($part, 0, 200)) . "'") . ", po_item_quantity = $quantity, po_item_cost = $cost, + po_item_product_id = " . ($product ? intval($product['product_id']) : 0) . ", po_item_client_id = $client"; + if ($line) { + mysqli_query($mysqli, "UPDATE po_items SET $set WHERE po_item_id = $po_item_id"); + // The item on the list follows the line it became + if (intval($line['po_item_order_item_id'])) { + mysqli_query($mysqli, "UPDATE order_items SET order_item_quantity = $quantity, order_item_cost = $cost, order_item_client_id = $client WHERE order_item_id = " . intval($line['po_item_order_item_id'])); + } + poRecalc($po_id); + poLog($po, 'Edit', poWho() . " changed $name on " . poNumber($po), poLogClient($po_id)); + return $po_item_id; + } + $order = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX(po_item_order), 0) + 1 FROM po_items WHERE po_item_po_id = $po_id"))[0]); + mysqli_query($mysqli, "INSERT INTO po_items SET $set, po_item_po_id = $po_id, po_item_order = $order"); + $po_item_id = intval(mysqli_insert_id($mysqli)); + poRecalc($po_id); + poLog($po, 'Edit', poWho() . ' added ' . billingQuantity($quantity) . " x $name to " . poNumber($po), poLogClient($po_id)); + return $po_item_id; +} + +/** Take a line off a draft PO - an item from the list goes back on it. */ +function poLineRemove(array $po, $po_item_id, &$error = '') { + global $mysqli; + $error = ''; + if ($po['po_status'] !== 'draft') { + $error = 'Only a draft can be changed - send it back to draft first.'; + return false; + } + $line = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM po_items WHERE po_item_id = " . intval($po_item_id) . " AND po_item_po_id = " . intval($po['po_id']))); + if (!$line) { + $error = 'That line is no longer on the purchase order.'; + return false; + } + if (intval($line['po_item_order_item_id'])) { + mysqli_query($mysqli, "UPDATE order_items SET order_item_status = 'waiting' WHERE order_item_id = " . intval($line['po_item_order_item_id'])); + } + mysqli_query($mysqli, "DELETE FROM po_items WHERE po_item_id = " . intval($line['po_item_id'])); + poRecalc($po['po_id']); + poLog($po, 'Edit', poWho() . ' took ' . $line['po_item_name'] . ' off ' . poNumber($po) . (intval($line['po_item_order_item_id']) ? ' - it is back on To Order' : ''), poLogClient($po['po_id'])); + return true; +} + +/* + * Who it is from, where it ships, shipping and the note. $in raw: vendor (a + * draft's only), ship_to (an office id, or 'other' with ship_to_address), + * shipping, note. True, or false with $error. + */ +function poDetailsSave(array $po, array $in, &$error = '') { + global $mysqli; + $error = ''; + if (in_array($po['po_status'], ['received', 'cancelled'], true)) { + $error = poNumber($po) . ' is ' . strtolower(PO_STATUSES[$po['po_status']]['label']) . ' - it can no longer be changed.'; + return false; + } + $set = []; + if ($po['po_status'] === 'draft' && isset($in['vendor'])) { + $vendor = intval($in['vendor']); + if (!isset(poVendors($po['po_vendor_id'])[$vendor])) { + $error = 'Pick who it is from.'; + return false; + } + $set[] = "po_vendor_id = $vendor"; + mysqli_query($mysqli, "UPDATE order_items JOIN po_items ON po_item_order_item_id = order_item_id SET order_item_vendor_id = $vendor WHERE po_item_po_id = " . intval($po['po_id'])); + } + if (isset($in['ship_to'])) { + if ((string) $in['ship_to'] === 'other') { + $address = trim(preg_replace("/\r\n?/", "\n", (string) ($in['ship_to_address'] ?? ''))); + if ($address === '') { + $error = 'Type the address it ships to.'; + return false; + } + $set[] = "po_ship_to_office_id = NULL, po_ship_to = '" . escapeSql(mb_substr($address, 0, 1000)) . "'"; + } else { + $office_id = officeIdFrom($in['ship_to']); + $set[] = "po_ship_to_office_id = $office_id, po_ship_to = '" . escapeSql(poOfficeShipTo($office_id)) . "'"; + } + } + if (isset($in['shipping'])) { + $shipping = trim((string) $in['shipping']) === '' ? 0.0 : poNumberIn($in['shipping']); + if ($shipping === null || $shipping < 0 || $shipping > 9999999999) { + $error = 'Shipping is an amount, zero or more.'; + return false; + } + $set[] = "po_shipping = $shipping"; + } + if (isset($in['note'])) { + $note = trim((string) $in['note']); + $set[] = 'po_note = ' . ($note === '' ? 'NULL' : "'" . escapeSql(mb_substr($note, 0, 2000)) . "'"); + } + if ($set) { + mysqli_query($mysqli, "UPDATE purchase_orders SET " . implode(', ', $set) . " WHERE po_id = " . intval($po['po_id'])); + poRecalc($po['po_id']); + poLog($po, 'Edit', poWho() . ' changed the details of ' . poNumber($po), poLogClient($po['po_id'])); + } + return true; +} + +/* + * Its total from its lines and shipping - and once ordered, its status from + * what has come in. A line all in marks its item on the list received. + */ +function poRecalc($po_id) { + global $mysqli; + $po_id = intval($po_id); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COALESCE(SUM(ROUND(po_item_quantity * po_item_cost, 2)), 0) AS lines_total, COALESCE(SUM(po_item_quantity), 0) AS qty, + COALESCE(SUM(LEAST(po_item_received, po_item_quantity)), 0) AS received FROM po_items WHERE po_item_po_id = $po_id")); + mysqli_query($mysqli, "UPDATE purchase_orders SET po_total = ROUND(" . floatval($row['lines_total']) . " + po_shipping, 2) WHERE po_id = $po_id"); + $status = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT po_status FROM purchase_orders WHERE po_id = $po_id"))[0] ?? ''); + if (in_array($status, ['ordered', 'partial', 'received'], true)) { + $now = floatval($row['received']) <= 0 ? 'ordered' : (floatval($row['received']) + 0.001 >= floatval($row['qty']) ? 'received' : 'partial'); + if ($now !== $status) { + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = '$now', po_received_at = " . ($now === 'received' ? 'NOW()' : 'NULL') . " WHERE po_id = $po_id"); + } + mysqli_query($mysqli, "UPDATE order_items JOIN po_items ON po_item_order_item_id = order_item_id + SET order_item_status = IF(po_item_received + 0.001 >= po_item_quantity, 'received', 'ordered') + WHERE po_item_po_id = $po_id AND order_item_status IN ('ordered', 'received')"); + } +} + +/* ------------------------------------------------------------- Approval */ + +/** Does this PO need approving before it is ordered? Over the amount, or a line without a cost (it would look free). */ +function poNeedsApproval(array $po) { + global $mysqli; + $settings = poSettings(); + if (!$settings['approval']) { + return false; + } + if ($settings['approval_over'] <= 0 || floatval($po['po_total']) > $settings['approval_over']) { + return true; + } + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM po_items WHERE po_item_po_id = " . intval($po['po_id']) . " AND po_item_cost <= 0"))[0]) > 0; +} + +/* + * The agents who can approve this PO - user_id => [user_name, user_email]: + * admins and roles with Full Procurement access, active, who can see every + * client on it. + */ +function poApprovers(array $po) { + global $mysqli; + $clients = array_keys(poClients($po['po_id'])); + $approvers = []; + $sql = mysqli_query($mysqli, "SELECT users.user_id, user_name, user_email FROM users + JOIN user_roles ON role_id = user_role_id + LEFT JOIN user_role_permissions ON user_role_permissions.user_role_id = role_id + AND module_id = (SELECT module_id FROM modules WHERE module_name = 'module_procurement' LIMIT 1) + WHERE user_type = 1" . serviceAccountsOutSql('users.user_service_account') . " AND user_status = 1 AND user_archived_at IS NULL + AND (role_is_admin = 1 OR user_role_permission_level >= 3) + GROUP BY users.user_id, user_name, user_email, role_is_admin"); + while ($row = mysqli_fetch_assoc($sql)) { + $user_id = intval($row['user_id']); + foreach ($clients as $client_id) { + if (!agentCanSeeClient($user_id, $client_id)) { + continue 2; + } + } + $approvers[$user_id] = $row; + } + return $approvers; +} + +/** Can that agent reach that client - their role's admin flag, then their allow and deny lists. */ +function agentCanSeeClient($user_id, $client_id) { + global $mysqli; + $user_id = intval($user_id); + $client_id = intval($client_id); + $admin = mysqli_fetch_row(mysqli_query($mysqli, "SELECT role_is_admin FROM users JOIN user_roles ON role_id = user_role_id WHERE user_id = $user_id")); + if ($admin && intval($admin[0]) === 1) { + return true; + } + $rules = mysqli_fetch_all(mysqli_query($mysqli, "SELECT client_id, permission_type FROM user_client_permissions WHERE user_id = $user_id"), MYSQLI_ASSOC); + if (!$rules) { + return true; + } + $allow = []; + foreach ($rules as $rule) { + if (intval($rule['client_id']) === $client_id && $rule['permission_type'] === 'deny') { + return false; + } + if ($rule['permission_type'] !== 'deny') { + $allow[] = intval($rule['client_id']); + } + } + return !$allow || in_array($client_id, $allow, true); +} + +/* + * May the signed-in agent approve this PO? Full Procurement access, and not + * their own - unless they are an admin, or nobody else can, so a PO is never + * stuck. + */ +function poMayApprove(array $po) { + global $session_user_id, $session_is_admin; + if (poLevel() < 3 || $po['po_status'] !== 'pending') { + return false; + } + if (!empty($session_is_admin) || intval($po['po_created_by']) !== intval($session_user_id)) { + return true; + } + return !array_diff(array_keys(poApprovers($po)), [intval($session_user_id)]); +} + +/** Tell an agent - a notice in their bell, and an email when $email. */ +function poTell($user_id, array $po, $text, $email = false, $subject = '') { + global $mysqli, $config_base_url; + $user_id = intval($user_id); + if (!$user_id) { + return; + } + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Purchase Order', notification = '" . escapeSql(mb_substr($text, 0, 1000)) . "', + notification_action = '/agent/purchase_order.php?po_id=" . intval($po['po_id']) . "', notification_user_id = $user_id, notification_entity_id = " . intval($po['po_id'])); + if (!$email) { + return; + } + $user = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE user_id = $user_id")); + if (!$user || !filter_var($user['user_email'], FILTER_VALIDATE_EMAIL)) { + return; + } + emailQueue([['email' => $user['user_email'], 'name' => $user['user_name'], 'footnote' => 'You get this because you can approve purchase orders in ITFlow.']], $subject ?: $text, [ + 'kind' => 'Purchase order', 'tone' => 'warning', 'preview' => $text, + 'title' => poNumber($po) . ' needs your approval', + 'intro' => [$text . '.'], + 'summary' => ['Purchase order' => poNumber($po), 'Vendor' => (string) $po['vendor_name'], 'Total' => poMoney($po['po_total'], $po['po_currency_code']), 'From' => poWho()], + 'button' => ['label' => 'Open ' . poNumber($po), 'url' => 'https://' . rtrim((string) $config_base_url, '/') . '/agent/purchase_order.php?po_id=' . intval($po['po_id'])], + ]); +} + +/** Send a draft for approval - its approvers are told. */ +function poSendForApproval(array $po, &$error = '') { + global $mysqli, $session_user_id; + $error = ''; + if ($po['po_status'] !== 'draft' || !poItemsCount($po['po_id'])) { + $error = $po['po_status'] !== 'draft' ? poNumber($po) . " isn't a draft." : 'Put something on it first.'; + return false; + } + $po_id = intval($po['po_id']); + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'pending', po_submitted_at = NOW(), po_approved_by = 0, po_approved_at = NULL, po_approval_note = NULL WHERE po_id = $po_id"); + $po = poRow($po_id); + poLog($po, 'Edit', poWho() . ' sent ' . poNumber($po) . ' for approval (' . poMoney($po['po_total'], $po['po_currency_code']) . ')', poLogClient($po_id)); + $text = poNumber($po) . ' (' . $po['vendor_name'] . ', ' . poMoney($po['po_total'], $po['po_currency_code']) . ') is waiting for your approval - from ' . poWho(); + foreach (array_keys(poApprovers($po)) as $user_id) { + if ($user_id !== intval($session_user_id)) { + poTell($user_id, $po, $text, true, poNumber($po) . ' needs your approval'); + } + } + return true; +} + +/** How many lines a PO has. */ +function poItemsCount($po_id) { + global $mysqli; + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM po_items WHERE po_item_po_id = " . intval($po_id)))[0]); +} + +/** An approver's answer - approved, or back to draft with why. Whoever made it is told. */ +function poDecide(array $po, $approve, $note, &$error = '') { + global $mysqli, $session_user_id; + $error = ''; + if (!poMayApprove($po)) { + $error = $po['po_status'] !== 'pending' ? poNumber($po) . " isn't waiting for approval." : "You can't approve this one - it needs someone with full Procurement access, other than whoever made it."; + return false; + } + $po_id = intval($po['po_id']); + $note = mb_substr(trim((string) $note), 0, 255); + $note_sql = $note === '' ? 'NULL' : "'" . escapeSql($note) . "'"; + if ($approve) { + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'approved', po_approved_by = " . intval($session_user_id) . ", po_approved_at = NOW(), po_approval_note = $note_sql WHERE po_id = $po_id"); + $own = intval($po['po_created_by']) === intval($session_user_id); + poLog($po, 'Edit', poWho() . ($own ? ' approved their own ' : ' approved ') . poNumber($po) . ($note !== '' ? " - $note" : ''), poLogClient($po_id)); + } else { + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'draft', po_approved_by = 0, po_approved_at = NULL, po_approval_note = $note_sql WHERE po_id = $po_id"); + poLog($po, 'Edit', poWho() . ' sent ' . poNumber($po) . ' back to draft' . ($note !== '' ? " - $note" : ''), poLogClient($po_id)); + } + if (intval($po['po_created_by']) !== intval($session_user_id)) { + poTell($po['po_created_by'], $po, poNumber($po) . ($approve ? ' was approved' : ' was sent back to draft') . ' by ' . poWho() . ($note !== '' ? ": $note" : '')); + } + return true; +} + +/** Back to draft, to change it - an approved PO needs approving again. */ +function poBackToDraft(array $po, &$error = '') { + global $mysqli; + $error = ''; + if (!in_array($po['po_status'], ['pending', 'approved'], true)) { + $error = poNumber($po) . " can't go back to draft now."; + return false; + } + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'draft', po_approved_by = 0, po_approved_at = NULL WHERE po_id = " . intval($po['po_id'])); + poLog($po, 'Edit', poWho() . ' took ' . poNumber($po) . ' back to draft to change it', poLogClient($po['po_id'])); + return true; +} + +/** Can it be marked ordered (or emailed as the order) now - approved, or a draft that needs no approval? */ +function poCanOrder(array $po) { + return $po['po_status'] === 'approved' || ($po['po_status'] === 'draft' && poItemsCount($po['po_id']) && !poNeedsApproval($po)); +} + +/** Mark it ordered with the vendor - on $date, with their order number if they gave one. */ +function poMarkOrdered(array $po, $date, $vendor_reference, &$error = '') { + global $mysqli, $session_user_id; + $error = ''; + if (!poCanOrder($po)) { + $error = $po['po_status'] === 'draft' ? poNumber($po) . ' needs approving before it is ordered.' : poNumber($po) . ' is ' . strtolower(PO_STATUSES[$po['po_status']]['label'] ?? $po['po_status']) . '.'; + return false; + } + $po_id = intval($po['po_id']); + $date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $date) && strtotime($date) ? $date : date('Y-m-d'); + $reference = mb_substr(trim((string) $vendor_reference), 0, 200); + // A draft that needed no approval is approved as it is ordered + $approved = $po['po_status'] === 'draft' ? ", po_approved_by = " . intval($session_user_id) . ", po_approved_at = NOW(), po_approval_note = '" . escapeSql(poSettings()['approval'] ? 'Under the approval amount' : 'Approval is off') . "'" : ''; + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'ordered', po_order_date = '$date', po_ordered_by = " . intval($session_user_id) . ", po_ordered_at = NOW()$approved" + . ($reference !== '' ? ", po_vendor_reference = '" . escapeSql($reference) . "'" : '') . " WHERE po_id = $po_id"); + poRecalc($po_id); + poLog($po, 'Edit', poWho() . ' marked ' . poNumber($po) . " ordered on $date" . ($reference !== '' ? " - their order $reference" : ''), poLogClient($po_id)); + return true; +} + +/** Cancel it - nothing has come in. Its items go back on the list. */ +function poCancel(array $po, &$error = '') { + global $mysqli; + $error = ''; + $po_id = intval($po['po_id']); + if (!in_array($po['po_status'], ['draft', 'pending', 'approved', 'ordered'], true) + || floatval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(po_item_received), 0) FROM po_items WHERE po_item_po_id = $po_id"))[0]) > 0) { + $error = 'Something on ' . poNumber($po) . ' has come in, so it can\'t be cancelled - undo the receipts first.'; + return false; + } + mysqli_query($mysqli, "UPDATE order_items JOIN po_items ON po_item_order_item_id = order_item_id SET order_item_status = 'waiting' WHERE po_item_po_id = $po_id"); + mysqli_query($mysqli, "UPDATE purchase_orders SET po_status = 'cancelled', po_cancelled_at = NOW() WHERE po_id = $po_id"); + poLog($po, 'Edit', poWho() . ' cancelled ' . poNumber($po) . ' - its items are back on To Order', poLogClient($po_id)); + return true; +} + +/* ------------------------------------------------------------- Receiving */ + +/** Lines still to come in on ordered POs the agent can see - by po_id, each line with its PO. $po_id for one PO. */ +function poAwaitingLines($po_id = 0) { + global $mysqli; + $po_id = intval($po_id); + $by_po = []; + if (!poReady()) { + return $by_po; + } + $sql = mysqli_query($mysqli, "SELECT po_items.*, po_prefix, po_number, po_status, po_order_date, po_vendor_reference, po_currency_code, vendor_name, client_name, + product_name, product_track_stock, product_asset_type + FROM po_items + JOIN purchase_orders ON po_id = po_item_po_id + LEFT JOIN vendors ON vendors.vendor_id = po_vendor_id + LEFT JOIN clients ON client_id = po_item_client_id AND po_item_client_id > 0 + LEFT JOIN products ON product_id = po_item_product_id AND po_item_product_id > 0 + WHERE po_status IN ('ordered', 'partial') AND po_item_received < po_item_quantity" . ($po_id ? " AND po_id = $po_id" : '') . poScopeSql('po_id') . " + ORDER BY po_order_date ASC, po_id ASC, po_item_order ASC, po_item_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $by_po[intval($row['po_item_po_id'])][] = $row; + } + return $by_po; +} + +/** The asset type a line's units become - its product's, else a guess from its name ('' when it is not hardware). */ +function poAssetTypeFor(array $line) { + $type = productAssetType($line['product_asset_type'] ?? ''); + if ($type !== '') { + return $type; + } + $name = mb_strtolower((string) $line['po_item_name']); + $guesses = [ + 'Laptop' => ['laptop', 'notebook', 'latitude', 'thinkpad', 'macbook', 'elitebook', 'probook'], + 'Desktop' => ['desktop', 'optiplex', 'thinkcentre', 'imac', 'mini pc'], + 'Server' => ['server', 'poweredge', 'proliant', 'nas', 'synology', 'qnap'], + 'Monitor' => ['monitor', 'display'], + 'Switch' => ['switch'], + 'Firewall/Router' => ['firewall', 'router', 'fortigate', 'sonicwall'], + 'Access Point' => ['access point', 'wap'], + 'Printer' => ['printer', 'copier', 'mfp', 'laserjet'], + 'Mobile Phone' => ['iphone', 'galaxy', 'pixel', 'smartphone'], + 'Tablet' => ['ipad', 'tablet'], + 'Phone' => ['yealink', 'polycom', 'handset', 'desk phone'], + 'Camera' => ['camera', 'nvr'], + ]; + foreach ($guesses as $guess => $words) { + foreach ($words as $word) { + if (preg_match('/(? ['qty', 'serials', 'asset_type' + * ('' - don't add them to the client's assets)]. Each line on an ordered PO + * the agent can see takes up to what is left. Our own stock of a product that + * tracks it goes on the shelf (Sales edit); a client's line becomes their + * assets, a unit each, when its type is picked (Support edit). Returns + * ['lines', 'pos', 'stock', 'assets', 'skipped' => what wasn't done and why]. + */ +function poReceive(array $in) { + global $mysqli, $session_user_id, $session_name; + $done = ['lines' => 0, 'pos' => [], 'stock' => 0, 'assets' => 0, 'skipped' => []]; + $can_stock = lookupUserPermission('module_sales') >= 2; + $can_assets = lookupUserPermission('module_support') >= 2; + foreach ($in as $po_item_id => $received) { + $qty = poNumberIn(is_array($received) ? ($received['qty'] ?? '') : ''); + if ($qty === null || $qty <= 0) { + continue; + } + $line = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT po_items.*, po_prefix, po_number, po_status, po_vendor_id, po_order_date, + product_track_stock, product_asset_type, product_make, product_model, product_warranty_months + FROM po_items JOIN purchase_orders ON po_id = po_item_po_id + LEFT JOIN products ON product_id = po_item_product_id AND po_item_product_id > 0 + WHERE po_item_id = " . intval($po_item_id))); + if (!$line || !in_array($line['po_status'], ['ordered', 'partial'], true) || !poAccessible($line['po_item_po_id'])) { + continue; + } + $qty = min($qty, poItemLeft($line)); + if ($qty <= 0) { + continue; + } + $po = ['po_id' => $line['po_item_po_id'], 'po_prefix' => $line['po_prefix'], 'po_number' => $line['po_number']]; + $number = poNumber($po); + $client_id = intval($line['po_item_client_id']); + $serials = poSerials($received['serials'] ?? ''); + $stock_id = 0; + $asset_ids = []; + + mysqli_begin_transaction($mysqli); + try { + // Our own stock goes on the shelf + if (!$client_id && intval($line['po_item_product_id']) && intval($line['product_track_stock'])) { + if ($can_stock) { + $stock_id = productStockMove(intval($line['po_item_product_id']), $qty, 'received', ['unit_cost' => $line['po_item_cost'], 'note' => "Received on $number"]); + $done['stock'] += $qty; + } else { + $done['skipped'][] = $line['po_item_name'] . ' was received, but not put on the shelf - that needs Sales edit access'; + } + } + + // A client's hardware becomes their assets, one a unit, each with its serial + $type = productAssetType($received['asset_type'] ?? ''); + if ($client_id && $type !== '') { + if (!$can_assets) { + $done['skipped'][] = $line['po_item_name'] . ' was received, but not added to assets - that needs Support edit access'; + } elseif (floor($qty) != $qty) { + $done['skipped'][] = $line['po_item_name'] . ' came in as part of a unit, so no asset was made'; + } else { + $units = min(PO_ASSETS_MAX, intval($qty)); + if (intval($qty) > PO_ASSETS_MAX) { + $done['skipped'][] = 'Only the first ' . PO_ASSETS_MAX . ' of ' . $line['po_item_name'] . ' became assets - add the rest by hand'; + } + $status = mysqli_fetch_row(mysqli_query($mysqli, "SELECT category_name FROM categories WHERE category_type = 'asset_status' AND category_archived_at IS NULL ORDER BY category_order ASC, category_id ASC LIMIT 1")); + $status = escapeSql((string) ($status[0] ?? '')); + $date = $line['po_order_date'] ?: date('Y-m-d'); + $warranty = productWarrantyUntil(date('Y-m-d'), intval($line['product_warranty_months'])); + $make = escapeSql(mb_substr((string) ($line['product_make'] ?? ''), 0, 200)); + $model = trim((string) ($line['product_model'] ?? '')) !== '' ? "'" . escapeSql(mb_substr($line['product_model'], 0, 200)) . "'" : 'NULL'; + $by = poWho(); + for ($i = 0; $i < $units; $i++) { + $name = mb_substr($line['po_item_name'], 0, 190) . ($units > 1 ? ' #' . ($i + 1) : ''); + $serial = $serials[$i] ?? ''; + mysqli_query($mysqli, "INSERT INTO assets SET asset_type = '" . escapeSql($type) . "', asset_name = '" . escapeSql($name) . "', asset_make = '$make', asset_model = $model, + asset_serial = " . ($serial === '' ? 'NULL' : "'" . escapeSql($serial) . "'") . ", asset_status = '$status', + asset_purchase_reference = '" . escapeSql($number) . "', asset_purchase_date = '" . escapeSql($date) . "', + asset_warranty_expire = " . ($warranty ? "'$warranty'" : 'NULL') . ", asset_vendor_id = " . intval($line['po_vendor_id']) . ", + asset_product_id = " . intval($line['po_item_product_id']) . ", asset_client_id = $client_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"); + mysqli_query($mysqli, "INSERT INTO asset_history SET asset_history_status = '$status', asset_history_description = '" . escapeSql(mb_substr("$by created $name, received on $number", 0, 255)) . "', asset_history_asset_id = $asset_id"); + logAudit('Asset', 'Create', escapeSql("$by created asset $name, received on $number"), $client_id, $asset_id); + $asset_ids[] = $asset_id; + } + $done['assets'] += count($asset_ids); + } + } + + mysqli_query($mysqli, "INSERT INTO po_receipts SET po_receipt_po_id = " . intval($line['po_item_po_id']) . ", po_receipt_item_id = " . intval($line['po_item_id']) . ", + po_receipt_quantity = $qty, po_receipt_serials = " . ($serials ? "'" . escapeSql(implode("\n", $serials)) . "'" : 'NULL') . ", + po_receipt_asset_ids = " . ($asset_ids ? "'" . implode(',', $asset_ids) . "'" : 'NULL') . ", po_receipt_stock_id = " . intval($stock_id) . ", po_receipt_by = " . intval($session_user_id)); + mysqli_query($mysqli, "UPDATE po_items SET po_item_received = po_item_received + $qty WHERE po_item_id = " . intval($line['po_item_id'])); + mysqli_commit($mysqli); + } catch (Throwable $e) { + mysqli_rollback($mysqli); + throw $e; + } + + poLog($po, 'Edit', poWho() . ' received ' . billingQuantity($qty) . ' x ' . $line['po_item_name'] . " on $number" + . ($serials ? ' - serials ' . implode(', ', $serials) : '') . ($stock_id ? ' - on the shelf' : '') . ($asset_ids ? ' - ' . count($asset_ids) . ' asset' . (count($asset_ids) === 1 ? '' : 's') . ' made' : ''), $client_id); + $done['lines']++; + $done['pos'][intval($line['po_item_po_id'])] = $number; + } + foreach (array_keys($done['pos']) as $po_id) { + poRecalc($po_id); + } + return $done; +} + +/** A PO's receipts, newest first, with the line and who took it in. */ +function poReceipts($po_id) { + global $mysqli; + $rows = []; + $sql = mysqli_query($mysqli, "SELECT po_receipts.*, po_item_name, po_item_client_id, user_name FROM po_receipts + JOIN po_items ON po_item_id = po_receipt_item_id + LEFT JOIN users ON user_id = po_receipt_by AND po_receipt_by > 0 + WHERE po_receipt_po_id = " . intval($po_id) . " ORDER BY po_receipt_id DESC"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/* + * Take a receipt back - received by mistake. The line is waiting for it + * again, the stock it put on the shelf comes off, and the assets it made are + * deleted (Full Support access, as deleting an asset needs). True, or false with $error. + */ +function poUndoReceipt($po_receipt_id, &$error = '') { + global $mysqli; + $error = ''; + $receipt = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT po_receipts.*, po_item_name, po_item_product_id, po_item_cost, po_item_client_id, po_prefix, po_number, po_status + FROM po_receipts JOIN po_items ON po_item_id = po_receipt_item_id JOIN purchase_orders ON po_id = po_receipt_po_id + WHERE po_receipt_id = " . intval($po_receipt_id))); + if (!$receipt || !poAccessible($receipt['po_receipt_po_id'])) { + $error = 'That receipt no longer exists.'; + return false; + } + if (!in_array($receipt['po_status'], ['ordered', 'partial', 'received'], true)) { + $error = 'Its purchase order is ' . strtolower(PO_STATUSES[$receipt['po_status']]['label'] ?? $receipt['po_status']) . '.'; + return false; + } + $po = ['po_id' => $receipt['po_receipt_po_id'], 'po_prefix' => $receipt['po_prefix'], 'po_number' => $receipt['po_number']]; + $number = poNumber($po); + $qty = floatval($receipt['po_receipt_quantity']); + $asset_ids = array_values(array_filter(array_map('intval', explode(',', (string) $receipt['po_receipt_asset_ids'])))); + if ($asset_ids) { + $asset_ids = array_map('intval', array_column(mysqli_fetch_all(mysqli_query($mysqli, "SELECT asset_id FROM assets WHERE asset_id IN (" . implode(',', $asset_ids) . ")"), MYSQLI_NUM), 0)); + } + if ($asset_ids && lookupUserPermission('module_support') < 3) { + $error = 'Undoing it deletes the ' . count($asset_ids) . ' asset' . (count($asset_ids) === 1 ? '' : 's') . ' it made - that needs full Support access.'; + return false; + } + if (intval($receipt['po_receipt_stock_id']) && lookupUserPermission('module_sales') < 2) { + $error = 'Undoing it takes stock off the shelf - that needs Sales edit access.'; + return false; + } + $also = []; + mysqli_begin_transaction($mysqli); + try { + foreach ($asset_ids as $asset_id) { + mysqli_query($mysqli, "DELETE FROM assets WHERE asset_id = $asset_id"); + mysqli_query($mysqli, "DELETE FROM rack_units WHERE unit_asset_id = $asset_id"); + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE asset_id = $asset_id"); + credentialsForget('asset', $asset_id); + logAudit('Asset', 'Delete', escapeSql(poWho() . " deleted asset $asset_id - its receipt on $number was undone"), intval($receipt['po_item_client_id']), $asset_id); + } + if ($asset_ids) { + $also[] = count($asset_ids) . ' asset' . (count($asset_ids) === 1 ? '' : 's') . ' deleted'; + } + if (intval($receipt['po_receipt_stock_id']) && intval($receipt['po_item_product_id'])) { + productStockMove(intval($receipt['po_item_product_id']), -$qty, 'received', ['unit_cost' => $receipt['po_item_cost'], 'note' => "Receipt on $number undone"]); + $also[] = billingQuantity($qty) . ' taken off the shelf'; + } + mysqli_query($mysqli, "UPDATE po_items SET po_item_received = GREATEST(0, po_item_received - $qty) WHERE po_item_id = " . intval($receipt['po_receipt_item_id'])); + mysqli_query($mysqli, "DELETE FROM po_receipts WHERE po_receipt_id = " . intval($receipt['po_receipt_id'])); + mysqli_commit($mysqli); + } catch (Throwable $e) { + mysqli_rollback($mysqli); + $error = 'Not undone - ' . $e->getMessage(); + return false; + } + poRecalc($receipt['po_receipt_po_id']); + poLog($po, 'Edit', poWho() . ' undid the receipt of ' . billingQuantity($qty) . ' x ' . $receipt['po_item_name'] . " on $number" . ($also ? ' (' . implode(', ', $also) . ')' : ''), intval($receipt['po_item_client_id'])); + return true; +} + +/* ------------------------------------------------------------- Tracking */ + +/** A PO's tracking numbers, newest first. */ +function poTracking($po_id) { + global $mysqli; + return mysqli_fetch_all(mysqli_query($mysqli, "SELECT * FROM po_tracking WHERE po_tracking_po_id = " . intval($po_id) . " ORDER BY po_tracking_id DESC"), MYSQLI_ASSOC); +} + +/** The tracking of several POs - po_id => rows. */ +function poTrackingFor(array $po_ids) { + global $mysqli; + $po_ids = array_values(array_filter(array_map('intval', $po_ids))); + $by_po = []; + if ($po_ids) { + $sql = mysqli_query($mysqli, "SELECT * FROM po_tracking WHERE po_tracking_po_id IN (" . implode(',', $po_ids) . ") ORDER BY po_tracking_id DESC"); + while ($row = mysqli_fetch_assoc($sql)) { + $by_po[intval($row['po_tracking_po_id'])][] = $row; + } + } + return $by_po; +} + +/** A tracking number as a link to its carrier's page (or the number), escaped. */ +function poTrackingHtml(array $row) { + $label = (PO_CARRIERS[$row['po_tracking_carrier']][0] ?? 'Tracking') . ' ' . $row['po_tracking_number']; + $url = poTrackingUrl($row['po_tracking_carrier'], $row['po_tracking_number']); + $eta = $row['po_tracking_eta'] ? ' - due ' . escapeHtml(date('M j', strtotime($row['po_tracking_eta']))) . '' : ''; + return ($url !== '' ? '' . escapeHtml($label) . ' ' : escapeHtml($label)) . $eta; +} + +/** Add a tracking number. True, or false with $error. */ +function poTrackingAdd(array $po, $carrier, $number, $eta, &$error = '') { + global $mysqli; + $error = ''; + $carrier = isset(PO_CARRIERS[$carrier]) ? $carrier : 'other'; + $number = mb_substr(trim((string) $number), 0, 100); + if ($number === '') { + $error = 'Type the tracking number.'; + return false; + } + if (!in_array($po['po_status'], ['ordered', 'partial', 'received'], true)) { + $error = 'Tracking goes on a purchase order once it is ordered.'; + return false; + } + $eta = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $eta) && strtotime($eta) ? "'$eta'" : 'NULL'; + mysqli_query($mysqli, "INSERT INTO po_tracking SET po_tracking_po_id = " . intval($po['po_id']) . ", po_tracking_carrier = '$carrier', po_tracking_number = '" . escapeSql($number) . "', po_tracking_eta = $eta"); + poLog($po, 'Edit', poWho() . ' added ' . PO_CARRIERS[$carrier][0] . " tracking $number to " . poNumber($po), poLogClient($po['po_id'])); + return true; +} + +/** Take a tracking number off. */ +function poTrackingRemove(array $po, $po_tracking_id) { + global $mysqli; + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM po_tracking WHERE po_tracking_id = " . intval($po_tracking_id) . " AND po_tracking_po_id = " . intval($po['po_id']))); + if (!$row) { + return false; + } + mysqli_query($mysqli, "DELETE FROM po_tracking WHERE po_tracking_id = " . intval($row['po_tracking_id'])); + poLog($po, 'Edit', poWho() . ' took tracking ' . $row['po_tracking_number'] . ' off ' . poNumber($po), poLogClient($po['po_id'])); + return true; +} + +/* ------------------------------------------------------------- The vendor's bill */ + +/** The expense its vendor bill was recorded as, or null. */ +function poExpense(array $po) { + global $mysqli; + if (!intval($po['po_expense_id'])) { + return null; + } + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT expense_id, expense_amount, expense_currency_code, expense_date, expense_reference, expense_archived_at + FROM expenses WHERE expense_id = " . intval($po['po_expense_id']))) ?: null; +} + +/* + * Record the vendor's bill as an expense - through the expense rules, so its + * account, category and currency are checked as anywhere. $in raw: date, + * amount, account, category, reference (their invoice number), description. + * One client on the PO makes it theirs. The stock this PO put on the shelf + * is noted as bought on it. The expense id, or 0 with $error. + */ +function poRecordBill(array $po, array $in, &$error = '') { + global $mysqli; + $error = ''; + if (!poLock('bill_' . intval($po['po_id']))) { + $error = 'Someone else is recording this bill right now - try again.'; + return 0; + } + try { + $po = poRow($po['po_id']) ?: $po; + if (poExpense($po)) { + $error = 'Its vendor bill is recorded already.'; + return 0; + } + if (in_array($po['po_status'], ['draft', 'pending', 'cancelled'], true)) { + $error = 'The vendor bill is recorded once it is ordered.'; + return 0; + } + $number = poNumber($po); + $reference = trim((string) ($in['reference'] ?? '')); + $expense_id = expenseSave([ + 'date' => (string) ($in['date'] ?? ''), 'amount' => (string) ($in['amount'] ?? ''), 'vendor' => intval($po['po_vendor_id']), + 'category' => intval($in['category'] ?? 0), 'account' => (string) ($in['account'] ?? ''), 'payment_method' => (string) ($in['payment_method'] ?? ''), + 'client_id' => poLogClient($po['po_id']), 'reference' => $reference !== '' ? $reference : $number, + 'description' => trim((string) ($in['description'] ?? '')) !== '' ? trim((string) $in['description']) : "$number - " . $po['vendor_name'], + ], 0, $error); + if (!$expense_id) { + return 0; + } + mysqli_query($mysqli, "UPDATE purchase_orders SET po_expense_id = $expense_id WHERE po_id = " . intval($po['po_id'])); + // What this PO put on the shelf was bought on this bill + mysqli_query($mysqli, "UPDATE product_stock JOIN po_receipts ON po_receipt_stock_id = stock_id SET stock_expense_id = $expense_id + WHERE po_receipt_po_id = " . intval($po['po_id']) . " AND stock_expense_id IS NULL"); + poLog($po, 'Edit', poWho() . " recorded the vendor bill for $number as an expense" . ($reference !== '' ? " - their invoice $reference" : ''), poLogClient($po['po_id'])); + logAudit('Expense', 'Create', escapeSql(poWho() . " recorded the vendor bill for $number"), poLogClient($po['po_id']), $expense_id); + return $expense_id; + } finally { + poUnlock('bill_' . intval($po['po_id'])); + } +} + +/* ------------------------------------------------------------- The PDF, and emailing it */ + +/** The PO as a PDF, in the look of the invoices - ['name', 'data']. */ +function poPdf(array $po) { + require_once __DIR__ . '/../libs/TCPDF/tcpdf.php'; + require_once __DIR__ . '/billing_pdf.php'; + $company = billingCompany(); + $items = poItems($po['po_id']); + $number = poNumber($po); + $currency = (string) $po['po_currency_code']; + $e = function ($value) { + return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); + }; + $money = function ($amount) use ($currency, $e) { + return $e(poMoney($amount, $currency)); + }; + $grey = '#6c757d'; + $label = function ($text) use ($grey, $e) { + return '' . $e(strtoupper($text)) . ''; + }; + + $format = in_array($company['company_country'] ?? '', ['United States', 'USA', 'US', 'Canada'], true) ? 'LETTER' : 'A4'; + $pdf = new BillingPdf('P', 'mm', $format, true, 'UTF-8', false); + $pdf->SetCreator('ITFlow'); + $pdf->SetAuthor((string) ($company['company_name'] ?? '')); + $pdf->SetTitle("Purchase Order $number"); + $pdf->SetMargins(16, 14, 16); + $pdf->SetHeaderMargin(0); + $pdf->SetFooterMargin(12); + $pdf->SetAutoPageBreak(true, 20); + $pdf->setFontSubsetting(true); + $pdf->setImageScale(1.5); + $pdf->footer_label = trim(($company['company_name'] ?? '') . " · Purchase Order $number", ' ·'); + $pdf->AddPage(); + $margins = $pdf->getMargins(); + $width = $pdf->getPageWidth() - $margins['left'] - $margins['right']; + + // Who it is from, and what it is + $from_lines = array_filter([ + formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', "\n"), + implode(' · ', array_filter([$company['company_email'] ?? '', $company['phone_display'] ?? ''])), + $company['company_website'] ?? '', + ]); + $logo = !empty($company['logo_path']) ? '
' : ''; + $dates = ['Date' => $po['po_order_date'] ?: date('Y-m-d', strtotime($po['po_created_at']))]; + if ($po['po_vendor_reference']) { + $dates['Your order'] = $po['po_vendor_reference']; + } + if ($po['vendor_account_number']) { + $dates['Our account'] = $po['vendor_account_number']; + } + $dates_html = ''; + foreach ($dates as $date_label => $value) { + $dates_html .= '' . $e($date_label) . '' . $e($value) . ''; + } + $html = ' + + +
' . $logo . '' . $e($company['company_name'] ?? '') . '
' . nl2br($e(implode("\n", $from_lines))) . '
PURCHASE ORDER
' . $e($number) . '
+ ' . $dates_html . '
'; + $pdf->SetFont('dejavusans', '', 8.5); + $pdf->SetTextColor(33, 37, 41); + $pdf->writeHTML($html, true, false, true, false, ''); + $pdf->SetDrawColor(222, 226, 230); + $pdf->SetLineWidth(0.2); + $pdf->Ln(1); + $pdf->Line($margins['left'], $pdf->GetY(), $margins['left'] + $width, $pdf->GetY()); + $pdf->Ln(4); + + // Who it is to, and where it goes + $vendor_lines = array_filter([ + $po['vendor_contact_name'] ?? '', + implode(' · ', array_filter([$po['vendor_contact_email'] ?: ($po['vendor_email'] ?? ''), !empty($po['vendor_phone']) ? formatPhoneNumber($po['vendor_phone'], $po['vendor_phone_country_code']) : ''])), + ]); + $ship = preg_split('/\r?\n/', trim((string) $po['po_ship_to']), 2); + $html = ' + + +
' . $label('Vendor') . '
' . $e($po['vendor_name']) . '
' . nl2br($e(implode("\n", $vendor_lines))) . '
' . $label('Ship to') . '
' . $e($ship[0] ?? '') . '
' . nl2br($e($ship[1] ?? '')) . '
'; + $pdf->writeHTML($html, true, false, true, false, ''); + + // Not yet a firm order - or never one + $stamp = null; + if (in_array($po['po_status'], ['draft', 'pending'], true)) { + $stamp = [$po['po_status'] === 'pending' ? 'NOT YET APPROVED' : 'DRAFT', [176, 42, 55]]; + } elseif ($po['po_status'] === 'cancelled') { + $stamp = ['CANCELLED', [220, 53, 69]]; + } + if ($stamp) { + $y = $pdf->GetY(); + $pdf->SetAlpha(0.28); + $pdf->StartTransform(); + $pdf->Rotate(12, $margins['left'] + $width / 2, 21); + $pdf->SetFont('dejavusans', 'B', 18); + $pdf->SetTextColor(...$stamp[1]); + $pdf->SetDrawColor(...$stamp[1]); + $pdf->SetLineWidth(0.8); + $stamp_width = $pdf->GetStringWidth($stamp[0]) + 8; + $pdf->SetXY($margins['left'] + $width / 2 - $stamp_width / 2, 15.5); + $pdf->Cell($stamp_width, 11, $stamp[0], 1, 0, 'C'); + $pdf->StopTransform(); + $pdf->SetAlpha(1); + $pdf->SetDrawColor(222, 226, 230); + $pdf->SetLineWidth(0.2); + $pdf->SetTextColor(33, 37, 41); + $pdf->SetXY($margins['left'], $y); + } + $pdf->SetFont('dejavusans', '', 8.5); + $pdf->Ln(3); + + // The lines + $th = 'font-size:6.5pt; color:' . $grey . '; font-weight:bold; border-bottom:0.6px solid #adb5bd;'; + $td = 'border-bottom:0.3px solid #dee2e6;'; + $html = ' + + '; + $subtotal = 0; + foreach ($items as $item) { + $amount = round(floatval($item['po_item_quantity']) * floatval($item['po_item_cost']), 2); + $subtotal += $amount; + $html .= ' + + + '; + } + if (!$items) { + $html .= ''; + } + $html .= '
ITEMQTYUNIT COSTAMOUNT
' . $e($item['po_item_name']) . '' + . ($item['po_item_vendor_part'] ? '
Part ' . $e($item['po_item_vendor_part']) . '' : '') + . (trim((string) $item['po_item_description']) !== '' ? '
' . nl2br($e($item['po_item_description'])) . '' : '') . '
' . $e(billingQuantity($item['po_item_quantity'])) . '' . $money($item['po_item_cost']) . '' . $money($amount) . '
Nothing on it yet.
'; + $pdf->writeHTML($html, true, false, true, false, ''); + $pdf->Ln(3); + + // The note, and what it all comes to + $rows = 'Subtotal' . $money($subtotal) . ''; + if (floatval($po['po_shipping']) > 0) { + $rows .= 'Shipping' . $money($po['po_shipping']) . ''; + } + $rows .= 'Total' . $money($po['po_total']) . ''; + $note = trim((string) $po['po_note']); + $html = ' + + + +
' . ($note !== '' ? $label('Notes') . '
' . nl2br($e($note)) . '' : '') . '
' . $rows . '
'; + $pdf->writeHTML($html, true, false, true, false, ''); + $pdf->Ln(6); + $pdf->SetFont('dejavusans', '', 7.5); + $pdf->SetTextColor(108, 117, 125); + $pdf->MultiCell($width, 4, "Please quote $number on your invoice and packing slip.", 0, 'C', false, 1); + + $name = preg_replace('/[^A-Za-z0-9_\-]+/', '_', trim('Purchase_Order_' . $number . '_' . $po['vendor_name'], '_')) . '.pdf'; + return ['name' => $name, 'data' => $pdf->Output($name, 'S')]; +} + +/* + * Email the PO to the vendor (or $to) with its PDF, from the invoice + * mailbox - with the agent's own words. True, or false with $error. + */ +function poEmail(array $po, $to, $message, &$error = '') { + $error = ''; + $to = trim((string) $to); + if (!emailReady()) { + $error = 'Mail isn\'t set up to send - Admin > Settings > Mail.'; + return false; + } + if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { + $error = "$to isn't an email address."; + return false; + } + $file = billingEmailPdf(poPdf($po)); + if (!$file) { + $error = "The PDF couldn't be saved for the email - check uploads/tmp can be written to."; + return false; + } + $number = poNumber($po); + $company = billingCompany(); + $company_name = (string) ($company['company_name'] ?? ''); + $lines = []; + foreach (poItems($po['po_id']) as $item) { + $lines[] = [$item['po_item_name'] . ($item['po_item_vendor_part'] ? ' (' . $item['po_item_vendor_part'] . ')' : ''), billingQuantity($item['po_item_quantity'])]; + } + $sent = emailQueue([['email' => $to, 'name' => (string) ($po['vendor_contact_name'] ?: $po['vendor_name']), + 'greet' => (string) ($po['vendor_contact_name'] ?: ''), 'footnote' => "You get this because $company_name buys from " . $po['vendor_name'] . '.']], "Purchase order $number - $company_name", [ + 'kind' => 'Purchase order', 'tone' => 'primary', 'preview' => "Purchase order $number from $company_name", + 'title' => "Purchase order $number", + 'intro' => ["Please find our purchase order $number attached. Please quote it on your invoice and packing slip, and send your order number and tracking when it ships."], + 'note' => trim((string) $message), + 'summary' => ['Purchase order' => $number, 'Total' => poMoney($po['po_total'], $po['po_currency_code']), 'Ship to' => str_replace("\n", ', ', trim((string) $po['po_ship_to']))], + 'lines' => $lines ? ['head' => ['Item', 'Qty'], 'align' => ['left', 'right'], 'rows' => $lines] : null, + ], ['from' => billingEmailFrom('invoice'), 'attachments' => [$file]]); + if (!$sent) { + $error = "It couldn't be queued."; + return false; + } + poLog($po, 'Edit', poWho() . " emailed $number to $to", poLogClient($po['po_id'])); + return true; +} + +/* ------------------------------------------------------------- The side menu */ + +/** What the PURCHASING menu counts - to_order, pending (waiting for this agent's approval), arriving (lines still to come in). */ +function poNavCounts() { + global $mysqli, $session_user_id, $session_is_admin; + $counts = ['to_order' => 0, 'pending' => 0, 'arriving' => 0]; + if (poLevel() < 1) { + return $counts; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT + (SELECT COUNT(*) FROM order_items WHERE order_item_status = 'waiting'" . clientScopeSql('order_item_client_id') . ") AS to_order, + (SELECT COUNT(*) FROM purchase_orders WHERE po_status = 'pending'" . (poLevel() >= 3 && empty($session_is_admin) ? " AND po_created_by <> " . intval($session_user_id) : '') . poScopeSql('po_id') . ") AS pending, + (SELECT COUNT(*) FROM po_items JOIN purchase_orders ON po_id = po_item_po_id WHERE po_status IN ('ordered', 'partial') AND po_item_received < po_item_quantity" . poScopeSql('po_id') . ") AS arriving")); + $counts['to_order'] = intval($row['to_order'] ?? 0); + $counts['pending'] = poLevel() >= 3 ? intval($row['pending'] ?? 0) : 0; + $counts['arriving'] = intval($row['arriving'] ?? 0); + return $counts; +} diff --git a/functions/roles.php b/functions/roles.php index 085d90cb0..9caaa1ee8 100644 --- a/functions/roles.php +++ b/functions/roles.php @@ -24,7 +24,8 @@ const ROLE_LEVEL_TONES = [0 => 'secondary', 1 => 'primary', 2 => 'warning', 3 => /* * The modules a role gives levels for, by module_name: label, icon, about * (what is in it) and levels (what each level adds - Modify and Full take in - * the ones before). 'max' is the highest level that means anything. + * the ones before). 'max' is the highest level that means anything; 'full' + * is what Full lets a role do, for the refusal, where it isn't deleting. */ function roleModuleInfo() { return [ @@ -52,6 +53,11 @@ function roleModuleInfo() { 'label' => 'Reports', 'icon' => 'fa-chart-line', 'about' => 'The reports - each needs read access to what it reports on too', 'levels' => [1 => 'Open the reports'], 'max' => 1, ], + 'module_procurement' => [ + 'label' => 'Purchasing', 'icon' => 'fa-truck-loading', 'about' => 'Items to order, purchase orders to vendors and receiving - with invoicing on', + 'levels' => [1 => 'See them', 2 => 'Add items, make and send purchase orders, add tracking and receive', 3 => 'Approve and cancel purchase orders, and undo a receipt'], + 'full' => 'approve or cancel purchase orders, or undo a receipt', + ], 'module_ai' => [ 'label' => 'AI', 'icon' => 'fa-robot', 'about' => 'Rewording, summaries and drafts, by the AI providers in Admin - each needs access to what it works on too', 'levels' => [1 => 'Use AI'], 'max' => 1, diff --git a/functions/settings.php b/functions/settings.php index b1897e84d..430bd529e 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -51,6 +51,8 @@ function settingsPages() { 'about' => 'How quotes are numbered, what goes at the foot of them, and who hears when one is answered.'], 'invoice' => ['group' => 'work', 'title' => 'Invoices and billing', 'icon' => 'fa-file-invoice', 'url' => 'settings_invoice.php', 'module' => 'accounting', 'about' => 'Invoice numbering, late fees, reminders and statements, and how time, expenses and trips are billed.'], + 'purchase_order' => ['group' => 'work', 'title' => 'Purchase orders', 'icon' => 'fa-file-signature', 'url' => 'settings_purchase_order.php', 'module' => 'accounting', + 'about' => 'How purchase orders are numbered, and whether one needs approving before it is ordered.'], 'mail' => ['group' => 'email', 'title' => 'Mail', 'icon' => 'fa-envelope', 'url' => 'settings_mail.php', 'about' => 'The mailboxes ITFlow sends from and reads tickets from, the names emails come from, and tests.'], 'notification' => ['group' => 'email', 'title' => 'Notifications', 'icon' => 'fa-bell', 'url' => 'settings_notification.php', @@ -187,6 +189,10 @@ function settingsFields() { 'config_ticket_moving_columns' => ['page' => 'ticket', 'section' => 'The tickets page', 'label' => 'Rearrange the board\'s columns', 'words' => 'kanban columns move'] + $on_off, // Projects + 'config_po_prefix' => ['page' => 'purchase_order', 'section' => 'Numbering', 'label' => 'Purchase order prefix', 'words' => 'po number prefix purchasing'], + 'config_po_next_number' => ['page' => 'purchase_order', 'section' => 'Numbering', 'label' => 'Next purchase order number', 'words' => 'po number counter purchasing'], + 'config_po_approval' => ['page' => 'purchase_order', 'section' => 'Approval', 'label' => 'Purchase orders need approval', 'words' => 'po approve approver sign off purchasing'] + $on_off, + 'config_po_approval_over' => ['page' => 'purchase_order', 'section' => 'Approval', 'label' => 'Approve purchase orders over', 'words' => 'po approval amount threshold limit purchasing'], 'config_project_prefix' => ['page' => 'project', 'section' => 'Numbering', 'label' => 'Project prefix', 'words' => 'project number prj prefix'], 'config_project_next_number' => ['page' => 'project', 'section' => 'Numbering', 'label' => 'Next project number', 'words' => 'project number counter'], 'config_project_tickets_apart' => ['page' => 'project', 'section' => 'Project tickets', 'label' => 'Keep project tickets apart', 'kind' => 'switch', 'words' => 'project tickets sla service desk queue separate apart'], @@ -832,6 +838,7 @@ function settingsNumbering($kind) { 'project' => ['prefix' => 'config_project_prefix', 'number' => 'config_project_next_number', 'table' => 'projects', 'column' => 'project', 'what' => 'project'], 'quote' => ['prefix' => 'config_quote_prefix', 'number' => 'config_quote_next_number', 'table' => 'quotes', 'column' => 'quote', 'what' => 'quote'], 'invoice' => ['prefix' => 'config_invoice_prefix', 'number' => 'config_invoice_next_number', 'table' => 'invoices', 'column' => 'invoice', 'what' => 'invoice'], + 'purchase_order' => ['prefix' => 'config_po_prefix', 'number' => 'config_po_next_number', 'table' => 'purchase_orders', 'column' => 'po', 'what' => 'purchase order'], 'recurring_invoice' => ['prefix' => 'config_recurring_invoice_prefix', 'number' => 'config_recurring_invoice_next_number', 'table' => 'recurring_invoices', 'column' => 'recurring_invoice', 'what' => 'recurring invoice'], ]; return $numbering[$kind]; diff --git a/js/purchase_orders.js b/js/purchase_orders.js new file mode 100644 index 000000000..5c2241004 --- /dev/null +++ b/js/purchase_orders.js @@ -0,0 +1,39 @@ +/* + * Purchasing > Receiving (agent/receiving.php): All fills in what is left on + * a line, and a line's serials box grows to as many rows as came in. + */ +(function () { + var form = document.querySelector('[data-receiving]'); + if (!form || form.dataset.wired) { + return; + } + form.dataset.wired = '1'; + + function rows(line) { + var qty = line.querySelector('[data-receive-qty]'); + var serials = line.querySelector('textarea'); + if (!qty || !serials) { + return; + } + var n = Math.floor(Number(String(qty.value).replace(/[\s,]/g, ''))); + serials.rows = isFinite(n) && n > 1 ? Math.min(n, 8) : 1; + } + + form.addEventListener('click', function (e) { + var all = e.target.closest('[data-receive-all]'); + if (!all) { + return; + } + var line = all.closest('[data-receiving-line]'); + var qty = line.querySelector('[data-receive-qty]'); + qty.value = line.dataset.left; + rows(line); + qty.focus(); + }); + + form.addEventListener('input', function (e) { + if (e.target.matches('[data-receive-qty]')) { + rows(e.target.closest('[data-receiving-line]')); + } + }); +})(); diff --git a/setup/seed_data.php b/setup/seed_data.php index 578faa96f..40392d05f 100644 --- a/setup/seed_data.php +++ b/setup/seed_data.php @@ -94,6 +94,7 @@ function seedDefaultData($mysqli) mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_financial', module_description = 'Access to payments, accounts, expenses and budgets'"); mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_reporting', module_description = 'Access to all reports'"); mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_ai', module_description = 'Using AI - rewording, summaries and drafts'"); + mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_procurement', module_description = 'Access to purchasing - items to order, purchase orders and receiving'"); // Add default roles mysqli_query($mysqli, "INSERT INTO user_roles SET role_id = 1, role_name = 'Accountant', role_description = 'Built-in - Limited access to financial-focused modules'");