From de9544ffc66a7ec6b06e98597bee911f91e1b521 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 17:56:00 -0500 Subject: [PATCH] Recurring tickets book each ticket for its run day at a set time, remote or onsite, and can be raised a number of days ahead of the run or of the 1st of its month; recurring invoices can be made a number of days ahead, due on their date plus the client's terms or on their date; database 3.7.7 adds the columns; 26.11.9 changelog entries --- CHANGELOG.md | 5 +- admin/database_updates/3.7.7.php | 43 ++++++++ agent/includes/inc_recurring_ticket_ahead.php | 54 ++++++++++ agent/modals/billing/billing_form.php | 29 +++++- .../recurring_ticket/recurring_ticket_add.php | 2 + .../recurring_ticket_edit.php | 2 + agent/post/recurring_invoice.php | 10 +- agent/post/recurring_ticket.php | 20 +++- agent/recurring_tickets.php | 3 + cron/nightly_tasks.php | 17 ++-- db.sql | 6 ++ functions/billing.php | 26 ++++- functions/ticket.php | 99 +++++++++++++++++++ 13 files changed, 301 insertions(+), 15 deletions(-) create mode 100644 admin/database_updates/3.7.7.php create mode 100644 agent/includes/inc_recurring_ticket_ahead.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b946e4f0..ed7a71f51 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 ten database changes (3.6.6 to 3.7.6) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, and the settings for Quick tickets, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's eleven database changes (3.6.6 to 3.7.7) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, and columns on recurring tickets and recurring invoices for booking and making them ahead, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -85,6 +85,8 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Tickets: Email reply has a To line. It starts with the contact, the watchers and anyone at the client who asked for every update on their company's tickets; the technician it's assigned to, the client's other contacts or any email address typed in can be added, and anyone taken out. Everyone in To gets the email, each told why. What was changed is kept for the ticket, so its next email reply starts with the same people - taking a watcher out of To doesn't stop them watching. A reply sent to several tickets at once still goes to each one's contact and watchers. From Mountaineer IT's build of ITFlow. - Tickets: Quick ticket - the + in the top bar, on every page - is for a call or someone at your desk: the client (on a client's page, that one), the contact, found by name, email address or phone number, and what the issue is. The contact's tickets still open are listed first, with who has each, so the same problem isn't raised twice - Work on this one goes to one of them instead, with its timer running. Make ticket raises it as New Ticket would and opens it with its timer already running. Admin > Settings > Tickets, Quick tickets, sets what these tickets start with: who they go to, the status, priority, category and billing, when the timer starts, whether the contact starts on the client's primary and whether they're emailed. From Mountaineer IT's build of ITFlow. - Tickets: a stopwatch in the top bar shows the ticket timers running or paused in your browser, pulsing while one runs, so time isn't lost on a ticket you moved away from. It lists each ticket and its time, to go back to it, pause or resume the timer, or throw its time away. From Mountaineer IT's build of ITFlow. +- Recurring tickets: on Schedule, Book the work for takes a time and Remote or Onsite - each ticket raised is booked for its run day at that time, with the emails, calendar invite and note booking it on the ticket gives. Make it ahead raises each ticket so many days before its run day, which stays the day the work is for - or so many days before the 1st of its month, so every run in a month is raised on one day (monthly and longer repeats). The window says when the next one will be made, and the list shows the time and days ahead. Raise now books the ticket for its run too. From Mountaineer IT's build of ITFlow. +- Recurring invoices: Make it ahead makes each invoice so many days before its date, dated the day it's made, and Due, when made ahead sets it due on its date plus the client's terms, or on its date. With 0 days nothing changes. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -200,6 +202,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.7.4: `tickets.ticket_no_response_at`, the `ticket_resolved_at` of a resolution that was "no response" - `ticketIsNoResponse()` while the two match, so a reopen and a later resolve leave it behind - and `settings.config_ticket_no_response_message` (NULL is `TICKET_NO_RESPONSE_MESSAGE`). `resolve_ticket_no_response` (`agent/post/ticket.php`, window `agent/modals/ticket/ticket_resolve_no_response.php`) checks the ticket is open with its tasks done, and `ticketResolveNoResponse()` inserts the message as a public note, calls `ticketResolve()` and sends `ticketEmailContent()`'s `resolved` kind with `no_response`, the message in place of its words. `ticketMailClosed()` sends nothing for such a ticket. The Resolve button is a group with a split arrow, and the group carries `data-ticket-resolve`, so ticking a task swaps it whole. From Mountaineer IT's build of ITFlow. - Database 3.7.5: `ticket_mail_choices` - per ticket, the addresses put in or taken out of the To line where that differs from the default (the contact, watchers and `ticketColleagueRecipients()` in; the assigned agent, the client's other contacts and typed addresses out), going with the ticket. `functions/ticket_reply_recipients.php`: `ticketReplyRecipients()` lists who the To line offers, `ticketReplyRecipientsPick()` keeps the posted choice and returns `emailQueue()` recipients with why each gets it, `ticketReplyRecipientsForget()` clears it. `add_ticket_reply` sends to them when `email_to_shown` is posted with `email_to[]`, through `ticketMailReply()`'s new `$to` and `ticketMailSend()`'s `recipients` option; without it - the bulk reply, the API, an older form - to the contact and watchers as before. `change_client_ticket` takes off watchers who are neither agents nor the new client's contacts, and forgets the ticket's choices. From Mountaineer IT's build of ITFlow. - Database 3.7.6: `config_quick_ticket_on`, `_assign` ('me', 'nobody' or a user id), `_status`, `_priority`, `_category`, `_billable` (-1 is `config_ticket_default_billable`), `_timer` (make, open or off), `_primary`, `_open_tickets` and `_email_client` in `settings`, read by `quickTicketSettings()` (`functions/quick_ticket.php`). `includes/top_nav.php` has the + (an `ajax-modal` of `agent/modals/ticket/ticket_quick.php`, with `agent/js/ticket_quick.js`) and the timers menu (`js/ticket_timers.js`, loaded from `includes/footer.php`). The window posts `add_ticket` with `quick_ticket`, plain-text `details` (made HTML by `quickTicketDetailsHtml()`), `status`, `category_id`, `billable` and `quick_ticket_timer`, the browser's clock in ms; `add_ticket` skips `ticketMailCreated()` when `_email_client` is off and calls `quickTicketAfterCreate()`, which logs the history line and keeps the start in the session for `quickTicketTimerScript()`, printed on the ticket page before `agent/js/ticket_time_tracking.js`. `agent/ajax.php`: `ticket_also_open` takes `work` (who has each, when it last moved, a Work on this one button with `data-ticket-work`, up to 10, and a line when there are none), `get_client_contacts` also returns `contact_phone` and `contact_mobile`, and `ticket_timer_tickets` returns the reference, subject, client and state of the tickets behind the timers the agent can open. The timers read and write the same `-startTime`, `-pausedTime` and `ticket-timer-running-` keys, and on the ticket's own page press its `#startStopTimer`. From Mountaineer IT's build of ITFlow. +- Database 3.7.7: `recurring_tickets.recurring_ticket_schedule_time` (NULL books nothing), `_schedule_onsite`, `_lead_days` and `_lead_mode` (days or month), and `recurring_invoices.recurring_invoice_lead_days` and `_due_mode` (terms or next) - `recurringAheadReady()`. The nightly job takes recurring tickets by `recurringTicketDueSql()` and recurring invoices up to `recurring_invoice_lead_days` ahead, made with `recurringInvoiceGenerate()`'s `$early` when the date is still to come. `recurringTicketRunNow()` calls `recurringTicketBook()`, which books through `ticketSetSchedule()` for the run day at the time (today for a missed run), as "Recurring ticket" from the cron; `recurringInvoiceGenerate()` dates an invoice made ahead with lead days due by `recurringInvoiceAheadDue()`. Days ahead are kept short of one step by `recurringTicketLeadDays()` and `recurringInvoiceLeadDays()` (a month is 28 days, 90 at most; 27 before the 1st of the month, month-based repeats only). The fields are `schedule_time`, `schedule_onsite`, `lead_days` and `lead_mode` on the recurring ticket windows (`agent/includes/inc_recurring_ticket_ahead.php`), and `lead_days` and `due_mode` on the recurring invoice form; a post without `lead_days` keeps what is saved. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.7.7.php b/admin/database_updates/3.7.7.php new file mode 100644 index 000000000..4084a81eb --- /dev/null +++ b/admin/database_updates/3.7.7.php @@ -0,0 +1,43 @@ + 0; + }; + + foreach ([ + ['recurring_tickets', 'recurring_ticket_schedule_time', "time DEFAULT NULL", 'recurring_ticket_next_run'], + ['recurring_tickets', 'recurring_ticket_schedule_onsite', "tinyint(1) NOT NULL DEFAULT 0", 'recurring_ticket_schedule_time'], + ['recurring_tickets', 'recurring_ticket_lead_days', "int(11) NOT NULL DEFAULT 0", 'recurring_ticket_schedule_onsite'], + ['recurring_tickets', 'recurring_ticket_lead_mode', "varchar(10) NOT NULL DEFAULT 'days'", 'recurring_ticket_lead_days'], + ['recurring_invoices', 'recurring_invoice_lead_days', "int(11) NOT NULL DEFAULT 0", 'recurring_invoice_anchor_day'], + ['recurring_invoices', 'recurring_invoice_due_mode', "varchar(10) NOT NULL DEFAULT 'terms'", 'recurring_invoice_lead_days'], + ] as [$itflow_table, $itflow_name, $itflow_type, $itflow_after]) { + if (!$itflow_column($itflow_table, $itflow_name)) { + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_name` $itflow_type AFTER `$itflow_after`"); + } + } diff --git a/agent/includes/inc_recurring_ticket_ahead.php b/agent/includes/inc_recurring_ticket_ahead.php new file mode 100644 index 000000000..e29415f83 --- /dev/null +++ b/agent/includes/inc_recurring_ticket_ahead.php @@ -0,0 +1,54 @@ + +
+
+
+ +
+ + + +
+
Each ticket is booked for its run day at this time, with the emails and calendar invite booking it on the ticket sends. Leave it empty to book nothing.
+
+
+
+
+ +
+ + + +
+
0 makes it on its run day, which stays the day the work is for. Before the 1st of its month makes a month's runs on one day - 3 makes all of December's on November 28 - for monthly and longer repeats.
+ 0) { ?> +
The next one is made , for .
+ +
+
+
+Emailing the invoices recurring invoices make is off in Settings > Notifications - they are made as drafts. + 0 ? 'Net ' . intval($form_ahead_terms) + : 'the client\'s terms' . ($form_ahead_terms === null ? '' : ' (due on receipt)'); ?> +
+ +
+ + + days before +
+
0 makes it on its date. One made ahead is dated the day it is made - short of a whole period ahead.
+
+
+ +
+ + +
+
Its date is the invoice date - the client's terms count from there.
+
+
diff --git a/agent/modals/recurring_ticket/recurring_ticket_add.php b/agent/modals/recurring_ticket/recurring_ticket_add.php index ff1bd954d..961d822bc 100644 --- a/agent/modals/recurring_ticket/recurring_ticket_add.php +++ b/agent/modals/recurring_ticket/recurring_ticket_add.php @@ -213,6 +213,8 @@ ob_start();
The nightly cron raises a ticket on this day, then again each time it comes round. Monthly ones keep to this day of the month - the last day, in a shorter month.
+ +
diff --git a/agent/modals/recurring_ticket/recurring_ticket_edit.php b/agent/modals/recurring_ticket/recurring_ticket_edit.php index e59fdbb24..b6a351b36 100644 --- a/agent/modals/recurring_ticket/recurring_ticket_edit.php +++ b/agent/modals/recurring_ticket/recurring_ticket_edit.php @@ -210,6 +210,8 @@ ob_start();
+ +
diff --git a/agent/post/recurring_invoice.php b/agent/post/recurring_invoice.php index 2868dc963..70399d7ee 100644 --- a/agent/post/recurring_invoice.php +++ b/agent/post/recurring_invoice.php @@ -93,6 +93,9 @@ if (isset($_POST['add_recurring_invoice'])) { $scope = escapeSql($_POST['scope']); $recurring_invoice_discount = round(floatval($_POST['recurring_invoice_discount'] ?? 0), 2); $auto_send = intval($_POST['auto_send'] ?? 1) ? 1 : 0; + // Made ahead of its date, and when one made ahead is due (functions/billing.php) + $ahead_sql = recurringAheadReady() ? ", recurring_invoice_lead_days = " . recurringInvoiceLeadDays($_POST['lead_days'] ?? 0, $frequency) + . ", recurring_invoice_due_mode = '" . (($_POST['due_mode'] ?? '') === 'next' ? 'next' : 'terms') . "'" : ''; enforceClientAccess(); @@ -107,7 +110,7 @@ if (isset($_POST['add_recurring_invoice'])) { $recurring_invoice_number = mysqli_insert_id($mysqli); - mysqli_query($mysqli,"INSERT INTO recurring_invoices SET recurring_invoice_prefix = '$config_recurring_invoice_prefix', recurring_invoice_number = $recurring_invoice_number, recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$start_date', recurring_invoice_anchor_day = DAY('$start_date'), recurring_invoice_category_id = $category, recurring_invoice_status = 1, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_amount = " . (0 - $recurring_invoice_discount) . ", recurring_invoice_auto_send = $auto_send, recurring_invoice_currency_code = '$session_company_currency', recurring_invoice_client_id = $client_id"); + mysqli_query($mysqli,"INSERT INTO recurring_invoices SET recurring_invoice_prefix = '$config_recurring_invoice_prefix', recurring_invoice_number = $recurring_invoice_number, recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_next_date = '$start_date', recurring_invoice_anchor_day = DAY('$start_date'), recurring_invoice_category_id = $category, recurring_invoice_status = 1, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_amount = " . (0 - $recurring_invoice_discount) . ", recurring_invoice_auto_send = $auto_send, recurring_invoice_currency_code = '$session_company_currency', recurring_invoice_client_id = $client_id $ahead_sql"); $recurring_invoice_id = mysqli_insert_id($mysqli); @@ -135,6 +138,9 @@ if (isset($_POST['edit_recurring_invoice'])) { $status = intval($_POST['status']); $recurring_invoice_discount = floatval($_POST['recurring_invoice_discount']); $auto_send = intval($_POST['auto_send']); + // Made ahead of its date, and when one made ahead is due - kept as it is by a form without them + $ahead_sql = recurringAheadReady() && isset($_POST['lead_days']) ? ", recurring_invoice_lead_days = " . recurringInvoiceLeadDays($_POST['lead_days'], $frequency) + . ", recurring_invoice_due_mode = '" . (($_POST['due_mode'] ?? '') === 'next' ? 'next' : 'terms') . "'" : ''; // Get Recurring Invoice Details and Client ID for Logging $sql = mysqli_query($mysqli,"SELECT recurring_invoice_prefix, recurring_invoice_number, recurring_invoice_client_id FROM recurring_invoices WHERE recurring_invoice_id = $recurring_invoice_id"); @@ -153,7 +159,7 @@ if (isset($_POST['edit_recurring_invoice'])) { // so a schedule on the 31st that is on the 28th this month keeps the 31st. // (Set before next_date: MySQL reads a column already set in the same // UPDATE as its new value.) - mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_anchor_day = IF(recurring_invoice_next_date = '$next_date' AND recurring_invoice_anchor_day > 0, recurring_invoice_anchor_day, DAY('$next_date')), recurring_invoice_next_date = '$next_date', recurring_invoice_category_id = $category, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_auto_send = $auto_send, recurring_invoice_status = $status WHERE recurring_invoice_id = $recurring_invoice_id"); + mysqli_query($mysqli,"UPDATE recurring_invoices SET recurring_invoice_scope = '$scope', recurring_invoice_frequency = '$frequency', recurring_invoice_anchor_day = IF(recurring_invoice_next_date = '$next_date' AND recurring_invoice_anchor_day > 0, recurring_invoice_anchor_day, DAY('$next_date')), recurring_invoice_next_date = '$next_date', recurring_invoice_category_id = $category, recurring_invoice_discount_amount = $recurring_invoice_discount, recurring_invoice_auto_send = $auto_send, recurring_invoice_status = $status $ahead_sql WHERE recurring_invoice_id = $recurring_invoice_id"); billingRecalc('recurring', $recurring_invoice_id); diff --git a/agent/post/recurring_ticket.php b/agent/post/recurring_ticket.php index a808635b3..65fc019c0 100644 --- a/agent/post/recurring_ticket.php +++ b/agent/post/recurring_ticket.php @@ -19,7 +19,9 @@ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); * a SET clause - or back to the form with what is wrong. $current is the * recurring ticket being edited (null for a new one). 'fill_ins': the answers * to what its template asks for, raised with every ticket - null with no - * template, when any it has are kept as they are. + * template, when any it has are kept as they are. 'ahead': the time and visit + * each ticket is booked for and the days ahead it is made, as SQL to add to + * the SET - '' before the 3.7.7 update, or from a form without them. */ function recurringTicketFromPost($client_id, $current = null) { global $mysqli; @@ -50,6 +52,17 @@ function recurringTicketFromPost($client_id, $current = null) { // Billing is the sales module's to change - without it a schedule keeps what it has $billable = lookupUserPermission('module_sales') >= 2 ? (intval($_POST['billable'] ?? 0) ? 1 : 0) : intval($current['recurring_ticket_billable'] ?? 0); + // Booked at a time, and made ahead (functions/ticket.php) - before the 1st of the month for month-based repeats only + $ahead = ''; + if (recurringAheadReady() && isset($_POST['lead_days'])) { + $time = trim((string) ($_POST['schedule_time'] ?? '')); + $mode = ($_POST['lead_mode'] ?? '') === 'month' && recurringTicketMonthBased($frequency) ? 'month' : 'days'; + $ahead = ", recurring_ticket_schedule_time = " . (preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) ? "'$time:00'" : 'NULL') + . ", recurring_ticket_schedule_onsite = " . (intval($_POST['schedule_onsite'] ?? 0) ? 1 : 0) + . ", recurring_ticket_lead_days = " . recurringTicketLeadDays($_POST['lead_days'], $frequency, $mode) + . ", recurring_ticket_lead_mode = '$mode'"; + } + return [ 'subject' => escapeSql(mb_substr($subject, 0, 500)), 'details' => mysqli_real_escape_string($mysqli, (string) ($_POST['details'] ?? '')), @@ -62,6 +75,7 @@ function recurringTicketFromPost($client_id, $current = null) { 'category_id' => ticketCategoryId($_POST['category_id'] ?? 0), 'template_id' => $template_id, 'fill_ins' => $fill_ins, + 'ahead' => $ahead, ]; } @@ -124,7 +138,7 @@ if (isset($_POST['add_recurring_ticket'])) { recurring_ticket_priority = '{$f['priority']}', recurring_ticket_frequency = '{$f['frequency']}', recurring_ticket_billable = {$f['billable']}, recurring_ticket_start_date = '$start_date', recurring_ticket_next_run = '$start_date', recurring_ticket_assigned_to = {$f['assigned_to']}, recurring_ticket_created_by = $session_user_id, recurring_ticket_client_id = $client_id, recurring_ticket_contact_id = {$f['contact_id']}, - recurring_ticket_asset_id = {$f['asset_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']}"); + recurring_ticket_asset_id = {$f['asset_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']} {$f['ahead']}"); $recurring_ticket_id = mysqli_insert_id($mysqli); @@ -169,7 +183,7 @@ if (isset($_POST['edit_recurring_ticket'])) { mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_subject = '{$f['subject']}', recurring_ticket_details = '{$f['details']}', recurring_ticket_priority = '{$f['priority']}', recurring_ticket_frequency = '{$f['frequency']}', recurring_ticket_billable = {$f['billable']}, recurring_ticket_next_run = '$next_run' $anchor_sql, recurring_ticket_assigned_to = {$f['assigned_to']}, recurring_ticket_asset_id = {$f['asset_id']}, - recurring_ticket_contact_id = {$f['contact_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']} + recurring_ticket_contact_id = {$f['contact_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']} {$f['ahead']} WHERE recurring_ticket_id = $recurring_ticket_id"); // The other assets go with the asset field - an empty multi-select posts nothing diff --git a/agent/recurring_tickets.php b/agent/recurring_tickets.php index 73c1ccb19..b2bb1b267 100644 --- a/agent/recurring_tickets.php +++ b/agent/recurring_tickets.php @@ -341,6 +341,9 @@ $sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $di
+ +
+ diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 2111f7493..0f9c63d50 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -407,11 +407,12 @@ if ($tickets_pending_assignment > 0) { } // Recurring tickets - each one due today, or missed (a night the cron didn't -// run), raises one ticket and moves on to its next run after today. Paused ones -// raise nothing. recurringTicketRunNow() (functions/ticket.php) is the same code -// the Raise now button runs. +// run), or made so many days ahead of its run (recurringTicketDueSql()), raises +// one ticket - booked for its run day, when it has a time - and moves on to its +// next run. Paused ones raise nothing. recurringTicketRunNow() (functions/ticket.php) +// is the same code the Raise now button runs. $sql_recurring_tickets = mysqli_query($mysqli, "SELECT recurring_ticket_id, recurring_ticket_next_run, recurring_ticket_frequency, recurring_ticket_start_date - FROM recurring_tickets WHERE recurring_ticket_next_run <= CURDATE() AND recurring_ticket_paused_at IS NULL"); + FROM recurring_tickets WHERE " . recurringTicketDueSql() . " AND recurring_ticket_paused_at IS NULL"); $recurring_tickets_raised = 0; while ($row = mysqli_fetch_assoc($sql_recurring_tickets)) { @@ -563,7 +564,8 @@ if ($reminder_rules['enabled']) { // Recurring invoices - each one due today, or missed by up to -// RECURRING_INVOICE_GRACE_DAYS (a night or a few the cron didn't run), makes +// RECURRING_INVOICE_GRACE_DAYS (a night or a few the cron didn't run), or +// within the days ahead it is made (dated today, due by its due rule), makes // its invoice and moves on a period from the run it billed. One further // behind than that is left for someone to look at - the page says it is late // and offers Invoice Now, or moving it on without billing the missed runs. @@ -571,12 +573,13 @@ if ($reminder_rules['enabled']) { // Invoice Now button runs. $sql_recurring_invoices = mysqli_query($mysqli, "SELECT recurring_invoice_id, recurring_invoice_next_date FROM recurring_invoices WHERE recurring_invoice_status = 1 AND recurring_invoice_archived_at IS NULL - AND recurring_invoice_next_date <= CURDATE() AND recurring_invoice_next_date >= CURDATE() - INTERVAL " . RECURRING_INVOICE_GRACE_DAYS . " DAY + AND recurring_invoice_next_date <= CURDATE()" . (recurringAheadReady() ? " + INTERVAL recurring_invoice_lead_days DAY" : "") . " + AND recurring_invoice_next_date >= CURDATE() - INTERVAL " . RECURRING_INVOICE_GRACE_DAYS . " DAY ORDER BY recurring_invoice_next_date ASC, recurring_invoice_id ASC"); $recurring_invoices_made = 0; while ($row = mysqli_fetch_assoc($sql_recurring_invoices)) { - if (recurringInvoiceGenerate($row['recurring_invoice_id'], 'Cron', false, $row['recurring_invoice_next_date'])) { + if (recurringInvoiceGenerate($row['recurring_invoice_id'], 'Cron', $row['recurring_invoice_next_date'] > date('Y-m-d'), $row['recurring_invoice_next_date'])) { $recurring_invoices_made++; } } diff --git a/db.sql b/db.sql index 86ce36a12..60c40fe27 100644 --- a/db.sql +++ b/db.sql @@ -2740,6 +2740,8 @@ CREATE TABLE `recurring_invoices` ( `recurring_invoice_last_sent` date DEFAULT NULL, `recurring_invoice_next_date` date NOT NULL, `recurring_invoice_anchor_day` tinyint(2) NOT NULL DEFAULT 0, + `recurring_invoice_lead_days` int(11) NOT NULL DEFAULT 0, + `recurring_invoice_due_mode` varchar(10) NOT NULL DEFAULT 'terms', `recurring_invoice_status` int(1) NOT NULL, `recurring_invoice_discount_amount` decimal(15,2) NOT NULL DEFAULT 0.00, `recurring_invoice_amount` decimal(15,2) NOT NULL DEFAULT 0.00, @@ -2858,6 +2860,10 @@ CREATE TABLE `recurring_tickets` ( `recurring_ticket_billable` tinyint(1) NOT NULL DEFAULT 0, `recurring_ticket_start_date` date NOT NULL, `recurring_ticket_next_run` date NOT NULL, + `recurring_ticket_schedule_time` time DEFAULT NULL, + `recurring_ticket_schedule_onsite` tinyint(1) NOT NULL DEFAULT 0, + `recurring_ticket_lead_days` int(11) NOT NULL DEFAULT 0, + `recurring_ticket_lead_mode` varchar(10) NOT NULL DEFAULT 'days', `recurring_ticket_paused_at` datetime DEFAULT NULL, `recurring_ticket_created_at` datetime NOT NULL DEFAULT current_timestamp(), `recurring_ticket_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), diff --git a/functions/billing.php b/functions/billing.php index 4e4acc154..a053c3ae0 100644 --- a/functions/billing.php +++ b/functions/billing.php @@ -2370,6 +2370,11 @@ function recurringInvoiceGenerate($recurring_invoice_id, $by = 'Cron', $early = $client_id = intval($row['client_id']); // 0 is "On Receipt" - the contract in force's net terms, else the client's $terms = function_exists('contractNetTerms') ? contractNetTerms($client_id, $date) : billingDefaults()['net_terms']; + $due_sql = "DATE_ADD('$date', INTERVAL $terms DAY)"; + // Made ahead by its days ahead (recurringInvoiceAheadDue()) - due by the date it bills for, not the day it was made + if ($date < $due && intval($row['recurring_invoice_lead_days'] ?? 0) > 0) { + $due_sql = "'" . escapeSql(recurringInvoiceAheadDue($row, $due)) . "'"; + } $prefix = escapeSql($settings['config_invoice_prefix'] ?? ''); $number = billingNextNumber('invoice'); $url_key = randomString(32); @@ -2380,7 +2385,7 @@ function recurringInvoiceGenerate($recurring_invoice_id, $by = 'Cron', $early = $category_id = intval($row['recurring_invoice_category_id']); mysqli_query($mysqli, "INSERT INTO invoices SET invoice_prefix = '$prefix', invoice_number = $number, invoice_scope = '$scope', invoice_date = '$date', - invoice_due = DATE_ADD('$date', INTERVAL $terms DAY), invoice_discount_amount = $discount, invoice_amount = 0, invoice_currency_code = '$currency', + invoice_due = $due_sql, invoice_discount_amount = $discount, invoice_amount = 0, invoice_currency_code = '$currency', invoice_note = '$note', invoice_category_id = $category_id, invoice_status = 'Draft', invoice_url_key = '$url_key', invoice_recurring_invoice_id = $recurring_invoice_id, invoice_client_id = $client_id"); $invoice_id = mysqli_insert_id($mysqli); @@ -2437,6 +2442,25 @@ function recurringInvoiceGenerate($recurring_invoice_id, $by = 'Cron', $early = return $invoice_id; } +/* + * When an invoice a recurring invoice made ahead of its date ($run) is due - + * that date plus the client's terms as they stand then (terms), or the date + * itself (next). Y-m-d. + */ +function recurringInvoiceAheadDue($row, $run) { + $run = substr((string) $run, 0, 10); + if (($row['recurring_invoice_due_mode'] ?? 'terms') === 'next') { + return $run; + } + $terms = function_exists('contractNetTerms') ? intval(contractNetTerms(intval($row['recurring_invoice_client_id']), $run)) : intval(billingDefaults()['net_terms']); + return date('Y-m-d', strtotime($run . ' +' . max(0, $terms) . ' days')); +} + +/** Days ahead a recurring invoice is made, as kept: up to 90, and short of one period (a month counts as 28 days). */ +function recurringInvoiceLeadDays($days, $frequency) { + return max(0, min(intval($days), 90, 28 * recurringInvoiceMonths($frequency) - 1)); +} + /** The invoices a recurring invoice has made, newest first, with what has been paid on each. */ function recurringInvoiceGenerated($recurring_invoice_id, $limit = 12) { global $mysqli; diff --git a/functions/ticket.php b/functions/ticket.php index c85e0e6ed..13cbb10fe 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -1907,12 +1907,111 @@ function recurringTicketRunNow($row, $by) { $ticket_id = recurringTicketRaise($recurring_ticket_id, $by); if ($ticket_id) { $due = (string) $row['recurring_ticket_next_run']; + // Booked for the day of the run it is for, at its time - when it has one + recurringTicketBook($ticket_id, $recurring_ticket_id, $due); $next_run = recurringTicketNextRun($due, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], max(date('Y-m-d'), substr($due, 0, 10))); mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_next_run = '$next_run' WHERE recurring_ticket_id = $recurring_ticket_id"); } return $ticket_id; } +/* + * ---------- Recurring tickets booked at a time, and made ahead ---------- + * A recurring ticket with a time books each ticket it raises for its run day + * at that time, remote or onsite, as the ticket's Schedule window does - the + * same emails, calendar file, note and history. One made ahead is raised so + * many days before its run - or before the 1st of the run's month, so every + * run in a month is made on one day - and its next run stays the day the work + * is for. The nightly job picks it up then (recurringTicketDueSql()). + */ + +/** Whether the 3.7.7 update has run - the time, visit and days ahead on recurring tickets and invoices. */ +function recurringAheadReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '3.7.7', '>='); + } + return $ready; +} + +/** Whether a recurring ticket's repeat counts in months - only those may be made ahead of the 1st of the month. */ +function recurringTicketMonthBased($frequency) { + return isset(RECURRING_TICKET_FREQUENCIES[recurringTicketFrequency($frequency)]['months']); +} + +/* + * Days ahead as kept: up to 90, and short of one step of the repeat (a month + * counts as 28 days), so the next run is never due before this one is made - + * before the 1st of the month, up to 27. + */ +function recurringTicketLeadDays($days, $frequency, $mode = 'days') { + $step = RECURRING_TICKET_FREQUENCIES[recurringTicketFrequency($frequency) ?: 'Monthly']; + $most = $mode === 'month' ? 27 : min(90, (isset($step['days']) ? $step['days'] : 28 * $step['months']) - 1); + return max(0, min(intval($days), $most)); +} + +/** The day a recurring ticket makes the ticket for a run on $run - Y-m-d. */ +function recurringTicketMadeOn($row, $run) { + $run = substr((string) $run, 0, 10); + $days = intval($row['recurring_ticket_lead_days'] ?? 0); + $from = ($row['recurring_ticket_lead_mode'] ?? '') === 'month' ? substr($run, 0, 8) . '01' : $run; + return $days ? date('Y-m-d', strtotime("$from -$days days")) : $run; +} + +/** For the nightly job - the recurring tickets to raise: due today or missed, or with the day come to make one ahead. */ +function recurringTicketDueSql() { + if (!recurringAheadReady()) { + return "recurring_ticket_next_run <= CURDATE()"; + } + return "(recurring_ticket_next_run <= CURDATE() OR (recurring_ticket_lead_days > 0 AND DATE_SUB(IF(recurring_ticket_lead_mode = 'month', + DATE_FORMAT(recurring_ticket_next_run, '%Y-%m-01'), recurring_ticket_next_run), INTERVAL recurring_ticket_lead_days DAY) <= CURDATE()))"; +} + +/* + * Book a ticket a recurring ticket raised for the run it is for ($run), at the + * recurring ticket's time - today, for a run that was missed. Nothing without + * a time. The nightly job has nobody signed in, so the history and note say + * the recurring ticket booked it. + */ +function recurringTicketBook($ticket_id, $recurring_ticket_id, $run) { + global $session_name; + $recurring = recurringAheadReady() ? recurringTicketRow($recurring_ticket_id) : null; + $ticket = $recurring && !empty($recurring['recurring_ticket_schedule_time']) ? ticketRow($ticket_id) : null; + if (!$ticket) { + return; + } + $day = max(date('Y-m-d'), substr((string) $run, 0, 10)); + $was = $session_name ?? null; + if (empty($session_name)) { + $GLOBALS['session_name'] = 'Recurring ticket'; + } + try { + ticketSetSchedule($ticket, $day . ' ' . substr($recurring['recurring_ticket_schedule_time'], 0, 5) . ':00', intval($recurring['recurring_ticket_schedule_onsite'])); + } finally { + $GLOBALS['session_name'] = $was; + } +} + +/** "9:00 am onsite · made 3 days ahead", for the recurring tickets list. '' with neither. */ +function recurringTicketAheadText($row) { + $bits = []; + if (!empty($row['recurring_ticket_schedule_time'])) { + $bits[] = date('g:i a', strtotime('2000-01-01 ' . $row['recurring_ticket_schedule_time'])) . (intval($row['recurring_ticket_schedule_onsite']) ? ' onsite' : ' remote'); + } + $days = intval($row['recurring_ticket_lead_days'] ?? 0); + if ($days) { + $bits[] = 'made ' . $days . ' day' . ($days === 1 ? '' : 's') . (($row['recurring_ticket_lead_mode'] ?? '') === 'month' ? ' before the 1st' : ' ahead'); + } + return implode(' · ', $bits); +} + /** * For post handlers: the recurring ticket a request names, after the module * and client checks - or back with an error if it is gone. Sets the global