diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a500d634..1323c32a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,12 +17,14 @@ If you manage other ITFlow installs, the manager and its instances can be update - Managed Instances: how much each instance is used. Its History card has a Usage part - tickets opened and resolved and those that came in by email, replies and notes by its agents, how many agents signed in each day and over the last 30 days, client portal sign-ins, invoices made and payments recorded, email sent and failed, and API calls with the keys that made the most of them - each day as the instance counts it, by its own date. The list has a Last 30 days column - tickets opened, how many of its agents signed in and when one last did, and API calls - and sorting by it puts the ones hardly used first. Only counts are sent, never what any of them say, and Managed By on the instance says so. - Managed Instances: an instance's page has an Agents card - who holds its seats, with each agent's name, email, role, whether they sign in with MFA and when they last signed in, then the invites waiting and the day each runs out. API accounts are marked. The support user takes no seat and isn't listed. Managed By, on the instance, lists this among what it tells its manager. - Managed Instances: errors logged on an instance now say which categories they were logged under, in its health line and under Errors today, where the count and each category sign you in to it as support on its App Logs, showing just those errors. Only how many there are under each category is sent - never what an error says, which can hold a client's email address or a ticket's subject. +- Payment reminders: a client with more than one late invoice gets one reminder for all of them, instead of one for each invoice on its own dates. It goes on the days of their oldest late invoice, on your reminder schedule, and lists everything they owe - each invoice with its link, the late ones marked, and the total - with the statement PDF attached when reminder emails attach PDFs. Texts send one reminder the same way. An invoice that goes late in between is in the next one, and an invoice's page shows when that is. A client with just one late invoice gets that invoice's own reminder, as before, and reminders before and on the due date are still one per invoice. When the monthly statement falls on the same day, the reminder goes in its place. ### Bug Fixes - Managed Instances: a manager behind a web application firewall - ModSecurity with the OWASP Core Rule Set, say - could answer an instance's check-ins with 403, as the cron command and error text in its report looked like an attack, and the instance's Managed By page said "The manager answered 403". Check-ins are now sent encoded, so nothing needs excluding. An instance sends them that way once its manager says it reads them, and a manager still reads a plain check-in, so either side can be updated first. - Racks: on a rack's drawing, clicking an asset opens its page, and the pen for editing it there - to move it or take it out of the rack - only showed while you pointed at it, at the far right. It was easy to miss, and on a touch screen it never showed. The pen is now always on each asset, in a holder's slot too when the slot is wide enough, and an asset's own page has Edit or remove under Rack, in Where & who. - Interfaces: adding several ports at once dropped the space at the end of the name before the number, so Port 01, Port 02 were made as Port01, Port02 - though the window showed them with the space. They are now made as the window shows them. +- Statements: an invoice marked Paid whose payments came to less than its total was listed as still owed. A Paid invoice now counts as settled, as it does everywhere else. ### Developer Updates @@ -40,6 +42,7 @@ If you manage other ITFlow installs, the manager and its instances can be update - Usage: `managedUsage()` counts the instance's today and yesterday, by its own date, with a `GROUP BY` of the day each - `tickets_opened` and `tickets_email` (`ticket_created_at`, `ticket_source = 'Email'`), `tickets_resolved`, `replies` (`ticket_reply_by > 0` and not `Client`), `invoices` (`invoice_created_at`), `payments` (`payment_created_at`), `agent_signins` (distinct `Login` `Success` log users, not the support user), `portal_signins` (`Client Login` `Success`), `emails_sent` and `emails_failed` (`email_queue` status 3 by `email_sent_at`, 2 by `email_failed_at`), and `api_calls` with `api_keys` - the ten keys' names with most calls, from `api_key_usage` - and `agents_30d`. A count that can't be made is left out. `managedReport()` sends it as `usage` (`days`, `agents_30d`, `measured_at`), counted at most every ten minutes and kept in `config_managed.usage` meanwhile. - Database 4.2.0: `managed_instance_stats` gets a column for each of `MANAGED_USAGE_FIGURES`, `_api_keys` (JSON) and `_agents_30d`, all NULL for a day nothing was reported. Re-runnable. `managedStatsRecord()` writes each of the instance's days onto the row of the same date, when it is there and within three days, and `_agents_30d` onto today's; `managedUsageReady()` guards it. `managedInstanceHistory()` adds each day's figures, `usage` (their totals, or null), `api_keys` and `agents_30d`, and the weekly view adds the figures up - `agent_signins` taking the week's highest day. - `admin/managed_instances.php` reads each instance's last 30 days in one query, and sorts by tickets opened in them as `usage_tickets` - a sort key keeps to letters and underscores, as `filter_header.php` strips anything else. The Health column wraps, so the table fits. +- Payment reminders: `cron/nightly_tasks.php` gathers each client's late invoices and reminds them once, when `billingReminderOnDay()` is true for the oldest one's days late - `billingOverdueEmail()` from `billingStatement()` with two or more late, and the invoice's own reminder with one. Each invoice in it gets a `Reminder emailed` history line, so the once-a-day check still holds. `billingReminderNext()` returns `with_others` and counts late days from `billingReminderClientOldestDue()`. `smsClientOverdueNotify()` sends the combined text, and `billingStatementLines()` builds the invoice rows for statements and the combined reminder. ## [26.12.1] diff --git a/admin/settings_invoice.php b/admin/settings_invoice.php index 9c051c1e2..6a53c1b7b 100644 --- a/admin/settings_invoice.php +++ b/admin/settings_invoice.php @@ -99,7 +99,7 @@ echo settingsPageStart('invoice'); -
Reminders go . An invoice a recurring autopay charges on its due date isn't reminded before then.
+
Reminders go . An invoice a recurring autopay charges on its due date isn't reminded before then. A client with more than one invoice late gets one reminder listing all they owe, on the days of the oldest.
diff --git a/agent/invoice.php b/agent/invoice.php index c1a1cf8d5..cbba9fab6 100644 --- a/agent/invoice.php +++ b/agent/invoice.php @@ -337,7 +337,7 @@ echo agentBannersHtml($client_id); Off for - Next - + Next - No more on the schedule diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index e54bd38b2..efc825ad9 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -502,15 +502,38 @@ while ($row = mysqli_fetch_assoc($sql_resolved_tickets_to_close)) { /* * Payment reminders, on the schedule in the invoice settings (functions/billing_email.php, - * billingReminderRules()): each open invoice whose day it is - before, on or after its due - * date - gets one, to the client's primary and billing contacts, unless the client is left - * out of reminders. One a recurring autopay will charge on its due date isn't reminded - * before then. Agents hear about each one late, on its reminder days, and the late fee - * still comes every 30 days late. At most one of each a day, however often this runs. + * billingReminderRules()), to the client's primary and billing contacts, unless the client is + * left out of reminders. Before and on its due date each invoice has its own; one a recurring + * autopay will charge on its due date isn't reminded before then. Once they are late, a + * client's invoices are reminded together: on the days of the oldest late one, one email lists + * everything they owe - or that invoice's own reminder, when it is the only one late. Agents + * hear about each one late, on its own reminder days, and the late fee still comes every 30 + * days late. At most one of each a day, however often this runs. */ $reminder_rules = billingReminderRules(true); +$reminded_clients = []; if ($reminder_rules['enabled']) { + // One invoice's own reminder - emailed, texted, and written in its history + $remind_invoice = function (array $invoice, int $days, array $recipients) use ($reminder_rules) { + [$subject, $email] = billingInvoiceEmail($invoice, ['kind' => 'reminder']); + $attach = []; + if ($reminder_rules['attach_pdf'] && ($file = billingEmailPdf(billingPdf('invoice', $invoice)))) { + $attach[] = $file; + } + $sent = billingEmailQueue($recipients, $subject, $email, ['attach' => $attach]); + // Texted too, in the morning, to those of them who agreed to texts (functions/sms.php) + $texted = smsInvoiceNotify($invoice, 'reminder', $recipients); + billingLog('invoice', intval($invoice['invoice_id']), $invoice['invoice_status'], 'Reminder emailed to ' . implode(', ', $sent) . ' - ' . billingReminderWhen($days) . ($texted ? ' - and texted to ' . implode(', ', $texted) : '')); + }; + // Reminded already today, or tried and couldn't be + $reminded_today = function (int $invoice_id) { + return cronInvoiceHistoryToday($invoice_id, 'Reminder emailed') || cronInvoiceHistoryToday($invoice_id, 'Reminder not sent') || cronInvoiceHistoryToday($invoice_id, 'Cron Emailed Overdue Invoice'); + }; + + // Late invoices by client, oldest first - reminded together below + $late_invoices = []; + $earliest = min(0, $reminder_rules['days'] ? min($reminder_rules['days']) : 0); $sql_reminders = mysqli_query($mysqli, "SELECT invoice_id, DATEDIFF(CURDATE(), invoice_due) AS days_late, client_reminders, invoice_recurring_invoice_id > 0 AND EXISTS (SELECT 1 FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = invoice_recurring_invoice_id) AS autopay @@ -546,17 +569,21 @@ if ($reminder_rules['enabled']) { } } + if ($days > 0) { + $late_invoices[intval($invoice['client_id'])][] = ['invoice' => $invoice, 'days' => $days, 'reminders' => intval($row['client_reminders'])]; + } + if (!billingReminderOnDay($days, $reminder_rules)) { continue; } if ($days > 0) { appNotify("Invoice Overdue", escapeSql("Invoice $number for {$invoice['client_name']} with a balance of " . billingMoney($balance, $invoice['invoice_currency_code']) . " is overdue by $days days"), "/agent/invoice.php?invoice_id=$invoice_id", intval($invoice['client_id'])); + continue; } - // Left out, charged by autopay on the day, already reminded today, or no mail - if (!intval($row['client_reminders']) || ($days <= 0 && intval($row['autopay'])) || empty($config_smtp_provider) - || cronInvoiceHistoryToday($invoice_id, 'Reminder emailed') || cronInvoiceHistoryToday($invoice_id, 'Reminder not sent') || cronInvoiceHistoryToday($invoice_id, 'Cron Emailed Overdue Invoice')) { + // Before or on its due date - left out, charged by autopay on the day, already reminded today, or no mail + if (!intval($row['client_reminders']) || intval($row['autopay']) || empty($config_smtp_provider) || $reminded_today($invoice_id)) { continue; } @@ -565,15 +592,52 @@ if ($reminder_rules['enabled']) { billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Reminder not sent - no primary or billing contact with an email address'); continue; } - [$subject, $email] = billingInvoiceEmail($invoice, ['kind' => 'reminder']); + $remind_invoice($invoice, $days, $recipients); + } + + // Late: one reminder a client, on the days of its oldest late invoice, listing all they owe + foreach ($late_invoices as $client_id => $invoices) { + $oldest_days = max(array_column($invoices, 'days')); + if (!billingReminderOnDay($oldest_days, $reminder_rules) || !$invoices[0]['reminders'] || empty($config_smtp_provider)) { + continue; + } + foreach ($invoices as $late) { + if ($reminded_today(intval($late['invoice']['invoice_id']))) { + continue 2; + } + } + $recipients = billingEmailRecipients($client_id); + if (!$recipients) { + foreach ($invoices as $late) { + billingLog('invoice', intval($late['invoice']['invoice_id']), $late['invoice']['invoice_status'], 'Reminder not sent - no primary or billing contact with an email address'); + } + continue; + } + + // Just the one late - its own reminder, as before + $statement = count($invoices) > 1 ? billingStatement($client_id) : null; + $statement_late = $statement ? count(array_filter($statement['invoices'], function ($invoice) { + return $invoice['balance'] > 0 && $invoice['days'] > 0; + })) : 0; + if ($statement_late < 2) { + $remind_invoice($invoices[0]['invoice'], $invoices[0]['days'], $recipients); + continue; + } + + [$subject, $email] = billingOverdueEmail($statement); $attach = []; - if ($reminder_rules['attach_pdf'] && ($file = billingEmailPdf(billingPdf('invoice', $invoice)))) { + if ($reminder_rules['attach_pdf'] && ($file = billingEmailPdf(billingStatementPdf($statement)))) { $attach[] = $file; } $sent = billingEmailQueue($recipients, $subject, $email, ['attach' => $attach]); - // Texted too, in the morning, to those of them who agreed to texts (functions/sms.php) - $texted = smsInvoiceNotify($invoice, 'reminder', $recipients); - billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Reminder emailed to ' . implode(', ', $sent) . ' - ' . billingReminderWhen($days) . ($texted ? ' - and texted to ' . implode(', ', $texted) : '')); + $texted = smsClientOverdueNotify($statement, $recipients); + $others = count($invoices) - 1; + foreach ($invoices as $late) { + billingLog('invoice', intval($late['invoice']['invoice_id']), $late['invoice']['invoice_status'], 'Reminder emailed to ' . implode(', ', $sent) . ' - ' . billingReminderWhen($late['days']) + . ", in one reminder with the client's $others other late invoice" . ($others === 1 ? '' : 's') . ($texted ? ' - and texted to ' . implode(', ', $texted) : '')); + } + // It lists all they owe, so no monthly statement as well today + $reminded_clients[$client_id] = true; } // Statements each month, on the day in the invoice settings, to every client with a balance @@ -584,8 +648,11 @@ if ($reminder_rules['enabled']) { while ($row = mysqli_fetch_assoc($sql_statements)) { $client_id = intval($row['client_id']); $already = mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM logs WHERE log_type = 'Client' AND log_action = 'Statement' AND log_client_id = $client_id AND log_created_at >= CURDATE() LIMIT 1")); + if ($already || isset($reminded_clients[$client_id])) { + continue; + } $statement = billingStatement($client_id); - if ($already || $statement['total'] <= 0) { + if ($statement['total'] <= 0) { continue; } $sent = billingStatementSend($statement, null, ['attach' => $reminder_rules['attach_pdf']]); diff --git a/functions/billing_email.php b/functions/billing_email.php index f9bf5a7d7..afdf198ac 100644 --- a/functions/billing_email.php +++ b/functions/billing_email.php @@ -111,9 +111,11 @@ function billingReminderScheduleText(?array $rules = null) { /** * When an invoice's next reminder goes, from tomorrow on: ['date' => Y-m-d, - * 'days' => days from its due date], or null - none on the schedule, or - * reminders are off. With $late_only, none before it is late - autopay - * charges it on the day. + * 'days' => days from its due date, 'with_others' => in the one email for + * the client's late invoices, on the days of an older one], or null - none + * on the schedule, or reminders are off. With $late_only, none before it is + * late - autopay charges it on the day. Before it is late it has reminders + * of its own; once it is late, the client's oldest late invoice sets the days. */ function billingReminderNext(array $invoice, ?array $rules = null, $late_only = false) { $rules = $rules ?? billingReminderRules(); @@ -127,15 +129,36 @@ function billingReminderNext(array $invoice, ?array $rules = null, $late_only = if ($late_only) { $from = max($from, 1); } + // How many days before this one the client's oldest invoice still owed was due - 0 when it is this one + $oldest = billingReminderClientOldestDue(intval($invoice['invoice_client_id'] ?? 0), $due); + $offset = intval((new DateTime($oldest))->diff($due_date)->format('%r%a')); for ($days = $from; $days <= $from + 400; $days++) { - if (billingReminderOnDay($days, $rules)) { + if (billingReminderOnDay($days > 0 ? $days + $offset : $days, $rules)) { $date = (clone $due_date)->modify(($days >= 0 ? '+' : '') . $days . ' days'); - return ['date' => $date->format('Y-m-d'), 'days' => $days]; + return ['date' => $date->format('Y-m-d'), 'days' => $days, 'with_others' => $days > 0 && $offset > 0]; } } return null; } +/** + * The due date of a client's oldest invoice still owed (sent, not paid in + * full), or $due when none is older - its days late set when the client's + * late invoices are reminded, all in one email (cron/nightly_tasks.php). + */ +function billingReminderClientOldestDue($client_id, $due) { + global $mysqli; + $client_id = intval($client_id); + if (!$client_id) { + return $due; + } + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT MIN(invoice_due) FROM invoices + WHERE invoice_client_id = $client_id AND invoice_status IN ('Sent', 'Viewed', 'Partial') AND invoice_due IS NOT NULL + AND ROUND(invoice_amount - COALESCE((SELECT SUM(payment_amount) FROM payments WHERE payment_invoice_id = invoice_id), 0), 2) > 0")); + $oldest = substr((string) ($row[0] ?? ''), 0, 10); + return preg_match('/^\d{4}-\d{2}-\d{2}$/', $oldest) && $oldest < $due ? $oldest : $due; +} + /** Will a recurring autopay charge this invoice on its due date? Then it isn't reminded before. */ function billingReminderAutopay(array $invoice) { global $mysqli; @@ -674,6 +697,10 @@ function billingStatement($client_id, $from = '', $to = '', $include_paid = fals $today = strtotime(date('Y-m-d')); while ($row = mysqli_fetch_assoc($sql)) { $row['balance'] = round(floatval($row['invoice_amount']) - floatval($row['paid']), 2); + // One marked paid is settled, whatever its payments come to - as everywhere else (invoiceState()) + if ($row['invoice_status'] === 'Paid') { + $row['balance'] = 0.0; + } if ($row['balance'] <= 0 && !$include_paid) { continue; } @@ -707,10 +734,8 @@ function billingStatementPdf(array $statement) { return billingStatementPdfRender($statement); } -/** A statement email - [subject, email]. $opts: note. */ -function billingStatementEmail(array $statement, array $opts = []) { - $currency = $statement['currency']; - $company = billingCompany(); +/** A statement's invoices as email lines - each linked, how late, its balance. */ +function billingStatementLines(array $statement) { $rows = []; foreach ($statement['invoices'] as $invoice) { $late = $invoice['balance'] > 0 && $invoice['days'] > 0; @@ -718,9 +743,16 @@ function billingStatementEmail(array $statement, array $opts = []) { ['text' => billingNumber('invoice', $invoice), 'url' => billingGuestUrl('invoice', $invoice)], billingEmailDate($invoice['invoice_date']), ['text' => billingEmailDate($invoice['invoice_due']) . ($late ? ' (' . $invoice['days'] . 'd late)' : ''), 'tone' => $late ? 'danger' : ''], - ['text' => $invoice['balance'] > 0 ? billingMoney($invoice['balance'], $currency) : 'Paid', 'tone' => $invoice['balance'] > 0 ? '' : 'success'], + ['text' => $invoice['balance'] > 0 ? billingMoney($invoice['balance'], $statement['currency']) : 'Paid', 'tone' => $invoice['balance'] > 0 ? '' : 'success'], ]; } + return ['head' => ['Invoice', 'Date', 'Due', 'Balance'], 'align' => ['left', 'left', 'left', 'right'], 'rows' => $rows]; +} + +/** A statement email - [subject, email]. $opts: note. */ +function billingStatementEmail(array $statement, array $opts = []) { + $currency = $statement['currency']; + $company = billingCompany(); $summary = ['Statement date' => billingEmailDate(date('Y-m-d')), 'Period' => ucfirst(billingStatementPeriod($statement)), 'Open invoices' => (string) count(array_filter($statement['invoices'], function ($invoice) { return $invoice['balance'] > 0; }))]; @@ -733,12 +765,42 @@ function billingStatementEmail(array $statement, array $opts = []) { 'intro' => ['Here is your statement for ' . $statement['client']['client_name'] . ', ' . billingStatementPeriod($statement) . '.' . ($statement['total'] > 0 ? ' Open an invoice to view' . (billingOnlinePayments() ? ' or pay' : '') . ' it.' : ' Nothing is owed - thank you.')], 'note' => $opts['note'] ?? '', 'summary' => $summary, 'strong' => 'Total due', - 'lines' => ['head' => ['Invoice', 'Date', 'Due', 'Balance'], 'align' => ['left', 'left', 'left', 'right'], 'rows' => $rows], + 'lines' => billingStatementLines($statement), 'after' => ['Questions about your account? Reply to this email' . (!empty($company['phone_display']) ? ' or call us on ' . $company['phone_display'] : '') . '.'], 'footnote' => billingEmailFootnote($statement['client']['client_name']), ]]; } +/** + * One payment reminder for all of a client's late invoices - [subject, email]: + * how many are late and what they come to, how late the oldest is, then every + * invoice still owed with its link, the late ones marked. From + * billingStatement() for the client, with two or more of them late. + */ +function billingOverdueEmail(array $statement) { + $currency = $statement['currency']; + $company = billingCompany(); + $late = array_filter($statement['invoices'], function ($invoice) { + return $invoice['balance'] > 0 && $invoice['days'] > 0; + }); + $count = count($late); + $oldest = $late ? max(array_column($late, 'days')) : 0; + $overdue = billingMoney($statement['overdue'], $currency); + $summary = ['Invoices past due' => (string) $count, 'Oldest' => $oldest . ' day' . ($oldest === 1 ? '' : 's') . ' past due', 'Past due' => $overdue]; + if ($statement['total'] > $statement['overdue']) { + $summary['Not yet due'] = billingMoney($statement['total'] - $statement['overdue'], $currency); + $summary['Total owed'] = billingMoney($statement['total'], $currency); + } + return ["Overdue: $count invoices are past due, $overdue in all", [ + 'kind' => 'Payment reminder', 'tone' => 'danger', 'title' => "$count invoices past due", + 'intro' => ["$count invoices for " . $statement['client']['client_name'] . " are past due, with $overdue still outstanding - the oldest by $oldest day" . ($oldest === 1 ? '' : 's') . '. Please arrange payment as soon as you can. Open an invoice below to view' . (billingOnlinePayments() ? ' or pay' : '') . ' it.'], + 'summary' => $summary, 'strong' => 'Past due', + 'lines' => billingStatementLines($statement), + 'after' => ['If you have already paid, thank you, and please disregard this reminder. Questions? Reply to this email' . (!empty($company['phone_display']) ? ' or call us on ' . $company['phone_display'] : '') . '.'], + 'footnote' => billingEmailFootnote($statement['client']['client_name']), + ]]; +} + /** * Email a statement to a client's contacts (the defaults when $contact_ids * is null), with its PDF when $attach. The addresses it went to. diff --git a/functions/sms.php b/functions/sms.php index 899ec6b75..31b1ffd1b 100644 --- a/functions/sms.php +++ b/functions/sms.php @@ -1610,6 +1610,38 @@ function smsInvoiceNotify(array $invoice, string $kind, array $recipients): arra return $texted; } +/* + * The one reminder for a client's late invoices (billingOverdueEmail()), texted the same way - + * how many and what they come to, with the oldest one's link. $statement as billingStatement() + * gives it. Who it went to. + */ +function smsClientOverdueNotify(array $statement, array $recipients): array +{ + if (!smsReady() || !smsClientSettings()['config_sms_client_invoices']) { + return []; + } + $late = array_values(array_filter($statement['invoices'], function ($invoice) { + return $invoice['balance'] > 0 && $invoice['days'] > 0; + })); + if (!$late) { + return []; + } + usort($late, function ($a, $b) { + return $b['days'] <=> $a['days']; + }); + $oldest = $late[0]; + $text = smsCompanyName() . ': a reminder - ' . count($late) . ' invoices are past due, ' . billingMoney($statement['overdue'], $statement['currency']) . ' in all. The oldest, invoice ' + . billingNumber('invoice', $oldest) . ', is ' . $oldest['days'] . ' day' . ($oldest['days'] === 1 ? '' : 's') . ' overdue: ' . billingGuestUrl('invoice', $oldest); + $texted = []; + foreach ($recipients as $recipient) { + $contact = smsContactTextable(intval($recipient['id'] ?? 0)); + if ($contact && smsNotifyContact(intval($contact['contact_id']), $text, ['purpose' => 'invoice_reminder'])) { + $texted[] = $contact['contact_name'] . ' (' . smsNumberText($contact['number']) . ')'; + } + } + return $texted; +} + /* * Turn a contact's texts on or off - $by says how they agreed, for the record ("Alex Rivera, * with their say-so", "them, in the client portal"). Turned on by the contact themselves, a STOP