diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b8928e93..b5a6bcb6f 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 sixteen database changes (3.6.6 to 3.8.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, and columns on tickets and recurring tickets for how long booked work takes, 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 seventeen database changes (3.6.6 to 3.8.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, and a column each on recurring tickets and calendar events for repeating on a weekday, 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 @@ -98,6 +98,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Users: an API / service account is a login that API keys act as - for your RMM or a sync. Turn on API / service account on a user's Sign in tab (a new one needs Set a password now, as it isn't invited). It keeps its role, so its keys work as before, but it's left out of the calendar, the assign pickers, the reports and the other agent lists, gets no notifications or admin alerts, and can't sign in to ITFlow - a session it has is ended. Admin > Users lists them under API accounts, with an API badge, and leaves them out of the other tabs but Archived. It still takes a seat where there's a limit on agents. From Mountaineer IT's build of ITFlow. - Tickets: booked work has an end. The Schedule window has How long - 15 minutes to a day, an hour unless picked - and an Agent picker, so booking someone else's ticket gives it to them and takes it off the old agent's calendar. New Ticket's Schedule and a recurring ticket's Book the work for take a length too. The calendar draws each booking at its length, and dragging its bottom edge changes how long it takes, after asking. The booking email, the calendar file, the ticket and the guest page say when it ends. From Mountaineer IT's build of ITFlow. - Tickets: the warning when an agent is booked twice now means it - it lists their tickets and timed events that overlap the booking, at their lengths, instead of anything within two hours. From Mountaineer IT's build of ITFlow. +- Recurring tickets and events: a monthly, quarterly, twice-yearly or yearly recurring ticket, and a monthly or yearly event, can repeat on a weekday - the third Wednesday, or the last Friday - instead of the same date. Pick its date, then Repeats on offers what that date is: On the 16th, or On the third Wednesday. Moving the next run, or an event's start, keeps it on the same kind of weekday. The recurring tickets list, the event and its calendar invitations say which, and Google, Outlook and phone calendars that subscribe show it on the right days. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -221,6 +222,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.8.0: `user_cost_rates` (`user_cost_rate_user_id`, `_from`, `_hourly`, `_created_by`, `_created_at`, one a day per agent) and `config_labor_cost_default` (NULL leaves time uncosted) - `laborCostReady()`. `functions/labor_cost.php`: `laborCostRates()`, `laborCostRateOn()` (the newest rate on or before the day, the first also before it, else the default), `laborCostRateSave()`, `laborCostRateDelete()`, `laborCostParse()`. `admin/labor_costs.php`, `admin/modals/labor_cost/labor_cost_rates.php` and `labor_cost_default.php`, handlers `add_labor_cost_rate`, `delete_labor_cost_rate` and `edit_labor_cost_default` (`admin/post/labor_cost.php`). `agent/reports/client_profitability.php` calls `laborProfitAdd()` before net - `?basis=invoiced` replaces income with `item_subtotal` less `invoice_discount_amount` on Sent, Viewed, Partial and Paid invoices by `invoice_date`, plus revenue; labor by `ticket_reply_by` and day; parts as `product_cost * item_quantity` - and `laborProfitFinish()` after it for profit, margin, `hours_month` and `break_even`; the columns, totals, basis switch (`laborProfitBasis()`, paid by default) and second stats row are there only with 3.8.0. From Mountaineer IT's build of ITFlow. - Database 3.8.1: `users.user_service_account` - `serviceAccountsReady()`, `serviceAccountIs()`, `serviceAccountSave()` (`functions/service_account.php`). `serviceAccountsOutSql($column)` adds ` AND user_service_account = 0` to the agent lists and pickers (tickets, recurring tickets, projects, contracts, calendar and events, ticket templates, bulk assign, exports, reports, client onboarding, Quick ticket, mentions, trips, expenses, labor costs, Getting Started's team, user archive's hand-over, incident response) and to `appNotify()`, `signInAdmins()`, `cronHealthRecipients()` and the last-admin checks (`userActiveAdminCount()` in `functions/user.php`, `roles.php`). Not to `apiKeyAgents()`, the API's own checks (`api/v1/enforce_api_rbac.php`) or `getActiveAgentUserCount()`. `login.php` matches agents with `user_service_account = 0`, and `includes/load_user_session.php` ends a service account's session. The switch is `service_account` with `service_account_present` on `admin/modals/user/user_form.php`'s Sign in tab, saved by `add_user` (an invite with it is refused) and `edit_user`. `admin/users.php` adds the `service` view and excludes them from the others but `archived`. From Mountaineer IT's build of ITFlow. - Database 3.8.2: `tickets.ticket_schedule_end` (NULL is `CALENDAR_TICKET_MINUTES` after the start) and `recurring_tickets.recurring_ticket_schedule_minutes` (default 60) - `ticketScheduleEndReady()`. `ticketSetSchedule($row, $schedule, $onsite, $end = null)` keeps the end (cancelling clears it) and `ticketScheduleIcs()` and `createiCalStr(..., $uid, $end)` write it as DTEND. `ticketScheduleEnd()`, `ticketScheduleMinutes()`, `ticketScheduleMinutesValue()` (15 to 1440), `ticketScheduleLengths()`, `ticketScheduleLengthText()`, `ticketScheduleWhenText()` and `ticketScheduleShortText()` word it; `ticketScheduleOverlapSql($from, $to)` finds bookings running into a range, used by the calendar's tickets source, the agent feed and `ticketScheduleConflicts()` (overlapping tickets and timed calendar events of the agent). `edit_ticket_schedule` takes `schedule_tech` (one of `ticketMentionAgents()`, given the ticket with `ticketChangeAssignee()`, the old agent sent `ticketMailScheduleAgentCancelled()`) and `schedule_minutes`; `add_ticket` and the recurring ticket handlers take `schedule_minutes`, and `recurringTicketBook()` books that long. `calendar_move` (`agent/ajax.php`) takes an `end` from a resize, or keeps the length on a move; ticket items are `durationEditable`. From Mountaineer IT's build of ITFlow. +- Database 3.8.3: `recurring_tickets.recurring_ticket_by_day` and `calendar_events.event_repeat_by_day`, an RFC 5545 BYDAY value (`3WE`, `-1FR`; NULL is the same date) - `byDayReady()` and the helpers in `functions/by_day.php`: `byDayRule()`, `byDayDate($year, $month, $rule)`, `byDayText()`, `byDayOptions($date)` (the rules a date can take), `byDayForDate()` (a posted rule, kept when the date takes it), `byDayFollow()` (a rule carried to a moved date) and `byDayField()`, the Repeats on picker filled by `js/repeat_on.js`, which posts `repeat_on` with `repeat_on_field`. `recurringTicketNextRun()` takes `$by_day` for month-based frequencies, passed by every caller, and `recurringTicketByDaySql()` saves it for `add_recurring_ticket`, `edit_recurring_ticket`, the bulk next run and `recurring_tickets/create` and `update` (`repeat_on`). `calendarEventFormSet()` saves `event_repeat_by_day` from `repeat_on`, or follows `repeat_on_current`; `expandRecurringEvent()`, `calendarRepeatText()` and `icsRepeatToRrule($repeat, $interval, $until, $all_day, $timezone, $by_day, $start)` (BYDAY, with BYMONTH for yearly) use it, through `calendarEventByDay()`. `events/create` and `update` take `event_repeat_by_day`. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.8.3.php b/admin/database_updates/3.8.3.php new file mode 100644 index 000000000..6cb79be66 --- /dev/null +++ b/admin/database_updates/3.8.3.php @@ -0,0 +1,29 @@ + 0; + }; + + if (!$itflow_column('recurring_tickets', 'recurring_ticket_by_day')) { + mysqli_query($mysqli, "ALTER TABLE `recurring_tickets` ADD `recurring_ticket_by_day` varchar(5) DEFAULT NULL AFTER `recurring_ticket_frequency`"); + } + + if (!$itflow_column('calendar_events', 'event_repeat_by_day')) { + mysqli_query($mysqli, "ALTER TABLE `calendar_events` ADD `event_repeat_by_day` varchar(5) DEFAULT NULL AFTER `event_repeat_interval`"); + } diff --git a/agent/modals/calendar/calendar_event_form.php b/agent/modals/calendar/calendar_event_form.php index dff5a9da6..5ec703ea0 100644 --- a/agent/modals/calendar/calendar_event_form.php +++ b/agent/modals/calendar/calendar_event_form.php @@ -113,6 +113,7 @@ $form_can_email = calendarCanEmail(); +
Skipped: 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 f0928d6e0..15b5685bd 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/event.php b/agent/post/event.php index ebab4350e..6f44831d9 100644 --- a/agent/post/event.php +++ b/agent/post/event.php @@ -256,7 +256,7 @@ if (isset($_POST['edit_event'])) { enforceCalendarEvent(['event_client_id' => $client_id], 'edit'); } - $set = calendarEventFormSet($_POST, $client_id, $error); + $set = calendarEventFormSet($_POST + ['repeat_on_current' => $old['event_repeat_by_day'] ?? ''], $client_id, $error); if ($set === '') { flashAlert($error, 'error'); redirect(); @@ -267,7 +267,7 @@ if (isset($_POST['edit_event'])) { // A change a calendar that already has it needs to know about moves it on a version $event = calendarEventRow($event_id); $changed = false; - foreach (['event_title', 'event_start', 'event_end', 'event_all_day', 'event_location', 'event_location_id', 'event_description', 'event_repeat', 'event_repeat_interval', 'event_repeat_until'] as $field) { + foreach (array_merge(['event_title', 'event_start', 'event_end', 'event_all_day', 'event_location', 'event_location_id', 'event_description', 'event_repeat', 'event_repeat_interval', 'event_repeat_until'], byDayReady() ? ['event_repeat_by_day'] : []) as $field) { if ((string) $old[$field] !== (string) $event[$field]) { $changed = true; } diff --git a/agent/post/recurring_ticket.php b/agent/post/recurring_ticket.php index 2f9308184..ba57b155f 100644 --- a/agent/post/recurring_ticket.php +++ b/agent/post/recurring_ticket.php @@ -135,11 +135,14 @@ if (isset($_POST['add_recurring_ticket'])) { $f = recurringTicketFromPost($client_id); + // The weekday it repeats on - the third Wednesday - when the first run falls on it + $by_day_sql = byDayReady() ? ", recurring_ticket_by_day = " . recurringTicketByDaySql($f['frequency'], $start_date, $_POST['repeat_on'] ?? '') : ''; + mysqli_query($mysqli, "INSERT INTO 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_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']} {$f['ahead']}"); + recurring_ticket_asset_id = {$f['asset_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']} {$f['ahead']} $by_day_sql"); $recurring_ticket_id = mysqli_insert_id($mysqli); @@ -181,10 +184,13 @@ if (isset($_POST['edit_recurring_ticket'])) { // A run moved by hand is the new anchor - monthly ones keep to its day of the month from here $anchor_sql = $next_run !== $current_next_run ? ", recurring_ticket_start_date = '$next_run'" : ''; + // The weekday it repeats on, as picked - or, from a form without the field, the one it had, following a moved run + $by_day_sql = byDayReady() ? ", recurring_ticket_by_day = " . recurringTicketByDaySql($f['frequency'], $next_run, isset($_POST['repeat_on_field']) ? ($_POST['repeat_on'] ?? '') : null, $row['recurring_ticket_by_day'] ?? '') : ''; + 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']} {$f['ahead']} + recurring_ticket_contact_id = {$f['contact_id']}, recurring_ticket_category = {$f['category_id']}, recurring_ticket_ticket_template_id = {$f['template_id']} {$f['ahead']} $by_day_sql WHERE recurring_ticket_id = $recurring_ticket_id"); // The other assets go with the asset field - an empty multi-select posts nothing @@ -264,7 +270,7 @@ if (isset($_GET['pause_recurring_ticket']) || isset($_GET['resume_recurring_tick // Runs it missed while paused are not raised now - it picks up from today $next_run = substr((string) $row['recurring_ticket_next_run'], 0, 10); if ($next_run < date('Y-m-d')) { - $next_run = recurringTicketNextRun($next_run, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day'))); + $next_run = recurringTicketNextRun($next_run, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day')), $row['recurring_ticket_by_day'] ?? ''); } mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_paused_at = NULL, recurring_ticket_next_run = '$next_run' WHERE recurring_ticket_id = $recurring_ticket_id"); } @@ -292,7 +298,7 @@ if (isset($_POST['bulk_pause_recurring_tickets']) || isset($_POST['bulk_resume_r } else { $next_run = substr((string) $row['recurring_ticket_next_run'], 0, 10); if ($next_run < date('Y-m-d')) { - $next_run = recurringTicketNextRun($next_run, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day'))); + $next_run = recurringTicketNextRun($next_run, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day')), $row['recurring_ticket_by_day'] ?? ''); } mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_paused_at = NULL, recurring_ticket_next_run = '$next_run' WHERE recurring_ticket_id = $recurring_ticket_id"); } @@ -455,8 +461,9 @@ if (isset($_POST['bulk_edit_recurring_ticket_next_run_date'])) { $count = 0; foreach (recurringTicketsForBulk(2) as $recurring_ticket_id => $row) { - // A run moved by hand is the new anchor for the day of the month - mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_next_run = '$next_run', recurring_ticket_start_date = '$next_run' WHERE recurring_ticket_id = $recurring_ticket_id"); + // A run moved by hand is the new anchor for the day of the month - and a weekday rule follows it + $by_day_sql = byDayReady() ? ", recurring_ticket_by_day = " . recurringTicketByDaySql($row['recurring_ticket_frequency'], $next_run, null, $row['recurring_ticket_by_day'] ?? '') : ''; + mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_next_run = '$next_run', recurring_ticket_start_date = '$next_run' $by_day_sql WHERE recurring_ticket_id = $recurring_ticket_id"); logAudit("Recurring Ticket", "Edit", "$session_name moved the next run of recurring ticket " . escapeSql($row['recurring_ticket_subject']) . " from " . escapeSql($row['recurring_ticket_next_run']) . " to $next_run", intval($row['recurring_ticket_client_id']), $recurring_ticket_id); triggerCustomAction('recurring_ticket_update', $recurring_ticket_id); $count++; diff --git a/api/v1/events/create.php b/api/v1/events/create.php index 19e9ee8e5..b653d82da 100644 --- a/api/v1/events/create.php +++ b/api/v1/events/create.php @@ -22,6 +22,8 @@ * event_repeat optional - Day, Week, Month or Year * event_repeat_interval optional - Every so many, 1 to 99 * event_repeat_until optional - Its last day, Y-m-d + * event_repeat_by_day optional - Month and Year: the weekday it repeats on, as it starts - + * "3WE" the third Wednesday, "-1FR" the last Friday; empty for the same date * attendee_user_ids, attendee_contact_ids, attendee_emails optional - Who is on it * send_invites optional - 1 emails them the invitation * diff --git a/api/v1/events/event_model.php b/api/v1/events/event_model.php index fa6cc56df..7ce855045 100644 --- a/api/v1/events/event_model.php +++ b/api/v1/events/event_model.php @@ -57,6 +57,13 @@ if ($location_id && (!$client_id || !assetClientOwnedId('location', $location_id $event_refuse("event_location_id isn't one of the client's locations."); } +// The weekday a monthly or yearly one repeats on - one it has follows a moved start when none is sent +$by_day_sent = array_key_exists('event_repeat_by_day', $_POST) ? trim($sent('event_repeat_by_day', '')) : null; +if (byDayReady() && $by_day_sent !== null && $by_day_sent !== '' && (!in_array($repeat, ['Month', 'Year'], true) || byDayForDate($by_day_sent, $start_date) === '')) { + $options = in_array($repeat, ['Month', 'Year'], true) ? array_keys(byDayOptions($start_date)) : []; + $event_refuse('event_repeat_by_day is the weekday a Month or Year one repeats on, from its ' . $start_date . ' start' . ($options ? ': ' . implode(' or ', $options) : ' - none for this one') . ', or empty for the same date.'); +} + $error = ''; $event_set = calendarEventFormSet([ 'title' => $sent('event_title', $event_row['event_title'] ?? ''), @@ -72,7 +79,8 @@ $event_set = calendarEventFormSet([ 'location' => $sent('event_location', $event_row['event_location'] ?? ''), 'location_id' => $location_id, 'description' => $sent('event_description', $event_row['event_description'] ?? ''), -], $client_id, $error); + 'repeat_on_current' => $event_row['event_repeat_by_day'] ?? '', +] + ($by_day_sent !== null ? ['repeat_on' => $by_day_sent] : []), $client_id, $error); if ($event_set === '') { $event_refuse($error); } diff --git a/api/v1/events/update.php b/api/v1/events/update.php index 12955effa..af46238e9 100644 --- a/api/v1/events/update.php +++ b/api/v1/events/update.php @@ -47,7 +47,7 @@ if ($event_row) { // A change a calendar that already has it needs to know about moves it on a version $event = calendarEventRow($event_id); $changed = false; - foreach (['event_title', 'event_start', 'event_end', 'event_all_day', 'event_location', 'event_location_id', 'event_description', 'event_repeat', 'event_repeat_interval', 'event_repeat_until'] as $field) { + foreach (array_merge(['event_title', 'event_start', 'event_end', 'event_all_day', 'event_location', 'event_location_id', 'event_description', 'event_repeat', 'event_repeat_interval', 'event_repeat_until'], byDayReady() ? ['event_repeat_by_day'] : []) as $field) { if ((string) $event_row[$field] !== (string) $event[$field]) { $changed = true; } diff --git a/api/v1/recurring_tickets/create.php b/api/v1/recurring_tickets/create.php index 8d32ba568..31f674536 100644 --- a/api/v1/recurring_tickets/create.php +++ b/api/v1/recurring_tickets/create.php @@ -16,6 +16,9 @@ * subject required, unless the template has one * frequency required - Three Days, Weekly, Biweekly, Monthly, Quarterly, Biannually or Annually * start_date optional - Its first run, Y-m-d, today or later; today if left out + * repeat_on optional - Monthly to yearly ones: the weekday it repeats on, as its first + * run falls - "3WE" the third Wednesday, "-1FR" the last Friday; left out, + * the same date each time * details optional - HTML * priority optional - Low, Medium (the default), High or Urgent * billable optional - 1 or 0; needs Modify on Sales @@ -94,6 +97,9 @@ $rt_set += [ ]; $rt_set['recurring_ticket_start_date'] = "'$start_date'"; $rt_set['recurring_ticket_next_run'] = "'$start_date'"; +if (byDayReady()) { + $rt_set['recurring_ticket_by_day'] = $rt_by_day(trim($rt_set['recurring_ticket_frequency'], "'"), $start_date); +} $rt_set['recurring_ticket_created_by'] = intval($session_user_id); $rt_set['recurring_ticket_client_id'] = $client_id; diff --git a/api/v1/recurring_tickets/recurring_ticket_model.php b/api/v1/recurring_tickets/recurring_ticket_model.php index 0f361d0a2..0796a84d4 100644 --- a/api/v1/recurring_tickets/recurring_ticket_model.php +++ b/api/v1/recurring_tickets/recurring_ticket_model.php @@ -36,6 +36,17 @@ $rt_refuse = function ($message) use (&$return_arr) { $rt_text = function ($field) { return trim((string) (is_scalar($_POST[$field] ?? '') ? ($_POST[$field] ?? '') : '')); }; +// The weekday it repeats on (repeat_on, "3WE") for a run on $date, as SQL - checked like the form +// checks it; not sent, the rule it had ($current) follows the run. Needs the 3.8.3 update. +$rt_by_day = function ($frequency, $date, $current = '') use ($rt_refuse, $rt_text) { + if (array_key_exists('repeat_on', $_POST) && $rt_text('repeat_on') !== '') { + if (!recurringTicketMonthBased($frequency) || byDayForDate($rt_text('repeat_on'), $date) === '') { + $options = recurringTicketMonthBased($frequency) ? array_keys(byDayOptions($date)) : []; + $rt_refuse('repeat_on is the weekday a monthly to yearly one repeats on, from its ' . $date . ' run' . ($options ? ': ' . implode(' or ', $options) : ' - none for this one') . ', or empty for the same date each time.'); + } + } + return recurringTicketByDaySql($frequency, $date, array_key_exists('repeat_on', $_POST) ? $rt_text('repeat_on') : null, $current); +}; if (array_key_exists('subject', $_POST)) { if ($rt_text('subject') === '') { diff --git a/api/v1/recurring_tickets/status.php b/api/v1/recurring_tickets/status.php index 911399fdd..34df561f1 100644 --- a/api/v1/recurring_tickets/status.php +++ b/api/v1/recurring_tickets/status.php @@ -30,7 +30,7 @@ if ($rt_row && isset($_POST['status'])) { mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_paused_at = COALESCE(recurring_ticket_paused_at, NOW()) WHERE recurring_ticket_id = $recurring_ticket_id"); } else { if ($next_run < date('Y-m-d')) { - $next_run = recurringTicketNextRun($next_run, $rt_row['recurring_ticket_frequency'], $rt_row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day'))); + $next_run = recurringTicketNextRun($next_run, $rt_row['recurring_ticket_frequency'], $rt_row['recurring_ticket_start_date'], date('Y-m-d', strtotime('-1 day')), $rt_row['recurring_ticket_by_day'] ?? ''); } mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_paused_at = NULL, recurring_ticket_next_run = '" . escapeSql($next_run) . "' WHERE recurring_ticket_id = $recurring_ticket_id"); } diff --git a/api/v1/recurring_tickets/update.php b/api/v1/recurring_tickets/update.php index 26b06ff2a..fe6544cac 100644 --- a/api/v1/recurring_tickets/update.php +++ b/api/v1/recurring_tickets/update.php @@ -13,6 +13,8 @@ * recurring_ticket_id required - The recurring ticket * client_id its client - needed when the key's user is limited to certain clients * next_date optional - Its next run, Y-m-d + * repeat_on optional - As for create, from its next run; one it has follows a moved + * next_date * subject, details, priority, frequency, billable, assigned_to, contact_id, asset_id, * asset_ids, category_id, ticket_template_id, fill_ins, tasks * optional - as for recurring_tickets/create.php @@ -44,8 +46,17 @@ if ($rt_row) { } } + // The weekday it repeats on - as sent, or the one it had following its run, going with a repeat that isn't month-based + if (byDayReady() && (array_key_exists('repeat_on', $_POST) || isset($rt_set['recurring_ticket_frequency']) || isset($rt_set['recurring_ticket_next_run']))) { + $rt_set['recurring_ticket_by_day'] = $rt_by_day( + isset($rt_set['recurring_ticket_frequency']) ? trim($rt_set['recurring_ticket_frequency'], "'") : $rt_row['recurring_ticket_frequency'], + isset($rt_set['recurring_ticket_next_run']) ? trim($rt_set['recurring_ticket_next_run'], "'") : substr((string) $rt_row['recurring_ticket_next_run'], 0, 10), + $rt_row['recurring_ticket_by_day'] ?? '' + ); + } + if (!$rt_set && $rt_assets === null && $rt_tasks === null && $rt_fill_ins === null && !array_key_exists('next_date', $_POST)) { - $rt_refuse('Send at least one of subject, details, priority, frequency, next_date, billable, assigned_to, contact_id, asset_id, asset_ids, category_id, ticket_template_id, fill_ins or tasks.'); + $rt_refuse('Send at least one of subject, details, priority, frequency, next_date, repeat_on, billable, assigned_to, contact_id, asset_id, asset_ids, category_id, ticket_template_id, fill_ins or tasks.'); } $update_sql = $rt_set ? mysqli_query($mysqli, "UPDATE recurring_tickets SET " . implode(', ', array_map(function ($column, $value) { diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 67e4b4366..959a14bcf 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -411,7 +411,7 @@ if ($tickets_pending_assignment > 0) { // 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 +$sql_recurring_tickets = mysqli_query($mysqli, "SELECT recurring_ticket_id, recurring_ticket_next_run, recurring_ticket_frequency, recurring_ticket_start_date" . (byDayReady() ? ", recurring_ticket_by_day" : "") . " FROM recurring_tickets WHERE " . recurringTicketDueSql() . " AND recurring_ticket_paused_at IS NULL"); $recurring_tickets_raised = 0; diff --git a/db.sql b/db.sql index fc0c974d4..0fd7eb14a 100644 --- a/db.sql +++ b/db.sql @@ -583,6 +583,7 @@ CREATE TABLE `calendar_events` ( `event_all_day` tinyint(1) NOT NULL DEFAULT 0, `event_repeat` varchar(200) DEFAULT NULL, `event_repeat_interval` int(11) NOT NULL DEFAULT 1, + `event_repeat_by_day` varchar(5) DEFAULT NULL, `event_repeat_until` date DEFAULT NULL, `event_repeat_skip` text DEFAULT NULL, `event_sequence` int(11) NOT NULL DEFAULT 0, @@ -2857,6 +2858,7 @@ CREATE TABLE `recurring_tickets` ( `recurring_ticket_details` longtext NOT NULL, `recurring_ticket_priority` varchar(200) DEFAULT NULL, `recurring_ticket_frequency` varchar(10) NOT NULL, + `recurring_ticket_by_day` varchar(5) DEFAULT NULL, `recurring_ticket_billable` tinyint(1) NOT NULL DEFAULT 0, `recurring_ticket_start_date` date NOT NULL, `recurring_ticket_next_run` date NOT NULL, diff --git a/functions.php b/functions.php index 86958ed57..ef06b1e34 100644 --- a/functions.php +++ b/functions.php @@ -68,6 +68,7 @@ require_once __DIR__ . '/functions/custom_link.php'; require_once __DIR__ . '/functions/system_health.php'; require_once __DIR__ . '/functions/database_collation.php'; require_once __DIR__ . '/functions/ticket_fields.php'; +require_once __DIR__ . '/functions/by_day.php'; require_once __DIR__ . '/functions/ticket.php'; require_once __DIR__ . '/functions/ticket_status.php'; require_once __DIR__ . '/functions/ticket_template.php'; diff --git a/functions/by_day.php b/functions/by_day.php new file mode 100644 index 000000000..e799a9356 --- /dev/null +++ b/functions/by_day.php @@ -0,0 +1,134 @@ + 'Monday', 'TU' => 'Tuesday', 'WE' => 'Wednesday', 'TH' => 'Thursday', 'FR' => 'Friday', 'SA' => 'Saturday', 'SU' => 'Sunday']; +const BY_DAY_ORDINALS = [1 => 'first', 2 => 'second', 3 => 'third', 4 => 'fourth', -1 => 'last']; + +/** Whether the 3.8.3 update has run. */ +function byDayReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '3.8.3', '>='); + } + return $ready; +} + +/** The rule tidied ("3WE", "-1FR"), or '' when it isn't one. */ +function byDayRule($rule) { + $rule = strtoupper(trim((string) $rule)); + return preg_match('/^(-1|[1-4])(MO|TU|WE|TH|FR|SA|SU)$/', $rule) ? $rule : ''; +} + +/** [ordinal, weekday code] of a rule - [0, ''] for none. */ +function byDayParts($rule) { + $rule = byDayRule($rule); + return $rule === '' ? [0, ''] : [intval(substr($rule, 0, -2)), substr($rule, -2)]; +} + +/** The date ('Y-m-d') a rule falls on in a month - the first to fourth and the last of a weekday are in every month. */ +function byDayDate($year, $month, $rule) { + [$ordinal, $code] = byDayParts($rule); + if (!$ordinal) { + return null; + } + $weekday = array_search($code, array_keys(BY_DAY_WEEKDAYS)) + 1; // ISO, 1 (Monday) to 7 (Sunday) + $days = intval(date('t', mktime(0, 0, 0, $month, 1, $year))); + if ($ordinal > 0) { + $first = intval(date('N', mktime(0, 0, 0, $month, 1, $year))); + $day = 1 + (($weekday - $first + 7) % 7) + ($ordinal - 1) * 7; + } else { + $last = intval(date('N', mktime(0, 0, 0, $month, $days, $year))); + $day = $days - (($last - $weekday + 7) % 7); + } + return sprintf('%04d-%02d-%02d', $year, $month, $day); +} + +/** "the third Wednesday", "the last Friday" - '' for no rule. */ +function byDayText($rule) { + [$ordinal, $code] = byDayParts($rule); + return $ordinal ? 'the ' . BY_DAY_ORDINALS[$ordinal] . ' ' . BY_DAY_WEEKDAYS[$code] : ''; +} + +/* + * The weekday rules a date can repeat on: its weekday of the month when that's the first to + * fourth, and the last when it's in the month's last seven days - [rule => "the third Wednesday"]. + */ +function byDayOptions($date) { + $ts = strtotime(substr((string) $date, 0, 10)); + if (!$ts) { + return []; + } + $code = array_keys(BY_DAY_WEEKDAYS)[intval(date('N', $ts)) - 1]; + $day = intval(date('j', $ts)); + $options = []; + $nth = intdiv($day - 1, 7) + 1; + if ($nth <= 4) { + $options[$nth . $code] = byDayText($nth . $code); + } + if ($day + 7 > intval(date('t', $ts))) { + $options['-1' . $code] = byDayText('-1' . $code); + } + return $options; +} + +/** A posted rule, kept only when the date can repeat on it - else ''. */ +function byDayForDate($rule, $date) { + $rule = byDayRule($rule); + return $rule !== '' && isset(byDayOptions($date)[$rule]) ? $rule : ''; +} + +/* + * A rule carried to a new date - a run or an event moved by hand: kept while the new date still + * fits it, otherwise the same kind of rule for the new date, the last staying the last when it can. + */ +function byDayFollow($rule, $date) { + $rule = byDayRule($rule); + if ($rule === '' || byDayForDate($rule, $date) !== '') { + return $rule; + } + $options = array_keys(byDayOptions($date)); + $last = array_values(array_filter($options, function ($option) { return strpos($option, '-1') === 0; })); + $nth = array_values(array_filter($options, function ($option) { return strpos($option, '-1') !== 0; })); + if (strpos($rule, '-1') === 0) { + return $last[0] ?? ($nth[0] ?? ''); + } + return $nth[0] ?? ($last[0] ?? ''); +} + +/* + * The Repeats on field (js/repeat_on.js fills it from the date): $date and $frequency are + * selectors for those fields in the same form, $months the frequency values it's for, $yearly + * those worded "of October". Posts repeat_on - nothing while hidden, so repeat_on_field says the + * form had it. Nothing before the update. + */ +function byDayField($date, $frequency, array $months, array $yearly, $current, $wrap_class = 'mb-3', $label_class = '') { + if (!byDayReady()) { + return ''; + } + return ''; +} diff --git a/functions/calendar.php b/functions/calendar.php index e181c4019..c780ee62b 100644 --- a/functions/calendar.php +++ b/functions/calendar.php @@ -257,7 +257,7 @@ function calendarEventRepeats($row) { return isset(CALENDAR_REPEATS[(string) ($row['event_repeat'] ?? '')]); } -/** "Every week", "Every 2 weeks until Mar 3, 2027", or '' for an event that does not repeat. */ +/** "Every week", "Every month on the third Wednesday", "Every 2 weeks until Mar 3, 2027", or '' for an event that does not repeat. */ function calendarRepeatText($row) { if (!calendarEventRepeats($row)) { return ''; @@ -265,12 +265,21 @@ function calendarRepeatText($row) { $interval = max(1, intval($row['event_repeat_interval'] ?? 1)); [, $one, $many] = CALENDAR_REPEATS[(string) $row['event_repeat']]; $text = $interval === 1 ? "Every $one" : "Every $interval $many"; + $by_day = calendarEventByDay($row); + if ($by_day !== '') { + $text .= ' on ' . byDayText($by_day) . ($row['event_repeat'] === 'Year' ? ' of ' . date('F', strtotime($row['event_start'])) : ''); + } if (!empty($row['event_repeat_until'])) { $text .= ' until ' . date('M j, Y', strtotime($row['event_repeat_until'])); } return $text; } +/** The weekday a monthly or yearly event repeats on ("3WE", functions/by_day.php) - '' for the same date each time. */ +function calendarEventByDay($row) { + return in_array($row['event_repeat'] ?? '', ['Month', 'Year'], true) ? byDayRule($row['event_repeat_by_day'] ?? '') : ''; +} + /** The dates of occurrences that have been skipped - ['Y-m-d', ...]. */ function calendarSkippedDates($row) { $skip = trim((string) ($row['event_repeat_skip'] ?? '')); @@ -291,6 +300,7 @@ function calendarSkippedDates($row) { * running date, so a long series cannot drift and a 9:00 meeting stays at 9:00 * either side of a DST change. Monthly on the 31st and yearly on Feb 29 skip the * months without that day, as RFC 5545 does, rather than rolling into the next. + * One on a weekday of the month (event_repeat_by_day) is on that day of each one. * * An occurrence still under way at the start of the window is included. The * bundled FullCalendar build has no rrule plugin, so the page gets the @@ -326,12 +336,18 @@ function expandRecurringEvent(array $event, $window_start, $window_end, $limit = $skip = array_flip(calendarSkippedDates($event)); $step = ['Day' => 'day', 'Week' => 'week', 'Month' => 'month', 'Year' => 'year'][$repeat]; $base_day = (int) $base->format('j'); + $by_day = calendarEventByDay($event); $occurrences = []; for ($i = 0; count($occurrences) < $limit && $i < 50000; $i++) { $candidate = clone $base; - if ($i > 0) { + if ($i > 0 && $by_day !== '') { + // Stepped from the 1st, so no month is passed over, then put on the rule's day - at the same time + $candidate->setDate((int) $base->format('Y'), (int) $base->format('n'), 1); + $candidate->modify('+' . ($i * $interval) . " $step"); + $candidate->setDate((int) $candidate->format('Y'), (int) $candidate->format('n'), (int) substr(byDayDate((int) $candidate->format('Y'), (int) $candidate->format('n'), $by_day), 8, 2)); + } elseif ($i > 0) { $candidate->modify('+' . ($i * $interval) . " $step"); if (($step === 'month' || $step === 'year') && (int) $candidate->format('j') !== $base_day) { if ($candidate > $to) { @@ -546,11 +562,24 @@ function calendarEventFormSet($post, $client_id, &$error = '') { $location_id = intval(assetClientOwnedId('location', $post['location_id'], $client_id)); } + // The weekday a monthly or yearly one repeats on (functions/by_day.php) - the one picked, when the + // start falls on it; from a form without the field, the one it had ('repeat_on_current') follows the start + $by_day_sql = ''; + if (byDayReady()) { + $by_day = ''; + if ($repeat === 'Month' || $repeat === 'Year') { + $by_day = isset($post['repeat_on_field']) || array_key_exists('repeat_on', $post) + ? byDayForDate($post['repeat_on'] ?? '', $start_date) + : byDayFollow($post['repeat_on_current'] ?? '', $start_date); + } + $by_day_sql = ", event_repeat_by_day = " . ($by_day !== '' ? "'$by_day'" : 'NULL'); + } + return "event_title = '" . escapeSql(mb_substr($title, 0, 200)) . "', event_location = '" . escapeSql(mb_substr(trim((string) ($post['location'] ?? '')), 0, 500)) . "', event_description = '" . escapeSql(trim((string) ($post['description'] ?? ''))) . "', event_start = '$start', event_end = '$end', event_all_day = $all_day, - event_repeat = '$repeat', event_repeat_interval = $interval, event_repeat_until = " . ($until !== '' ? "'$until'" : 'NULL') . ", + event_repeat = '$repeat', event_repeat_interval = $interval, event_repeat_until = " . ($until !== '' ? "'$until'" : 'NULL') . "$by_day_sql, event_calendar_id = $calendar_id, event_client_id = " . intval($client_id) . ", event_location_id = $location_id"; } @@ -767,7 +796,7 @@ function calendarEventItems(array $calendar_ids, $from, $to, array $opts = []) { $user_id = intval($opts['user_id'] ?? 0); $user_query = $user_id ? "AND (event_created_by = $user_id OR EXISTS (SELECT 1 FROM calendar_event_attendees a WHERE a.attendee_event_id = event_id AND a.attendee_user_id = $user_id))" : ''; - $sql = mysqli_query($mysqli, "SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip, + $sql = mysqli_query($mysqli, "SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip," . (byDayReady() ? " event_repeat_by_day," : "") . " event_location, event_client_id, event_calendar_id, event_created_by, calendar_color, client_name, location_name, (SELECT COUNT(*) FROM calendar_event_attendees a WHERE a.attendee_event_id = event_id) AS attendee_count, (SELECT COUNT(*) FROM calendar_event_attendees a WHERE a.attendee_event_id = event_id AND a.attendee_invited_at IS NOT NULL) AS invited_count @@ -971,7 +1000,7 @@ function icsVtimezone($timezone, $from, $to) { * UTC (RFC 5545 requires UTC when DTSTART carries a TZID); an all-day event's * is the date itself. */ -function icsRepeatToRrule($repeat, $interval = 1, $until = null, $all_day = false, $timezone = 'UTC') { +function icsRepeatToRrule($repeat, $interval = 1, $until = null, $all_day = false, $timezone = 'UTC', $by_day = '', $start = null) { if (!isset(CALENDAR_REPEATS[(string) $repeat])) { return null; @@ -981,6 +1010,11 @@ function icsRepeatToRrule($repeat, $interval = 1, $until = null, $all_day = fals if (intval($interval) > 1) { $rule .= ';INTERVAL=' . intval($interval); } + // On a weekday of the month - yearly ones in the month they start in + $by_day = in_array($repeat, ['Month', 'Year'], true) ? byDayRule($by_day) : ''; + if ($by_day !== '') { + $rule .= ';BYDAY=' . $by_day . ($repeat === 'Year' && $start ? ';BYMONTH=' . date('n', strtotime($start)) : ''); + } if (!empty($until)) { $rule .= ';UNTIL=' . ($all_day ? date('Ymd', strtotime($until)) : icsFormatUtc(substr($until, 0, 10) . ' 23:59:59', $timezone)); } @@ -1044,7 +1078,7 @@ function icsEventLines(array $item, $timezone, $tzid) { } } - $rrule = icsRepeatToRrule($item['repeat'] ?? '', $item['repeat_interval'] ?? 1, $item['repeat_until'] ?? null, $all_day, $timezone); + $rrule = icsRepeatToRrule($item['repeat'] ?? '', $item['repeat_interval'] ?? 1, $item['repeat_until'] ?? null, $all_day, $timezone, $item['repeat_by_day'] ?? '', $item['start'] ?? null); if ($rrule) { $lines[] = "RRULE:$rrule"; foreach ($item['skip'] ?? [] as $date) { @@ -1191,6 +1225,7 @@ function calendarEventIcsItem(array $event, $busy = false) { 'repeat' => $event['event_repeat'] ?? '', 'repeat_interval' => $event['event_repeat_interval'] ?? 1, 'repeat_until' => $event['event_repeat_until'] ?? null, + 'repeat_by_day' => calendarEventByDay($event), 'skip' => calendarSkippedDates($event), 'busy' => $busy, ]; diff --git a/functions/client_overview.php b/functions/client_overview.php index 23c4790e1..0d4b90065 100644 --- a/functions/client_overview.php +++ b/functions/client_overview.php @@ -400,7 +400,7 @@ function clientOverviewUpcoming($client_id, $access, $days = 14) { } } - $sql = mysqli_query($mysqli, "SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip, + $sql = mysqli_query($mysqli, "SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip," . (byDayReady() ? " event_repeat_by_day," : "") . " event_location, location_name FROM calendar_events JOIN calendars ON calendar_id = event_calendar_id AND calendar_archived_at IS NULL diff --git a/functions/dashboard.php b/functions/dashboard.php index 7fd087e1e..ba885762f 100644 --- a/functions/dashboard.php +++ b/functions/dashboard.php @@ -492,7 +492,7 @@ function dashboardSchedule($days = 7, $limit = 30) { // Events I am on or added - and the ones nobody owns (made before events had // attendees, or with no agent on them), which are everyone's $sql = mysqli_query($mysqli, " - SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip, + SELECT event_id, event_title, event_start, event_end, event_all_day, event_repeat, event_repeat_interval, event_repeat_until, event_repeat_skip," . (byDayReady() ? " event_repeat_by_day," : "") . " event_location, client_name, calendar_color, location_name FROM calendar_events JOIN calendars ON event_calendar_id = calendar_id AND calendar_archived_at IS NULL diff --git a/functions/ticket.php b/functions/ticket.php index c32ef29f8..ebe5b233d 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -1806,13 +1806,15 @@ function recurringTicketFrequency($frequency) { * was due fell on - except when that was a shorter month's last day standing * in for a later one: one that started ($anchor) on the 31st runs on the last * day of shorter months and back on the 31st after, rather than drifting. - * Missed runs are stepped over, not raised one by one. + * Missed runs are stepped over, not raised one by one. With a weekday rule + * ($by_day, "3WE") month-based ones land on that weekday of the month instead. */ -function recurringTicketNextRun($due, $frequency, $anchor = '', $after = '') { +function recurringTicketNextRun($due, $frequency, $anchor = '', $after = '', $by_day = '') { $frequency = recurringTicketFrequency($frequency) ?: 'Monthly'; $step = RECURRING_TICKET_FREQUENCIES[$frequency]; $after = $after !== '' ? $after : date('Y-m-d'); $date = DateTime::createFromFormat('!Y-m-d', substr((string) $due, 0, 10)) ?: new DateTime('today'); + $by_day = isset($step['months']) ? byDayRule($by_day) : ''; $anchor_date = DateTime::createFromFormat('!Y-m-d', substr((string) $anchor, 0, 10)); $anchor_day = intval($date->format('j')); if ($anchor_date && intval($anchor_date->format('j')) > $anchor_day && $anchor_day === intval($date->format('t'))) { @@ -1827,6 +1829,10 @@ function recurringTicketNextRun($due, $frequency, $anchor = '', $after = '') { $month = intval($date->format('n')) + $step['months']; $year += intdiv($month - 1, 12); $month = ($month - 1) % 12 + 1; + if ($by_day !== '') { + $date = DateTime::createFromFormat('!Y-m-d', byDayDate($year, $month, $by_day)); + continue; + } $days_in_month = intval(date('t', mktime(0, 0, 0, $month, 1, $year))); $date->setDate($year, $month, min($anchor_day, $days_in_month)); } @@ -1845,6 +1851,10 @@ function recurringTicketCadenceText($row) { if (isset($step['days'])) { return $step['days'] === 7 ? 'on ' . $next->format('l') . 's' : ($step['days'] === 14 ? 'every other ' . $next->format('l') : 'every three days'); } + $by_day = byDayText($row['recurring_ticket_by_day'] ?? ''); + if ($by_day !== '') { + return 'on ' . $by_day . ($frequency === 'Annually' ? ' of ' . $next->format('F') : ''); + } $day = intval($next->format('j')); $start = DateTime::createFromFormat('!Y-m-d', substr((string) ($row['recurring_ticket_start_date'] ?? ''), 0, 10)); if ($start && intval($start->format('j')) > $day && $day === intval($next->format('t'))) { @@ -1997,7 +2007,7 @@ function recurringTicketRunNow($row, $by) { $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))); + $next_run = recurringTicketNextRun($due, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], max(date('Y-m-d'), substr($due, 0, 10)), $row['recurring_ticket_by_day'] ?? ''); mysqli_query($mysqli, "UPDATE recurring_tickets SET recurring_ticket_next_run = '$next_run' WHERE recurring_ticket_id = $recurring_ticket_id"); } return $ticket_id; @@ -2034,6 +2044,20 @@ function recurringTicketMonthBased($frequency) { return isset(RECURRING_TICKET_FREQUENCIES[recurringTicketFrequency($frequency)]['months']); } +/* + * The weekday it repeats on (functions/by_day.php), as SQL for recurring_ticket_by_day - NULL is the + * same date each time. $posted is the Repeats on choice when one was sent (null when not), kept only + * when $date - the first or next run - falls on it; without one the rule it had ($current) follows the + * run to $date. Only month-based repeats have one. + */ +function recurringTicketByDaySql($frequency, $date, $posted, $current = '') { + if (!recurringTicketMonthBased($frequency)) { + return 'NULL'; + } + $rule = $posted !== null ? byDayForDate($posted, $date) : byDayFollow($current, $date); + return $rule !== '' ? "'$rule'" : 'NULL'; +} + /* * 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 - @@ -2159,7 +2183,7 @@ function recurringTicketUpcoming($row, $count = 3) { } $runs[] = $date; while (count($runs) < $count) { - $date = recurringTicketNextRun($date, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], $date); + $date = recurringTicketNextRun($date, $row['recurring_ticket_frequency'], $row['recurring_ticket_start_date'], $date, $row['recurring_ticket_by_day'] ?? ''); $runs[] = $date; } return $runs; diff --git a/js/repeat_on.js b/js/repeat_on.js new file mode 100644 index 000000000..648616097 --- /dev/null +++ b/js/repeat_on.js @@ -0,0 +1,110 @@ +/** + * The Repeats on choice for monthly and yearly repeats (byDayField() in functions/by_day.php): + * "On the 21st", or "On the third Wednesday" / "On the last Wednesday", worked out from the date + * picked. It shows only for the month-based frequencies, and follows the date as it changes - + * keeping the choice when the new date still offers it, the last staying the last when it can. + * + * Markup: