From 87c441b3b90a40583a19f06e5cd683683b90d00d Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 16 Oct 2026 17:12:10 -0400 Subject: [PATCH] Billing stage 5: payment reminders on a schedule set in Invoice Settings (days before, on and after the due date, then every N days until paid, with a client opt-out on the Billing tab and no reminder for autopay invoices until late), Send Reminder and next-reminder status on the invoice page, a message and PDF attachment in the invoice, quote and statement Send windows, a statement PDF with aging and an optional monthly statement run, a new look for invoice, quote, reminder, receipt, statement and team notice emails sent to primary and billing contacts, late fee added as a proper invoice line, fixes for the quote answered notice link and batch payment receipts, database 2.9.8 and changelog --- CHANGELOG.md | 39 +- admin/database_updates/2.9.8.php | 24 + admin/post/settings_invoice.php | 18 + admin/post/settings_notification.php | 5 +- admin/settings_invoice.php | 126 +++- admin/settings_notification.php | 11 +- agent/invoice.php | 29 + agent/invoices.php | 5 + agent/modals/client/client_add.php | 9 + agent/modals/client/client_edit.php | 12 +- agent/modals/client/client_statement.php | 56 +- agent/modals/invoice/invoice_email.php | 36 +- agent/modals/quote/quote_email.php | 16 + agent/post/client.php | 4 +- agent/post/client_model.php | 2 + agent/post/invoice.php | 408 +++--------- agent/post/payment.php | 219 +------ agent/post/quote.php | 155 +---- cron/nightly_tasks.php | 233 +++---- db.sql | 6 + functions.php | 1 + functions/billing.php | 39 +- functions/billing_email.php | 773 +++++++++++++++++++++++ functions/billing_pdf.php | 136 ++++ guest/guest_pay_invoice_stripe.php | 42 +- guest/guest_post.php | 28 +- 26 files changed, 1550 insertions(+), 882 deletions(-) create mode 100644 admin/database_updates/2.9.8.php create mode 100644 functions/billing_email.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 977ab7565..0a04f8077 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 2.9.7) in the same pass. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 2.9.8) in the same pass. Nothing else is required. -This is a big release, with eighteen database steps in one go, so take a backup before you update. +This is a big release, with nineteen database steps in one go, so take a backup before you update. The update also clears out data that deletes in older versions left behind, all of it pointing at something that no longer exists: @@ -19,6 +19,8 @@ The update also clears out data that deletes in older versions left behind, all It also gives every existing network a type (LAN, WAN, Guest and so on) guessed from its name or description, which you can change afterwards, and fills in the issue date, names covered and fingerprint of every certificate already on file. Invoices made from a quote before the update are linked to that quote, so each one shows where it came from. Products that ever had stock added keep tracking their stock, and the rest are set to ordered as needed (see Breaking Changes, Products). Their past stock changes are sorted into received, sold and returned from their notes, and linked to the invoice they name. No product becomes a client asset when it is sold until you give it an asset type (see New Features, Products). Each product's price history starts with the update, so lines on recurring invoices are only flagged as behind once their product's price changes. +Payment reminders keep the schedule they had: 1 and 30 days late, then every 30 days until the invoice is paid. If reminders were on, they stay on, and every client is included. The schedule can now be changed in Admin > Settings > Invoice (see Breaking Changes, Billing emails). Monthly statements start switched off. + If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below. ### Breaking Changes and Notes @@ -44,6 +46,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Invoice and quote PDFs have a new layout, and print on Letter paper in the United States and Canada and A4 elsewhere. They were always A4. - The recurring invoices list no longer has a date filter. It filtered by the date each one was created. - Links to the invoices list with `?status=Draft`, `Unpaid` or `Overdue` still work, and `Paid` and `Cancelled` are new. +- Billing emails: + - Payment reminders moved from Admin > Settings > Notifications to Admin > Settings > Invoice, under Reminders and Statements. Saving the Notifications page no longer changes them. + - Reminders and payment receipts go to the client's primary and billing contacts, once per address. They used to go to the primary contact only. + - An invoice on a recurring invoice with autopay is not reminded before or on its due date, as the card is charged that day. It is reminded once it is late. + - Invoice, quote, reminder, receipt and statement emails have a new look, with the invoice, quote or statement attached as a PDF. Attaching can be turned off in Invoice Settings, or for one email in its Send window. The subjects changed too, such as "Invoice INV-12 from PittPC", "Overdue: invoice INV-12 is 30 days past due" and "Payment received for invoice INV-12". If you filter mail on the old subjects ("Overdue Invoice INV-12", "Quote [scope]", "Account Statement - Client"), update the filters. + - The late fee is now a line on the invoice like any other, and the total is worked out from the lines. It still comes every 30 days late, while reminders are on. - Recurring invoices: - The nightly run also bills a run it missed by up to 7 days, for nights the cron didn't run. It used to bill only on the day itself. A recurring invoice further behind than that is still left for you to look at. - Invoice Now bills the next run early, and the schedule moves one period on from that run, so the invoice takes its place. It used to restart the schedule from today: pressing it on the 16th for a run due on the 1st moved every later invoice to the 16th. @@ -244,6 +252,18 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Start Billing on an accepted quote: the one-time lines go on a draft invoice, dated as you choose and due on the client's terms. Each month, quarter or year part goes on a new recurring invoice from the date you pick (the first of next month to start), with its invoices emailed as they are made or left as drafts, or is added to one of the client's recurring invoices billed as often. Switch on Bill the first month on the invoice now to put the first period on the invoice too. A quote with only one-time lines keeps Make Invoice. - The quote shows what it was invoiced as, with a link to each invoice and recurring invoice, including any it added lines to. The invoice and the recurring invoices link back to the quote, and each history says what happened. - The quotes list adds the monthly part to each row and to its totals. Search, the client portal's quotes, the Send and Copy windows, the quote email and the client's Accept all show the amounts by part. The quotes export has a Monthly column, and the client export a monthly amount on quotes and how each quote line is billed. + - **Reminders and statements**, in Admin > Settings > Invoice under Reminders and Statements: + - Set when reminders go: any days before the due date, on the due date, any days late, then every so many days until the invoice is paid. The schedule is shown in words as you type, such as "3 days before it is due, on the due date, 7 and 14 days late, then every 30 days until it is paid". + - A reminder before the due date is a friendly one. Once the invoice is late it is firmer, and says how many days late it is. + - A client can be left out of reminders and monthly statements with the switch on the Billing tab of its Edit window. + - The invoice page's payment card shows how many reminders have gone and when the last one went, and when the next one goes, or why none will. Send Reminder in the More menu sends one now. + - Monthly statements: switch them on and pick the day of the month (the 1st to the 28th). Each client with a balance gets one, unless left out of reminders. + - The nightly run sends at most one reminder a day for each invoice and one statement a day for each client, however often it runs. The invoice's history says who each reminder went to and how late the invoice was. + - **Statements**: Send Statement attaches the statement as a PDF. It shows what is owed by age (current, 1-30, 31-60, 61-90 and over 90 days) and every invoice in the period with what was paid and what is left. Download PDF in the window follows the dates and options you pick, and Statement PDF is in the invoice list's menu when it is showing one client. + - **Send windows**: the invoice, quote and statement windows take a message of your own, which goes in the email above the document, and a switch to attach the PDF. On an invoice that is still owed, the invoice window can send the invoice or a reminder. + - **Billing emails** have a new look: your logo, what is owed and by when in a summary, the message if there is one, and a button to view and pay the invoice or accept the quote. This covers invoices, quotes, reminders, payment receipts and statements, and the notices to your team when a quote is accepted or declined or a payment is made online. + - Receipts show the amount, method, reference and what is still to pay. A batch payment's receipt lists each invoice it was applied to. + - Each email's entry in the history says who it went to and whether the PDF went with it. - **Products** (rebuilt) - Each product or service records what it costs you, so its margin shows, along with the vendor you buy it from, their part number and notes for agents only. - How it is billed by default: one time, monthly, quarterly or yearly, and per user or per device. Picking it on a quote fills in Billed. On a recurring invoice, per user or per device takes the quantity from the client's count. @@ -457,6 +477,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Billing: an invoice made from a quote was due counting from today instead of the invoice date, and with no terms when the client had none set. - Billing: the client's view of a quote offered Accept on a viewed quote that had run out, and the invoice and quote views put the browser's HTML into the history. - Billing: copying an invoice logged its old number with the prefix twice. +- Billing: the nightly late fee line was saved without its subtotal, and the invoice total was raised by hand instead of from its lines. +- Billing: the email telling your team a quote was accepted or declined linked to a page that doesn't exist. It now opens the quote. +- Billing: a batch payment's receipt went to the primary contact only, and sending it wrote a PHP warning. - Products: Restore in the archived list's bulk actions did nothing. Deleting a product left its stock records behind. - Products: Add Stock could record zero units, or link an expense that no longer existed. - Products: deleting an invoice did not put its stock back. Copying an invoice or making one from a quote lost the link to the product, so the copy took no stock and the product did not count it as sold. @@ -497,7 +520,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run ### Developer Updates -- Database 2.8.0 to 2.9.4, one file per step under `admin/database_updates/`, with `db.sql` matching 2.9.4: +- Database 2.8.0 to 2.9.8, one file per step under `admin/database_updates/`, with `db.sql` matching 2.9.8: - 2.8.0: `racks.rack_units_descending`, `rack_power_capacity` and `rack_photo_rear`. On `rack_units`: `unit_face`, `unit_full_depth`, `unit_type`, `unit_power_watts`, `unit_notes` and a `unit_asset_id` key. Unlinked items move from asset id 0 to NULL. - 2.8.1: `location_documents` and `location_files`. - 2.8.2: `vendor_tags` (tag type 6), and `vendor_contact_phone_country_code`, `vendor_contact_phone` and `vendor_contact_email`. @@ -528,6 +551,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - 2.9.5: `product_stock.stock_qty` becomes `decimal(15,2)`, with `stock_type` (`received`, `sold`, `returned`, `adjusted` or `written_off`, default `adjusted`), `stock_unit_cost`, `stock_invoice_id` (keyed) and `stock_user_id`. Existing rows take their invoice from a note ending "Invoice n" and their type from the sign and the note. `products.product_reorder_level` and `product_reorder_qty`. - 2.9.6: `products.product_asset_type` (one of the asset types, NULL for none), `product_make`, `product_model` and `product_warranty_months`. `assets.asset_product_id`, `asset_invoice_id` and `asset_invoice_item_id`, keyed on the product and the invoice. - 2.9.7: `product_prices` - a product's price and cost history: `price_old`, `price_new`, `price_cost_old`, `price_cost_new`, `price_source` (`edit`, `import` or `receive`), `price_user_id` and `price_product_id`, keyed. + - 2.9.8: `settings.config_invoice_reminder_days` ('1,30' - days from the due date, negative before it), `config_invoice_reminder_repeat` (30), `config_statement_monthly` (0), `config_statement_day` (1) and `config_billing_email_attach_pdf` (1), and `clients.client_reminders` (1). - New shared function files, loaded by `functions.php`: `functions/asset.php`, `asset_interface.php`, `certificate.php`, `client_overview.php`, `contact.php`, `credential.php`, `dashboard.php`, `links.php`, `location.php`, `notifications.php`, `project.php`, `rack.php`, `search.php`, `service.php`, `software.php`, `tags.php`, `ticket.php`, `ticket_fields.php`, `user.php` and `vendor.php`. They hold the queries and rules, so the pages, the API and cron share one definition. - Removed post models: `agent/post/{asset_interface,certificate,credential,domain,event,location,network_ip,network,recurring_ticket,vendor}_model.php`, `admin/post/user_model.php` and `api/v1/certificates/certificate_model.php`. Their handlers call the shared functions above. Interface handlers moved to `agent/post/asset_interface.php`. - New scripts: `js/itflow_select.js`, `quick_pick.js`, `tag_picker.js`, `global_search.js`, `notifications.js`, `dashboard.js`, `client_overview.js`, `client_switcher.js`, `credentials.js` and `autosubmit.js`, and `agent/js/calendar.js`, `calendar_event_modal.js`, `files.js`, `interface_form.js`, `network_form.js`, `project_modal.js` and `ticket_schedule_modal.js`. @@ -634,6 +658,15 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `agent/modals/quote/quote_to_invoice.php` posts those fields. Quote lines carry `data-group`, with `tr.itflow-paper-group` headings in `includes/billing_paper.php`, and the Sortable in `js/billing_items.js` drags only `tr[data-item-id]`, within its group when the table is grouped. - `reportCsv()` writes a totals row as given, without the column's `csv` function, which read fields a totals row doesn't have. The quotes export takes `quote_monthly_amount`. - Removed: `add_invoice_item`, `edit_invoice_item`, `delete_invoice_item`, `add_quote_item`, `edit_quote_item`, `delete_quote_item`, `add_recurring_invoice_item`, `edit_recurring_invoice_item`, `delete_recurring_invoice_item` and `link_invoice_to_ticket` (it wrote a column that does not exist), `update_invoice_items_order`, `update_quote_items_order` and `update_recurring_invoice_items_order` in `agent/ajax.php`, `agent/modals/invoice/invoice_item_edit.php`, `agent/modals/quote/quote_item_edit.php`, `agent/modals/recurring_invoice/recurring_invoice_item_edit.php`, `guest/guest_quote_upload_file_modal.php` and `js/product_autocomplete.js`. +- Billing emails, in `functions/billing_email.php` (loaded by `functions.php`): + - Schedule: `billingReminderRules($fresh)` reads the 2.9.8 settings once a request, falling back to 1 and 30 days late before 2.9.8 is applied, so they are not in `load_global_settings.php`. Also `billingReminderDaysParse()`, `billingReminderOnDay($days, $rules)` (days late, negative before the due date: a listed day, or every `repeat` days after the last listed day), `billingReminderScheduleText()` (the settings page's script mirrors it), `billingReminderNext($invoice, $rules, $late_only)`, `billingReminderAutopay()` and `billingReminderWhen()`. + - Layout: `billingEmailHtml($email)` draws every billing email from one array (`kind`, `tone`, `title`, `greeting`, `intro`, `note`, `summary`, `lines`, `button`, `after`, `footnote`) as inline-styled tables, for mail clients. The templates return `[$subject, $email]`: `billingInvoiceEmail($invoice, $opts)` (`kind` invoice or reminder, and `note`; a paid invoice gets the receipt), `billingQuoteEmail()`, `billingPaymentEmail($applied, $payment)`, `billingStatementEmail()` and `billingNotifyEmail()`. + - Sending: `billingEmailRecipients($client_id, $contact_ids, $type)` returns the client's own contacts with an address, once each, or the defaults from `documentDefaultContactFilterSql()` when `$contact_ids` is null. `billingEmailQueue($recipients, $subject, $email, $opts)` (`from` and `attach`) queues one row each and returns "Name (email)" labels for the history. Also `billingEmailFrom()` and `billingEmailReady()`. + - Attachments: `billingEmailPdf($pdf)` writes the PDF under `uploads/tmp/billing_mail//` for the queue's attachment manifest, and `billingEmailPdfCleanup($days)` removes folders older than that. The nightly run calls it with 7. + - Receipts and notices: `billingPaymentSend($invoice_id, $amount, $payment, $notify)` is used by `add_payment`, saved-card and guest Stripe payments and cron autopay. With `$notify` it also emails `config_invoice_paid_notification_email` through `billingPaymentNotify()`. `guest/guest_post.php` calls `billingQuoteAnsweredNotify($quote_id, $accepted)`. + - Statements: `billingStatement($client_id, $from, $to, $include_paid)` returns the invoices with paid, balance and days late, the total, what is overdue and the `aging` buckets. Also `billingStatementPeriod()`, `billingStatementPdf()` and `billingStatementSend($statement, $contact_ids, $opts)`. The drawing is `billingStatementPdfRender()` in `functions/billing_pdf.php`, where `billingPdfConfig()` now loads the footer settings when the globals are not set, as in cron. + - Handlers: `email_invoice` takes `kind` (`invoice` or `reminder`), `note` (up to 2000 characters) and `attach_pdf`, and `email_quote` and `send_statement` take `note` and `attach_pdf`. New GET `export_client_statement_pdf=client_id`, with `dtf`, `dtt` and `include_paid`. `edit_invoice_settings` takes `config_send_invoice_reminders`, `reminder_before`, `reminder_on_due`, `reminder_after`, `reminder_repeat`, `config_statement_monthly`, `config_statement_day` and `config_billing_email_attach_pdf`. `edit_notification_settings` no longer writes `config_send_invoice_reminders`. Client add and edit take `reminders` with a hidden `reminders_field`, and a form without the field leaves `client_reminders` alone. + - `agent/modals/invoice/invoice_email.php?kind=reminder` opens on the reminder. Recurring auto-send, the batch payment receipt and the nightly reminders use the same functions. The nightly late fee goes through `billingItemSave()`. Reminders write "Reminder emailed to ..." history, and today's "Cron Emailed Overdue Invoice" entries from before the update still count as sent. Monthly statements are logged with `logAudit("Client", "Statement", ...)`, which is also what stops a second one the same day. - Products: - `functions/products.php` (loaded by `functions.php`): `productTypes()`, `productSeatSources()`, `productBilledText()`, `productMargin()` (percent of the price, null without a cost), `productMarginPill()`, `productStockSql()`, `productTile()`, `productRow()` (with category, tax, vendor and stock), `productVendors()`, `productCopy()`, `productDelete()` (with its stock), `productUsage()` (recurring, open quotes, invoice lines, sold over 12 months and a month's recurring, scoped with `clientScopeSql()`), `productHistory()` and `productStockMoves()`. - `productSave($in, $product_id, &$error)` is the one path that writes a product - New, Edit, Copy, Import and notes. On an existing product only the keys given change. It validates the type, numbers, an Income category, the tax and one of our vendors, clears Counted when billed once and Track stock for a service. diff --git a/admin/database_updates/2.9.8.php b/admin/database_updates/2.9.8.php new file mode 100644 index 000000000..4ae53c3a1 --- /dev/null +++ b/admin/database_updates/2.9.8.php @@ -0,0 +1,24 @@ + 0 && $day <= 60; })), + !empty($_POST['reminder_on_due']) ? [0] : [], + array_filter(billingReminderDaysParse($_POST['reminder_after'] ?? ''), function ($day) { return $day > 0; }) + ); + $config_invoice_reminder_days = escapeSql(implode(',', billingReminderDaysParse(implode(',', $reminder_days)))); + $config_invoice_reminder_repeat = max(0, min(365, intval($_POST['reminder_repeat'] ?? 0))); + $config_statement_monthly = intval(!empty($_POST['config_statement_monthly'])); + $config_statement_day = max(1, min(28, intval($_POST['config_statement_day'] ?? 1))); + $config_billing_email_attach_pdf = intval(!empty($_POST['config_billing_email_attach_pdf'])); + + mysqli_query($mysqli,"UPDATE settings SET config_send_invoice_reminders = $config_send_invoice_reminders, config_invoice_reminder_days = '$config_invoice_reminder_days', + config_invoice_reminder_repeat = $config_invoice_reminder_repeat, config_statement_monthly = $config_statement_monthly, config_statement_day = $config_statement_day, + config_billing_email_attach_pdf = $config_billing_email_attach_pdf WHERE company_id = 1"); + mysqli_query($mysqli,"UPDATE settings SET config_time_increment = $config_time_increment, config_time_rounding = '$config_time_rounding', config_time_minimum = $config_time_minimum, config_time_item_name = '$config_time_item_name' WHERE company_id = 1"); mysqli_query($mysqli,"UPDATE settings SET config_invoice_prefix = '$config_invoice_prefix', config_invoice_next_number = $config_invoice_next_number, config_invoice_footer = '$config_invoice_footer', config_invoice_show_tax_id = $config_invoice_show_tax_id, config_invoice_late_fee_enable = $config_invoice_late_fee_enable, config_invoice_late_fee_percent = $config_invoice_late_fee_percent, config_invoice_paid_notification_email = '$config_invoice_paid_notification_email', config_recurring_invoice_prefix = '$config_recurring_invoice_prefix', config_recurring_invoice_next_number = $config_recurring_invoice_next_number WHERE company_id = 1"); diff --git a/admin/post/settings_notification.php b/admin/post/settings_notification.php index 52623ce92..02801ee51 100644 --- a/admin/post/settings_notification.php +++ b/admin/post/settings_notification.php @@ -6,15 +6,16 @@ if (isset($_POST['edit_notification_settings'])) { validateCSRFToken(); + // config_send_invoice_reminders is NOT set here either - reminders moved to Invoice Settings + // with their schedule, in 26.11. // config_enable_cron is NOT set here - the master cron switch moved to Maintenance > Cron // in 26.08. Leaving it in this UPDATE would switch cron off every time somebody saved // this form, because the checkbox that fed it is gone from the page. $config_enable_alert_domain_expire = intval($_POST['config_enable_alert_domain_expire'] ?? 0); - $config_send_invoice_reminders = intval($_POST['config_send_invoice_reminders'] ?? 0); $config_recurring_auto_send_invoice = intval($_POST['config_recurring_auto_send_invoice'] ?? 0); $config_ticket_client_general_notifications = intval($_POST['config_ticket_client_general_notifications'] ?? 0); - mysqli_query($mysqli,"UPDATE settings SET config_send_invoice_reminders = $config_send_invoice_reminders, config_recurring_auto_send_invoice = $config_recurring_auto_send_invoice, config_enable_alert_domain_expire = $config_enable_alert_domain_expire, config_ticket_client_general_notifications = $config_ticket_client_general_notifications WHERE company_id = 1"); + mysqli_query($mysqli,"UPDATE settings SET config_recurring_auto_send_invoice = $config_recurring_auto_send_invoice, config_enable_alert_domain_expire = $config_enable_alert_domain_expire, config_ticket_client_general_notifications = $config_ticket_client_general_notifications WHERE company_id = 1"); logAudit("Settings", "Edit", "$session_name edited notification settings"); diff --git a/admin/settings_invoice.php b/admin/settings_invoice.php index 19c30a811..fcb33d765 100644 --- a/admin/settings_invoice.php +++ b/admin/settings_invoice.php @@ -57,7 +57,7 @@ require_once "includes/inc_all_admin.php"; - We recommend updating the invoice footer to include policies on your late charges. This will be applied every 30 days after the invoice Due Date. + We recommend updating the invoice footer to include policies on your late charges. It is added as a line every 30 days after the invoice's due date, while payment reminders are on.
@@ -70,6 +70,130 @@ require_once "includes/inc_all_admin.php";
+ 0; })); ?> +

Reminders and Statements

+

Payment reminders go to each client's primary and billing contacts while an invoice is still owed, with a button to view and pay it. A client can be left out of reminders and statements on the Billing tab of its Edit window. Late fees above come every 30 days late, while reminders are on.

+ +
+
+ data-reminder-input> + +
+
+ +
+
+ +
+ + + days +
+
+
+ +
+ + + days late +
+
+
+ +
+ + + days until paid +
+ 0 for no more after the last one. +
+
+
+ data-reminder-input> + +
+
+
+
Reminders go . An invoice a recurring autopay charges on its due date isn't reminded before then.
+
+
+ +
+
+
+ > + +
+ Their open invoices, how late each is and what is owed, as a PDF too. +
+
+
+ + +
+
+
+ +
+
+ > + +
+ The default in each Send window, and what reminders, statements and recurring invoices do. +
+ + + +
+

Recurring Invoice

diff --git a/admin/settings_notification.php b/admin/settings_notification.php index 0cb496542..9bddf375b 100644 --- a/admin/settings_notification.php +++ b/admin/settings_notification.php @@ -49,20 +49,17 @@ require_once "includes/inc_all_admin.php"; -
Invoice Reminders
+
Invoice Reminders and Statements
- (This will automatically dispatch a reminder email for the invoice to the primary contact's email every 30 days following the invoice's due date.) + (Reminders before and after an invoice's due date, and monthly statements, are set in Invoice Settings.) - -
- value="1" id="sendInvoiceRemindersSwitch"> - -
+ + diff --git a/agent/invoice.php b/agent/invoice.php index c8b3b1773..ec4f09fae 100644 --- a/agent/invoice.php +++ b/agent/invoice.php @@ -66,6 +66,13 @@ $hardware = $can_see_assets ? productInvoiceHardware($invoice_id) : []; $hardware_units = array_sum(array_column($hardware, 'units')); $hardware_to_add = $status === 'Cancelled' ? 0 : array_sum(array_column($hardware, 'to_add')); $can_add_assets = $hardware_to_add > 0 && lookupUserPermission('module_support') >= 2; +// Payment reminders - how many have gone, and when the next one goes (functions/billing_email.php) +$owed = in_array($state['state'], ['open', 'overdue'], true) && $status !== 'Draft'; +$reminder_rules = billingReminderRules(); +$reminders_sent = $owed ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(*) AS sent, MAX(history_created_at) AS last FROM history + WHERE history_invoice_id = $invoice_id AND (history_description LIKE 'Reminder emailed%' OR history_description LIKE 'Cron Emailed Overdue Invoice%')")) : null; +$client_reminders = intval(getFieldById('clients', $client_id, 'client_reminders') ?? 1); +$reminder_next = $owed && $client_reminders ? billingReminderNext($invoice, $reminder_rules, billingReminderAutopay($invoice)) : null; $csrf = $_SESSION['csrf_token']; // Made by a recurring invoice? @@ -212,6 +219,11 @@ $paper = [ View as Client + 0) { ?> + + Send Reminder... + + Send Again... @@ -281,6 +293,23 @@ $paper = [
Terms
days
+ +
Reminders
+
+ +
+ + Off - set in Invoice Settings + + Off for + + Next - + + No more on the schedule + +
+
+
Margin
diff --git a/agent/invoices.php b/agent/invoices.php index 6c3988b3f..7d552facf 100644 --- a/agent/invoices.php +++ b/agent/invoices.php @@ -199,6 +199,11 @@ $stat_money = function ($amount) use ($session_company_currency) { Send Statement
+ + + Statement PDF + + 0) { ?> diff --git a/agent/modals/client/client_add.php b/agent/modals/client/client_add.php index 2f5292c28..435cca7f1 100644 --- a/agent/modals/client/client_add.php +++ b/agent/modals/client/client_add.php @@ -313,6 +313,15 @@ ob_start();
+
+ +
+ + +
+ Emailed as set in Invoice Settings. Off, this client gets neither - invoices can still be sent by hand. +
+ diff --git a/agent/modals/client/client_edit.php b/agent/modals/client/client_edit.php index 627759851..40f2686fa 100644 --- a/agent/modals/client/client_edit.php +++ b/agent/modals/client/client_edit.php @@ -9,7 +9,7 @@ $client_id = intval($_GET['id']); enforceClientAccess(); $sql = mysqli_query($mysqli, "SELECT client_abbreviation, client_archived_at, client_created_at, client_lead, client_name, - client_net_terms, client_notes, client_rate, client_referral, client_tax_id_number, + client_net_terms, client_notes, client_rate, client_reminders, client_referral, client_tax_id_number, client_type, client_website FROM clients WHERE client_id = $client_id LIMIT 1"); $row = mysqli_fetch_assoc($sql); @@ -19,6 +19,7 @@ $client_type = escapeHtml($row['client_type']); $client_website = escapeHtml($row['client_website']); $client_referral = escapeHtml($row['client_referral']); $client_net_terms = intval($row['client_net_terms']); +$client_reminders = intval($row['client_reminders'] ?? 1); $client_tax_id_number = escapeHtml($row['client_tax_id_number']); $client_abbreviation = escapeHtml($row['client_abbreviation']); $client_rate = floatval($row['client_rate']); @@ -217,6 +218,15 @@ ob_start(); +
+ +
+ > + +
+ Emailed as set in Invoice Settings. Off, this client gets neither - invoices can still be sent by hand. +
+ diff --git a/agent/modals/client/client_statement.php b/agent/modals/client/client_statement.php index 12651d64e..2e94bb957 100644 --- a/agent/modals/client/client_statement.php +++ b/agent/modals/client/client_statement.php @@ -1,5 +1,11 @@ -
+ @@ -102,7 +108,7 @@ ob_start();
- +
Leave blank for all history @@ -110,14 +116,14 @@ ob_start();
- "> + " data-statement-option>
- +
+
+ Download PDF + +
Email Options
@@ -168,6 +178,17 @@ ob_start(); + +
+ + +
+ +
+ > + +
+ @@ -183,5 +204,32 @@ ob_start();
+ + - + 0 && in_array($doc['invoice_status'], invoiceOpenStatuses(), true); + $kind = $can_remind && ($_GET['kind'] ?? '') === 'reminder' ? 'reminder' : 'invoice'; + $reminder_when = $can_remind ? billingReminderWhen(-$doc_state['days']) : ''; ?> + +
+ > + + > + +
+
@@ -132,6 +155,17 @@ ob_start();
+ +
+ + +
+ +
+ > + +
+

This invoice is diff --git a/agent/modals/quote/quote_email.php b/agent/modals/quote/quote_email.php index d042230b5..d0688ac68 100644 --- a/agent/modals/quote/quote_email.php +++ b/agent/modals/quote/quote_email.php @@ -1,5 +1,10 @@ + +

+ + +
+ +
+ > + +
+

This quote is diff --git a/agent/post/client.php b/agent/post/client.php index afdcaa616..ea74817ce 100644 --- a/agent/post/client.php +++ b/agent/post/client.php @@ -39,7 +39,7 @@ if (isset($_POST['add_client'])) { $extended_log_description = ''; // Create client - mysqli_query($mysqli, "INSERT INTO clients SET client_name = '$name', client_type = '$type', client_website = '$website', client_referral = '$referral', client_rate = $rate, client_currency_code = '$session_company_currency', client_net_terms = $net_terms, client_tax_id_number = '$tax_id_number', client_lead = $lead, client_abbreviation = '$abbreviation', client_notes = '$notes', client_accessed_at = NOW()"); + mysqli_query($mysqli, "INSERT INTO clients SET client_name = '$name', client_type = '$type', client_website = '$website', client_referral = '$referral', client_rate = $rate, client_currency_code = '$session_company_currency', client_net_terms = $net_terms, client_reminders = " . ($reminders ?? 1) . ", client_tax_id_number = '$tax_id_number', client_lead = $lead, client_abbreviation = '$abbreviation', client_notes = '$notes', client_accessed_at = NOW()"); $client_id = mysqli_insert_id($mysqli); @@ -126,7 +126,7 @@ if (isset($_POST['edit_client'])) { enforceClientAccess(); // Update client - mysqli_query($mysqli, "UPDATE clients SET client_name = '$name', client_type = '$type', client_website = '$website', client_referral = '$referral', client_rate = $rate, client_net_terms = $net_terms, client_tax_id_number = '$tax_id_number', client_lead = $lead, client_abbreviation = '$abbreviation', client_notes = '$notes' WHERE client_id = $client_id"); + mysqli_query($mysqli, "UPDATE clients SET client_name = '$name', client_type = '$type', client_website = '$website', client_referral = '$referral', client_rate = $rate, client_net_terms = $net_terms" . ($reminders !== null ? ", client_reminders = $reminders" : '') . ", client_tax_id_number = '$tax_id_number', client_lead = $lead, client_abbreviation = '$abbreviation', client_notes = '$notes' WHERE client_id = $client_id"); // Create referral category if it doesn't exist $sql = mysqli_query($mysqli, "SELECT category_name FROM categories WHERE category_type = 'Referral' AND category_archived_at IS NULL AND category_name = '$referral'"); diff --git a/agent/post/client_model.php b/agent/post/client_model.php index 096cb1da4..311449bbf 100644 --- a/agent/post/client_model.php +++ b/agent/post/client_model.php @@ -14,3 +14,5 @@ if (empty($abbreviation)) { } $notes = escapeSql($_POST['notes'] ?? ''); $lead = intval($_POST['lead'] ?? 0); +// Reminders and statements - only when the Billing tab was on the form +$reminders = isset($_POST['reminders_field']) ? intval(!empty($_POST['reminders'])) : null; diff --git a/agent/post/invoice.php b/agent/post/invoice.php index 755b07015..afa172c0c 100644 --- a/agent/post/invoice.php +++ b/agent/post/invoice.php @@ -322,154 +322,59 @@ if (isset($_POST['email_invoice'])) { enforceUserPermission('module_sales', 2); - $invoice_id = intval($_POST['invoice_id']); - - $sql = mysqli_query($mysqli,"SELECT client_id, client_name, invoice_amount, invoice_currency_code, - invoice_date, invoice_due, invoice_id, invoice_number, invoice_prefix, invoice_scope, - invoice_status, invoice_url_key FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - WHERE invoice_id = $invoice_id" - ); - $row = mysqli_fetch_assoc($sql); - - $invoice_id = intval($row['invoice_id']); - $invoice_prefix = escapeSql($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_scope = escapeSql($row['invoice_scope']); - $invoice_status = escapeSql($row['invoice_status']); - $invoice_date = escapeSql(validateDate($row['invoice_date'])); - $invoice_due = escapeSql(validateDate($row['invoice_due'])); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_url_key = escapeSql($row['invoice_url_key']); - $invoice_currency_code = escapeSql($row['invoice_currency_code']); - $client_id = intval($row['client_id']); - $client_name = escapeSql($row['client_name']); + $invoice = billingRow('invoice', intval($_POST['invoice_id'] ?? 0)); + if (!$invoice) { + flashAlert('That invoice no longer exists.', 'error'); + redirect('invoices.php'); + } + $invoice_id = intval($invoice['invoice_id']); + $client_id = intval($invoice['client_id']); + $number = billingNumber('invoice', $invoice); enforceClientAccess(); - // Two ways in. Quick Send skips the modal and resolves the default - // recipients server-side; the modal posts an explicit contacts[] list. - // Scoping either lookup to this invoice's client is what makes a tampered - // contact_id harmless - it simply matches nothing. + // Two ways in. Quick Send skips the window and goes to the primary and + // billing contacts; the window posts the contacts picked. Either way only + // this client's contacts can match, so a tampered id finds nobody. if (!empty($_POST['quick_send'])) { - - $recipient_filter = documentDefaultContactFilterSql('invoice'); - - } else { - - $selected_contacts = $_POST['contacts'] ?? []; - if (!is_array($selected_contacts)) { - $selected_contacts = []; - } - $selected_contact_ids = array_filter(array_unique(array_map('intval', $selected_contacts))); - - if (empty($selected_contact_ids)) { - flashAlert("Select at least one contact to send to", 'error'); + $recipients = billingEmailRecipients($client_id); + if (!$recipients) { + flashAlert("No default contacts to quick send to - use Send to choose recipients", 'error'); redirect(); } - - $selected_contact_id_list = implode(',', $selected_contact_ids); - $recipient_filter = "AND contact_id IN ($selected_contact_id_list)"; - - } - - $sql_recipients = mysqli_query( - $mysqli, - "SELECT contact_email, contact_name FROM contacts - WHERE contact_client_id = $client_id - AND contact_archived_at IS NULL - AND contact_email IS NOT NULL - AND contact_email != '' - $recipient_filter - ORDER BY contact_primary DESC, contact_billing DESC, contact_name ASC" - ); - - if (mysqli_num_rows($sql_recipients) == 0) { - if (!empty($_POST['quick_send'])) { - flashAlert("No default contacts to quick send to - use Send Email to choose recipients", 'error'); - } else { - flashAlert("None of the selected contacts have a usable email address", 'error'); - } - redirect(); - } - - $sql = mysqli_query($mysqli,"SELECT company_address, company_city, company_country, company_email, company_logo, company_name, - company_phone, company_phone_country_code, company_state, company_website, company_zip FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - - $company_name = escapeSql($row['company_name']); - $company_country = escapeSql($row['company_country']); - $company_address = escapeSql($row['company_address']); - $company_city = escapeSql($row['company_city']); - $company_state = escapeSql($row['company_state']); - $company_zip = escapeSql($row['company_zip']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - $company_email = escapeSql($row['company_email']); - $company_website = escapeSql($row['company_website']); - $company_logo = escapeSql($row['company_logo']); - - // Sanitize Config vars from get_settings.php - $config_invoice_from_name = escapeSql($config_invoice_from_name); - $config_invoice_from_email = escapeSql($config_invoice_from_email); - - // Add up all the payments for the invoice and get the total amount paid to the invoice - $sql_amount_paid = mysqli_query($mysqli,"SELECT SUM(payment_amount) AS amount_paid FROM payments WHERE payment_invoice_id = $invoice_id"); - $row = mysqli_fetch_assoc($sql_amount_paid); - $amount_paid = floatval($row['amount_paid']); - - $balance = $invoice_amount - $amount_paid; - - if ($invoice_status == 'Paid') { - $subject = "Invoice $invoice_prefix$invoice_number Receipt"; } else { - $subject = "Invoice $invoice_prefix$invoice_number"; - } - - // One queue row per selected contact, each greeting its own recipient. - // The old handler built a single body around the primary contact's name - // and reused it for the billing copies, so those read "Hello " - visible enough with one hidden copy, wrong enough to keep once - // the recipient list is something the agent picks. - $data = []; - $recipient_labels = []; - - while ($recipient = mysqli_fetch_assoc($sql_recipients)) { - $contact_name = escapeSql($recipient['contact_name']); - $contact_email = escapeSql($recipient['contact_email']); - - if ($invoice_status == 'Paid') { - $body = "Hello $contact_name,

Please click on the link below to see your invoice regarding \"$invoice_scope\" marked paid.

Invoice Link


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; - } else { - $body = "Hello $contact_name,

Please view the details of your invoice regarding \"$invoice_scope\" below.

Invoice: $invoice_prefix$invoice_number
Issue Date: $invoice_date
Total: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "
Balance Due: " . numfmt_format_currency($currency_format, $balance, $invoice_currency_code) . "
Due Date: $invoice_due


To view your invoice, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; + $recipients = billingEmailRecipients($client_id, (array) ($_POST['contacts'] ?? [])); + if (!$recipients) { + flashAlert(empty($_POST['contacts']) ? "Select at least one contact to send to" : "None of the selected contacts have a usable email address", 'error'); + redirect(); } - - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - $recipient_labels[] = "$contact_name <$contact_email>"; - - logAudit("Invoice", "Email", "$session_name emailed $contact_email Invoice $invoice_prefix$invoice_number", $client_id, $invoice_id); } - addToMailQueue($data); + // The invoice, or a reminder of what is still owed - with the agent's note and the PDF + $kind = ($_POST['kind'] ?? '') === 'reminder' ? 'reminder' : 'invoice'; + $note = trim(mb_substr((string) ($_POST['note'] ?? ''), 0, 2000)); + $attach_pdf = !empty($_POST['quick_send']) ? billingReminderRules()['attach_pdf'] : !empty($_POST['attach_pdf']); + [$subject, $email] = billingInvoiceEmail($invoice, ['kind' => $kind, 'note' => $note]); + $attach = []; + if ($attach_pdf && ($file = billingEmailPdf(billingPdf('invoice', $invoice)))) { + $attach[] = $file; + } + $sent = billingEmailQueue($recipients, $subject, $email, ['attach' => $attach]); + $reminder = $kind === 'reminder' && $email['kind'] === 'Payment reminder'; - $recipient_list = implode(', ', $recipient_labels); - $recipient_count = count($recipient_labels); - - logHistory('Sent', "Invoice emailed by $session_name to $recipient_list", $invoice_id); - - // Don't change the status to sent if the status is anything but draft - if ($invoice_status == 'Draft') { - mysqli_query($mysqli,"UPDATE invoices SET invoice_status = 'Sent' WHERE invoice_id = $invoice_id"); + $by = stripslashes($session_name); + billingLog('invoice', $invoice_id, $invoice['invoice_status'] === 'Draft' ? 'Sent' : $invoice['invoice_status'], + ($reminder ? 'Reminder emailed' : 'Invoice emailed') . " by $by to " . implode(', ', $sent) . ($attach ? ' with the PDF' : '')); + foreach ($recipients as $recipient) { + logAudit("Invoice", "Email", "$session_name emailed " . escapeSql($recipient['email']) . ($reminder ? " a reminder for" : "") . " invoice " . escapeSql($number), $client_id, $invoice_id); } - flashAlert("Invoice queued to $recipient_count " . ($recipient_count == 1 ? "recipient" : "recipients")); + // Sending a draft sends it - anything further along keeps its status + if ($invoice['invoice_status'] === 'Draft') { + mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Sent' WHERE invoice_id = $invoice_id"); + } + + flashAlert(($reminder ? 'Reminder' : 'Invoice') . " queued to " . count($sent) . " " . (count($sent) === 1 ? "recipient" : "recipients")); redirect(); @@ -482,214 +387,67 @@ if (isset($_POST['send_statement'])) { enforceUserPermission('module_sales', 2); - $client_id = intval($_POST['client_id']); + $client_id = intval($_POST['client_id'] ?? 0); enforceClientAccess(); - $sql = mysqli_query($mysqli, "SELECT client_currency_code, client_name FROM clients WHERE client_id = $client_id LIMIT 1"); - $row = mysqli_fetch_assoc($sql); - $client_name = escapeSql($row['client_name']); - $client_currency_code = escapeSql($row['client_currency_code']); - - if (empty($client_currency_code)) { - $client_currency_code = escapeSql($session_company_currency); - } - - // Statement options. Emptiness has to be tested BEFORE validateDate(), - // which falls back to today rather than returning empty - running a blank - // From through it would silently produce a one-day statement. - $statement_date_to = $_POST['dtt'] ?? ''; - if (empty($statement_date_to)) { - $statement_date_to = date("Y-m-d"); - } else { - $statement_date_to = validateDate($statement_date_to); - } - $statement_date_to = escapeSql($statement_date_to); - - $statement_date_from = $_POST['dtf'] ?? ''; - if (empty($statement_date_from)) { - // Blank means the whole history, so there is no lower bound to apply - $statement_date_query = ''; - $statement_period = "up to $statement_date_to"; - } else { - $statement_date_from = escapeSql(validateDate($statement_date_from)); - $statement_date_query = "AND invoice_date >= '$statement_date_from'"; - $statement_period = "$statement_date_from to $statement_date_to"; - } - - $include_paid = !empty($_POST['include_paid']); - - // Recipients - same picker contract as the invoice send, so the same - // client scoping applies and a tampered contact_id matches nothing - $selected_contacts = $_POST['contacts'] ?? []; - if (!is_array($selected_contacts)) { - $selected_contacts = []; - } - $selected_contact_ids = array_filter(array_unique(array_map('intval', $selected_contacts))); - - if (empty($selected_contact_ids)) { - flashAlert("Select at least one contact to send to", 'error'); + // The period - a blank From is the whole history, a blank To is today + $statement_to = trim((string) ($_POST['dtt'] ?? '')); + $statement_from = trim((string) ($_POST['dtf'] ?? '')); + $statement = billingStatement($client_id, $statement_from !== '' ? validateDate($statement_from) : '', $statement_to !== '' ? validateDate($statement_to) : '', !empty($_POST['include_paid'])); + if (!$statement['client']) { + flashAlert('That client no longer exists.', 'error'); redirect(); } - - $selected_contact_id_list = implode(',', $selected_contact_ids); - - $sql_recipients = mysqli_query( - $mysqli, - "SELECT contact_email, contact_name FROM contacts - WHERE contact_id IN ($selected_contact_id_list) - AND contact_client_id = $client_id - AND contact_archived_at IS NULL - AND contact_email IS NOT NULL - AND contact_email != '' - ORDER BY contact_primary DESC, contact_billing DESC, contact_name ASC" - ); - - if (mysqli_num_rows($sql_recipients) == 0) { - flashAlert("None of the selected contacts have a usable email address", 'error'); - redirect(); - } - - // The statement lines. Draft / Cancelled / Non-Billable are not money the - // client owes, so they never appear - same exclusion the Outstanding - // Balances report uses. Payments are summed in a derived table rather than - // joined directly, or an invoice with two payments would be counted twice. - $sql_statement = mysqli_query( - $mysqli, - "SELECT invoice_amount, invoice_date, invoice_due, invoice_id, invoice_number, invoice_prefix, - invoice_scope, invoice_status, invoice_url_key, IFNULL(amount_paid, 0) AS amount_paid - FROM invoices - LEFT JOIN ( - SELECT payment_invoice_id, SUM(payment_amount) AS amount_paid FROM payments - WHERE payment_archived_at IS NULL - GROUP BY payment_invoice_id - ) AS invoice_payments ON payment_invoice_id = invoice_id - WHERE invoice_client_id = $client_id - AND invoice_status NOT IN ('Draft', 'Cancelled', 'Non-Billable') - AND invoice_date <= '$statement_date_to' - $statement_date_query - " . ($include_paid ? '' : "AND invoice_amount - IFNULL(invoice_payments.amount_paid, 0) > 0") . " - ORDER BY invoice_date ASC, invoice_number ASC" - ); - - if (mysqli_num_rows($sql_statement) == 0) { + if (!$statement['invoices']) { flashAlert("No invoices to report for that period - nothing sent", 'error'); redirect(); } - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - $config_invoice_from_name = escapeSql($config_invoice_from_name); - $config_invoice_from_email = escapeSql($config_invoice_from_email); - $config_base_url = escapeSql($config_base_url); - - // Build the table once - it is identical for every recipient, only the - // greeting differs. Everything interpolated here is already escaped: - // addToMailQueue() writes the body into the queue raw. - // - // KEEP EVERY ATTRIBUTE IN THIS MARKUP DOUBLE-QUOTED. The body is spliced - // into a single-quoted SQL literal, so a bare ' ends the statement and the - // INSERT dies; a " is just a character there and needs nothing. The older - // bodies above solve the same problem the other way, writing \' inside a - // double-quoted PHP string so the backslash itself reaches MySQL - do not - // copy that here, because \' inside a SINGLE-quoted PHP string collapses to - // a bare quote and puts the crash straight back. - // - // escapeSql() is not an option on assembled markup: it strip_tags() first, - // which would empty the table. - $statement_rows = ''; - $statement_total = 0; - $statement_line_count = 0; - - while ($row = mysqli_fetch_assoc($sql_statement)) { - $invoice_id = intval($row['invoice_id']); - $invoice_prefix = escapeSql($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_scope = escapeSql($row['invoice_scope']); - $invoice_status = escapeSql($row['invoice_status']); - $invoice_date = escapeSql($row['invoice_date']); - $invoice_due = escapeSql($row['invoice_due']); - $invoice_url_key = escapeSql($row['invoice_url_key']); - $invoice_amount = floatval($row['invoice_amount']); - $amount_paid = floatval($row['amount_paid']); - $invoice_balance = $invoice_amount - $amount_paid; - - $statement_total += $invoice_balance; - $statement_line_count++; - - $invoice_link = "https://$config_base_url/guest/guest_view_invoice.php?invoice_id=$invoice_id&url_key=$invoice_url_key"; - - $overdue_flag = ''; - if ($invoice_balance > 0 && !empty($invoice_due) && $invoice_due < date("Y-m-d")) { - $overdue_flag = ' (overdue)'; - } - - $statement_rows .= '' - . '' . "$invoice_prefix$invoice_number" . '' - . '' . $invoice_scope . '' - . '' . $invoice_date . '' - . '' . $invoice_due . $overdue_flag . '' - . '' . numfmt_format_currency($currency_format, $invoice_amount, $client_currency_code) . '' - . '' . numfmt_format_currency($currency_format, $amount_paid, $client_currency_code) . '' - . '' . numfmt_format_currency($currency_format, $invoice_balance, $client_currency_code) . '' - . ''; + $recipients = billingEmailRecipients($client_id, (array) ($_POST['contacts'] ?? [])); + if (!$recipients) { + flashAlert(empty($_POST['contacts']) ? "Select at least one contact to send to" : "None of the selected contacts have a usable email address", 'error'); + redirect(); } - $statement_table = '' - . '' - . '' - . '' - . '' - . '' - . '' - . '' - . '' - . '' - . $statement_rows - . '' - . '' - . '
InvoiceScopeDateDueAmountPaidBalance
Total Balance Due' . numfmt_format_currency($currency_format, $statement_total, $client_currency_code) . '
'; + // functions/billing_email.php - the statement, its PDF when asked for + $sent = billingStatementSend($statement, array_column($recipients, 'id'), [ + 'note' => trim(mb_substr((string) ($_POST['note'] ?? ''), 0, 2000)), + 'attach' => !empty($_POST['attach_pdf']), + ]); - $subject = "Account Statement - $client_name"; + $client_name = escapeSql($statement['client']['client_name']); + logAudit("Client", "Statement", "$session_name emailed a statement (" . escapeSql(billingStatementPeriod($statement)) . ", " . count($statement['invoices']) . " invoices, " + . escapeSql(billingMoney($statement['total'], $statement['currency'])) . " due) to " . escapeSql(implode(', ', $sent)), $client_id); - $data = []; - $recipient_labels = []; - - while ($recipient = mysqli_fetch_assoc($sql_recipients)) { - $contact_name = escapeSql($recipient['contact_name']); - $contact_email = escapeSql($recipient['contact_email']); - - $body = "Hello $contact_name,

Please find your account statement for $statement_period below.

" - . $statement_table - . "

Click any invoice number above to view or pay it online.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - $recipient_labels[] = "$contact_name <$contact_email>"; - - logAudit("Invoice", "Statement", "$session_name emailed an account statement ($statement_period, $statement_line_count invoices) to $contact_email", $client_id); - } - - addToMailQueue($data); - - $recipient_count = count($recipient_labels); - - flashAlert("Statement queued to $recipient_count " . ($recipient_count == 1 ? "recipient" : "recipients")); + flashAlert("Statement queued to " . count($sent) . " " . (count($sent) === 1 ? "recipient" : "recipients") . " - " . count($statement['invoices']) . " " . (count($statement['invoices']) === 1 ? "invoice" : "invoices") . ", " . escapeHtml(billingMoney($statement['total'], $statement['currency'])) . " due"); redirect(); } +if (isset($_GET['export_client_statement_pdf'])) { + + validateCSRFToken(); + + enforceUserPermission('module_sales'); + + $client_id = intval($_GET['export_client_statement_pdf']); + + enforceClientAccess(); + + $statement_to = trim((string) ($_GET['dtt'] ?? '')); + $statement_from = trim((string) ($_GET['dtf'] ?? '')); + $statement = billingStatement($client_id, $statement_from !== '' ? validateDate($statement_from) : '', $statement_to !== '' ? validateDate($statement_to) : '', !empty($_GET['include_paid'])); + if (!$statement['client']) { + flashAlert('That client no longer exists.', 'error'); + redirect(); + } + + billingPdfSend(billingStatementPdf($statement)); + +} + if (isExportRequest('export_invoices')) { validateCSRFToken(); diff --git a/agent/post/payment.php b/agent/post/payment.php index c0741f9f0..f596b0646 100644 --- a/agent/post/payment.php +++ b/agent/post/payment.php @@ -43,123 +43,18 @@ if (isset($_POST['add_payment'])) { $total_payments_amount = floatval($row['payments_amount']); //Get the invoice total - $sql = mysqli_query($mysqli,"SELECT client_name, contact_email, contact_extension, contact_mobile, contact_mobile_country_code, - contact_name, contact_phone, contact_phone_country_code, invoice_amount, - invoice_currency_code, invoice_number, invoice_prefix, invoice_url_key FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 - WHERE invoice_id = $invoice_id" - ); - + $sql = mysqli_query($mysqli,"SELECT invoice_amount, invoice_currency_code, invoice_number, invoice_prefix FROM invoices WHERE invoice_id = $invoice_id"); $row = mysqli_fetch_assoc($sql); $invoice_amount = floatval($row['invoice_amount']); $invoice_prefix = escapeSql($row['invoice_prefix']); $invoice_number = intval($row['invoice_number']); - $invoice_url_key = escapeSql($row['invoice_url_key']); $invoice_currency_code = escapeSql($row['invoice_currency_code']); - $client_name = escapeSql($row['client_name']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $contact_phone = escapeSql(formatPhoneNumber($row['contact_phone'], $row['contact_phone_country_code'])); - $contact_extension = preg_replace("/[^0-9]/", '',$row['contact_extension']); - $contact_mobile = escapeSql(formatPhoneNumber($row['contact_mobile'], $row['contact_mobile_country_code'])); - - $sql = mysqli_query($mysqli,"SELECT company_address, company_city, company_country, company_email, company_logo, company_name, - company_phone, company_phone_country_code, company_state, company_website, company_zip FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - - $company_name = escapeSql($row['company_name']); - $company_country = escapeSql($row['company_country']); - $company_address = escapeSql($row['company_address']); - $company_city = escapeSql($row['company_city']); - $company_state = escapeSql($row['company_state']); - $company_zip = escapeSql($row['company_zip']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - $company_email = escapeSql($row['company_email']); - $company_website = escapeSql($row['company_website']); - $company_logo = escapeSql($row['company_logo']); - - // Sanitize Config vars from get_settings.php - $config_invoice_from_name = escapeSql($config_invoice_from_name); - $config_invoice_from_email = escapeSql($config_invoice_from_email); //Calculate the Invoice balance $invoice_balance = $invoice_amount - $total_payments_amount; - $email_data = []; - //Determine if invoice has been paid then set the status accordingly - if ($invoice_balance == 0) { - - $invoice_status = "Paid"; - - if ($email_receipt == 1) { - - $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

We have received your payment in full for the amount of " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . "
Payment Method: $payment_method
Payment Reference: $reference

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - // Queue Mail - $email = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - $email_data[] = $email; - - // Add email to queue - if (!empty($email)) { - addToMailQueue($email_data); - } - - // Get Email ID for reference - $email_id = mysqli_insert_id($mysqli); - - // Email Logging - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $invoice_id"); - logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $invoice_id); - - } - - } else { - - $invoice_status = "Partial"; - - if ($email_receipt == 1) { - - $subject = "Partial Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

We have received partial payment in the amount of " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . " and it has been applied to invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . "
Payment Method: $payment_method
Payment Reference: $reference
Invoice Balance: " . numfmt_format_currency($currency_format, $invoice_balance, $invoice_currency_code) . "

Thank you for your business!


~
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - // Queue Mail - $email = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - $email_data[] = $email; - - // Add email to queue - if (!empty($email)) { - addToMailQueue($email_data); - } - - // Get Email ID for reference - $email_id = mysqli_insert_id($mysqli); - - // Email Logging - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $invoice_id"); - logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $invoice_id); - - } - - } + $invoice_status = $invoice_balance == 0 ? "Paid" : "Partial"; //Update Invoice Status mysqli_query($mysqli,"UPDATE invoices SET invoice_status = '$invoice_status' WHERE invoice_id = $invoice_id"); @@ -169,6 +64,14 @@ if (isset($_POST['add_payment'])) { logAudit("Invoice", "Payment", "Payment amount of " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . " added to invoice $invoice_prefix$invoice_number", $client_id, $invoice_id); + // The client's receipt - functions/billing_email.php + if ($email_receipt == 1) { + $receipt_to = billingPaymentSend($invoice_id, $amount, ['date' => $date, 'method' => stripslashes($payment_method), 'reference' => stripslashes($reference)]); + if ($receipt_to) { + logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to " . escapeSql(implode(', ', $receipt_to)), $client_id, $invoice_id); + } + } + triggerCustomAction('invoice_pay', $invoice_id); flashAlert("Payment amount " . numfmt_format_currency($currency_format, $amount, $invoice_currency_code) . " added"); @@ -450,44 +353,12 @@ if (isset($_POST['add_payment_stripe'])) { mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$pi_date', payment_amount = $pi_amount_paid, payment_currency_code = '$pi_currency', payment_account_id = $account_id, payment_method = 'Stripe', payment_reference = 'Stripe - $pi_id', payment_invoice_id = $invoice_id"); mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Paid', history_description = 'Online Payment added (agent)', history_invoice_id = $invoice_id"); - // Email receipt + // The client's receipt, and the paid notification address - functions/billing_email.php if (!empty($config_smtp_provider)) { - $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - // Queue Mail - $data = [ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - - // Email the internal notification address too - if (!empty($config_invoice_paid_notification_email)) { - $subject = "Payment Received - $client_name - Invoice $invoice_prefix$invoice_number"; - $body = "Hello,

This is a notification that an invoice has been paid in ITFlow. Below is a copy of the receipt sent to the client:-

--------

Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $config_invoice_paid_notification_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ]; + $receipt_to = billingPaymentSend($invoice_id, $pi_amount_paid, ['date' => $pi_date, 'method' => 'Card', 'reference' => "Stripe - $pi_id", 'how' => 'Card'], true); + if ($receipt_to) { + logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to " . escapeSql(implode(', ', $receipt_to)), $client_id, $invoice_id); } - - $mail = addToMailQueue($data); - - // Email Logging - $email_id = mysqli_insert_id($mysqli); - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $invoice_id"); - logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $invoice_id); } // Log info @@ -551,6 +422,7 @@ if (isset($_POST['add_bulk_payment'])) { $result_invoices = mysqli_query($mysqli, $sql_invoices); // Loop Through Each Invoice + $applied_payments = []; while ($row = mysqli_fetch_assoc($result_invoices)) { $invoice_id = intval($row['invoice_id']); $invoice_prefix = escapeSql($row['invoice_prefix']); @@ -600,53 +472,30 @@ if (isset($_POST['add_bulk_payment'])) { $add_history_query = "INSERT INTO history (history_status, history_description, history_invoice_id) VALUES ('{$invoice_status}', '{$history_description}', {$invoice_id})"; mysqli_query($mysqli, $add_history_query); - // Add to Email Body Invoice Portion - $email_body_invoices .= "
Invoice $invoice_prefix$invoice_number - Outstanding Amount: " . numfmt_format_currency($currency_format, $invoice_balance, $currency_code) . " - Payment Applied: " . numfmt_format_currency($currency_format, $payment_amount, $currency_code) . " - New Balance: " . numfmt_format_currency($currency_format, $remaining_invoice_balance, $currency_code); + // For the receipt - what went on each invoice + $applied_payments[] = ['invoice_id' => $invoice_id, 'amount' => $payment_amount]; triggerCustomAction('invoice_pay', $invoice_id); } // End Invoice Loop - // Send Email - if ($email_receipt == 1) { - - // Get Client / Contact Info - $sql_client = mysqli_query($mysqli,"SELECT * FROM clients - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id - AND contact_primary = 1 - WHERE client_id = $client_id" - ); - - $row = mysqli_fetch_assoc($sql_client); - $client_name = escapeSql($row['client_name']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - - $sql_company = mysqli_query($mysqli,"SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql_company); - - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // Sanitize Config vars from get_settings.php - $config_invoice_from_name = escapeSql($config_invoice_from_name); - $config_invoice_from_email = escapeSql($config_invoice_from_email); - - $subject = "Payment Received - Multiple Invoices"; - $body = "Hello $contact_name,

Thank you for your payment of " . numfmt_format_currency($currency_format, $bulk_payment_amount_static, $currency_code) . " We\'ve applied your payment to the following invoices, updating their balances accordingly:

$email_body_invoices


We appreciate your continued business!

Sincerely,
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - // Queue Mail - mysqli_query($mysqli, "INSERT INTO email_queue SET email_recipient = '$contact_email', email_recipient_name = '$contact_name', email_from = '$config_invoice_from_email', email_from_name = '$config_invoice_from_name', email_subject = '$subject', email_content = '$body'"); - - // Get Email ID for reference - $email_id = mysqli_insert_id($mysqli); - - // Email Logging - logAudit("Payment", "Email", "Bulk Payment receipt for multiple Invoices queued to $contact_email Email ID: $email_id", $client_id); - - $alert_message .= "Email receipt queued and "; - - } // End Email + // The client's receipt, listing each invoice paid - functions/billing_email.php + $alert_message = ''; + if ($email_receipt == 1 && !empty($applied_payments)) { + $applied = []; + foreach ($applied_payments as $entry) { + $applied[] = ['invoice' => billingRow('invoice', $entry['invoice_id'], false), 'amount' => $entry['amount']]; + } + [$subject, $email] = billingPaymentEmail($applied, ['date' => $date, 'method' => stripslashes($payment_method), 'reference' => stripslashes($reference), 'currency' => $currency_code]); + $receipt_to = billingEmailQueue(billingEmailRecipients($client_id), $subject, $email); + if ($receipt_to) { + foreach ($applied_payments as $entry) { + billingLog('invoice', $entry['invoice_id'], 'Sent', 'Payment receipt emailed to ' . implode(', ', $receipt_to)); + } + logAudit("Payment", "Email", "Bulk Payment receipt for multiple Invoices queued to " . escapeSql(implode(', ', $receipt_to)), $client_id); + $alert_message .= "Email receipt queued and "; + } + } logAudit("Invoice", "Payment", "Bulk Payment amount of " . numfmt_format_currency($currency_format, $bulk_payment_amount_static, $currency_code) . " applied to multiple invoices", $client_id); diff --git a/agent/post/quote.php b/agent/post/quote.php index 8f14e874f..030d1c7b6 100644 --- a/agent/post/quote.php +++ b/agent/post/quote.php @@ -366,141 +366,54 @@ if (isset($_POST['email_quote'])) { enforceUserPermission('module_sales', 2); - $quote_id = intval($_POST['quote_id']); - - $sql = mysqli_query($mysqli,"SELECT client_id, client_name, quote_amount, quote_currency_code, - quote_date, quote_expire, quote_number, quote_prefix, quote_scope, quote_status, - quote_url_key FROM quotes - LEFT JOIN clients ON quote_client_id = client_id - WHERE quote_id = $quote_id" - ); - - $row = mysqli_fetch_assoc($sql); - $quote_prefix = escapeSql($row['quote_prefix']); - $quote_number = intval($row['quote_number']); - $quote_scope = escapeSql($row['quote_scope']); - $quote_status = escapeSql($row['quote_status']); - $quote_date = escapeSql($row['quote_date']); - $quote_expire = escapeSql($row['quote_expire']); - $quote_amount = floatval($row['quote_amount']); - $quote_url_key = escapeSql($row['quote_url_key']); - $quote_currency_code = escapeSql($row['quote_currency_code']); - $client_id = intval($row['client_id']); - $client_name = escapeSql($row['client_name']); + $quote = billingRow('quote', intval($_POST['quote_id'] ?? 0)); + if (!$quote) { + flashAlert('That quote no longer exists.', 'error'); + redirect('quotes.php'); + } + $quote_id = intval($quote['quote_id']); + $client_id = intval($quote['client_id']); + $number = billingNumber('quote', $quote); enforceClientAccess(); - // What it comes to - up front, and each month, quarter or year - $quote_groups = quoteGroups(billingRow('quote', $quote_id, false)); - $quote_groups_recurring = quoteHasRecurring($quote_groups); - $quote_cost_text = quoteAmountText($quote_groups, $row['quote_currency_code'] ?? $quote_currency_code); - - // Two ways in. Quick Send skips the modal and resolves the default - // recipients server-side; the modal posts an explicit contacts[] list. - // Scoping either lookup to this quote's client is what makes a tampered - // contact_id harmless - it simply matches nothing. + // Two ways in. Quick Send skips the window and goes to the primary + // contact; the window posts the contacts picked. Either way only this + // client's contacts can match, so a tampered id finds nobody. if (!empty($_POST['quick_send'])) { - - $recipient_filter = documentDefaultContactFilterSql('quote'); - - } else { - - $selected_contacts = $_POST['contacts'] ?? []; - if (!is_array($selected_contacts)) { - $selected_contacts = []; - } - $selected_contact_ids = array_filter(array_unique(array_map('intval', $selected_contacts))); - - if (empty($selected_contact_ids)) { - flashAlert("Select at least one contact to send to", 'error'); + $recipients = billingEmailRecipients($client_id, null, 'quote'); + if (!$recipients) { + flashAlert("No default contacts to quick send to - use Send to choose recipients", 'error'); redirect(); } - - $selected_contact_id_list = implode(',', $selected_contact_ids); - $recipient_filter = "AND contact_id IN ($selected_contact_id_list)"; - - } - - $sql_recipients = mysqli_query( - $mysqli, - "SELECT contact_email, contact_name FROM contacts - WHERE contact_client_id = $client_id - AND contact_archived_at IS NULL - AND contact_email IS NOT NULL - AND contact_email != '' - $recipient_filter - ORDER BY contact_primary DESC, contact_billing DESC, contact_name ASC" - ); - - if (mysqli_num_rows($sql_recipients) == 0) { - if (!empty($_POST['quick_send'])) { - flashAlert("No default contacts to quick send to - use Send Email to choose recipients", 'error'); - } else { - flashAlert("None of the selected contacts have a usable email address", 'error'); + } else { + $recipients = billingEmailRecipients($client_id, (array) ($_POST['contacts'] ?? [])); + if (!$recipients) { + flashAlert(empty($_POST['contacts']) ? "Select at least one contact to send to" : "None of the selected contacts have a usable email address", 'error'); + redirect(); } - redirect(); } - $sql = mysqli_query($mysqli,"SELECT company_address, company_city, company_country, company_email, company_logo, company_name, - company_phone, company_phone_country_code, company_state, company_website, company_zip FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); + // functions/billing_email.php - the quote, with the agent's note and the PDF + [$subject, $email] = billingQuoteEmail($quote, ['note' => trim(mb_substr((string) ($_POST['note'] ?? ''), 0, 2000))]); + $attach_pdf = !empty($_POST['quick_send']) ? billingReminderRules()['attach_pdf'] : !empty($_POST['attach_pdf']); + $attach = []; + if ($attach_pdf && ($file = billingEmailPdf(billingPdf('quote', $quote)))) { + $attach[] = $file; + } + $sent = billingEmailQueue($recipients, $subject, $email, ['from' => 'quote', 'attach' => $attach]); - $company_name = escapeSql($row['company_name']); - $company_country = escapeSql($row['company_country']); - $company_address = escapeSql($row['company_address']); - $company_city = escapeSql($row['company_city']); - $company_state = escapeSql($row['company_state']); - $company_zip = escapeSql($row['company_zip']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - $company_email = escapeSql($row['company_email']); - $company_website = escapeSql($row['company_website']); - $company_logo = escapeSql($row['company_logo']); - - // Sanitize Config vars from get_settings.php - $config_quote_from_name = escapeSql($config_quote_from_name); - $config_quote_from_email = escapeSql($config_quote_from_email); - $config_base_url = escapeSql($config_base_url); - - $subject = "Quote [$quote_scope]"; - - // One queue row per selected contact, each greeting its own recipient - $data = []; - $recipient_labels = []; - - while ($recipient = mysqli_fetch_assoc($sql_recipients)) { - $contact_name = escapeSql($recipient['contact_name']); - $contact_email = escapeSql($recipient['contact_email']); - - $body = "Hello $contact_name,

Thank you for your inquiry, we are pleased to provide you with the following estimate.


$quote_scope
" . ($quote_groups_recurring ? 'Cost: ' : 'Total Cost: ') . escapeSql(htmlspecialchars($quote_cost_text)) . "


View and accept your estimate online here


--
$company_name - Sales
$config_quote_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_quote_from_email, - 'from_name' => $config_quote_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ]; - - $recipient_labels[] = "$contact_name <$contact_email>"; - - logAudit("Quote", "Email", "$session_name emailed quote $quote_prefix$quote_number to $contact_email", $client_id, $quote_id); + billingLog('quote', $quote_id, $quote['quote_status'] === 'Draft' ? 'Sent' : $quote['quote_status'], 'Quote emailed by ' . stripslashes($session_name) . ' to ' . implode(', ', $sent) . ($attach ? ' with the PDF' : '')); + foreach ($recipients as $recipient) { + logAudit("Quote", "Email", "$session_name emailed quote " . escapeSql($number) . " to " . escapeSql($recipient['email']), $client_id, $quote_id); } - addToMailQueue($data); - - $recipient_list = implode(', ', $recipient_labels); - $recipient_count = count($recipient_labels); - - // Update History - logHistory('Sent', "Quote emailed by $session_name to $recipient_list", 0, $quote_id); - - //Don't change the status to sent if the status is anything but draft - if ($quote_status == 'Draft') { - mysqli_query($mysqli,"UPDATE quotes SET quote_status = 'Sent' WHERE quote_id = $quote_id"); + // Sending a draft sends it - anything further along keeps its status + if ($quote['quote_status'] === 'Draft') { + mysqli_query($mysqli, "UPDATE quotes SET quote_status = 'Sent' WHERE quote_id = $quote_id"); } - flashAlert("Quote queued to $recipient_count " . ($recipient_count == 1 ? "recipient" : "recipients")); + flashAlert("Quote queued to " . count($sent) . " " . (count($sent) === 1 ? "recipient" : "recipients")); redirect(); diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index f72483812..e92fb4d59 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -166,6 +166,9 @@ mysqli_query($mysqli, "DELETE FROM notifications WHERE notification_dismissed_at // Clean-up mail queue mysqli_query($mysqli, "DELETE FROM email_queue WHERE email_queued_at < CURDATE() - INTERVAL 90 DAY"); +// Clean-up the PDFs made to go with billing emails - sent or given up on by now +billingEmailPdfCleanup(7); + // Clean-up old remember me tokens mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_created_at < CURDATE() - INTERVAL $config_login_remember_me_expire DAY"); @@ -406,123 +409,100 @@ while ($row = mysqli_fetch_assoc($sql_resolved_tickets_to_close)) { //TODO: Add client notifs if $config_ticket_client_general_notifications is on } -if ($config_send_invoice_reminders == 1) { +/* + * 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. + */ +$reminder_rules = billingReminderRules(true); +if ($reminder_rules['enabled']) { - // PAST DUE INVOICE Notifications - $invoiceAlertArray = [1,30,60,90,120,150,180,210,240,270,300,330,360,390,420,450,480,510,540,570,590,620,650,680,710,740]; + $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 + FROM invoices + JOIN clients ON client_id = invoice_client_id + WHERE invoice_status IN ('Sent', 'Viewed', 'Partial') AND invoice_due IS NOT NULL AND DATEDIFF(CURDATE(), invoice_due) >= $earliest + ORDER BY invoice_due ASC, invoice_id ASC"); - foreach ($invoiceAlertArray as $day) { - - $sql = mysqli_query( - $mysqli, - "SELECT client_id, client_name, contact_email, contact_name, invoice_amount, invoice_currency_code, - invoice_date, invoice_due, invoice_id, invoice_number, invoice_prefix, invoice_status, - invoice_url_key FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 - WHERE invoice_status != 'Draft' - AND invoice_status != 'Paid' - AND invoice_status != 'Cancelled' - AND invoice_status != 'Non-Billable' - AND DATE_ADD(invoice_due, INTERVAL $day DAY) = CURDATE() - ORDER BY invoice_number DESC" - ); - - while ($row = mysqli_fetch_assoc($sql)) { - $invoice_id = intval($row['invoice_id']); - $invoice_prefix = escapeSql($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_status = escapeSql($row['invoice_status']); - $invoice_date = escapeSql($row['invoice_date']); - $invoice_due = escapeSql($row['invoice_due']); - $invoice_url_key = escapeSql($row['invoice_url_key']); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_currency_code = escapeSql($row['invoice_currency_code']); - $client_id = intval($row['client_id']); - $client_name = escapeSql($row['client_name']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - - // Sum payments already applied, derive the real balance owed - $sql_paid = mysqli_query($mysqli, "SELECT SUM(payment_amount) AS amount_paid FROM payments WHERE payment_invoice_id = $invoice_id"); - $paid_row = mysqli_fetch_assoc($sql_paid); - $amount_paid = floatval($paid_row['amount_paid']); - - $invoice_balance = $invoice_amount - $amount_paid; - - // Nothing actually owed (e.g. paid in full but status lagging) - skip - if ($invoice_balance <= 0) { - continue; - } - - // Late Charges - at most one per invoice per day, or a second run of this - // script stacks another fee on the already-inflated balance - if ($config_invoice_late_fee_enable == 1 && $day > 1 && !cronInvoiceHistoryToday($invoice_id, 'Cron applied a late fee')) { - - $todays_date = date('Y-m-d'); - $late_fee_amount = ($invoice_balance * $config_invoice_late_fee_percent) / 100; - $new_invoice_amount = $invoice_amount + $late_fee_amount; - - mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id"); - - //Insert Items into New Invoice - mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = 'Late Fee', item_description = '$config_invoice_late_fee_percent% late fee applied on $todays_date', item_quantity = 1, item_price = $late_fee_amount, item_total = $late_fee_amount, item_order = 998, item_invoice_id = $invoice_id"); - - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron applied a late fee of $late_fee_amount', history_invoice_id = $invoice_id"); - - appNotify("Invoice Late Charge", "Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount was charged a late fee of $late_fee_amount", "/agent/invoice.php?invoice_id=$invoice_id", $client_id); - - // Roll the fee into the balance and total we report below - $invoice_amount = $new_invoice_amount; - $invoice_balance = $invoice_balance + $late_fee_amount; - - } - - appNotify("Invoice Overdue", "Invoice $invoice_prefix$invoice_number for $client_name with a balance of " . numfmt_format_currency($currency_format, $invoice_balance, $invoice_currency_code) . " is overdue by $day days", "/agent/invoice.php?invoice_id=$invoice_id", $client_id); - - // One client email per invoice per day - the 3am run and a Run Now the same - // afternoon must not both mail them - if (cronInvoiceHistoryToday($invoice_id, 'Cron Emailed Overdue Invoice')) { - continue; - } - - $subject = "Overdue Invoice $invoice_prefix$invoice_number"; - - // Only show the paid line if a payment has actually been applied - $paid_line = $amount_paid > 0 ? "Amount Paid: " . numfmt_format_currency($currency_format, $amount_paid, $invoice_currency_code) . "
" : ""; - - $body = "Hello $contact_name,

Our records indicate that we have not yet received payment in full for the invoice $invoice_prefix$invoice_number. We kindly request that you submit your payment as soon as possible. If you have any questions or concerns, please do not hesitate to contact us at $company_email or $company_phone. -
- Kindly review the invoice details mentioned below.

Invoice: $invoice_prefix$invoice_number
Issue Date: $invoice_date
Invoice Total: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "
$paid_line" . "Balance Due: " . numfmt_format_currency($currency_format, $invoice_balance, $invoice_currency_code) . "
Due Date: $invoice_due
Over Due By: $day Days


To view your invoice, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - $mail = addToMailQueue([ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ] - ]); - - if ($mail === true) { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Overdue Invoice', history_invoice_id = $invoice_id"); - } else { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Failed to send Overdue Invoice', history_invoice_id = $invoice_id"); - - appNotify("Mail", "Failed to send email to $contact_email"); - - // Logging - logApp("Mail", "error", "Failed to send email to $contact_email regarding $subject. $mail"); - } + while ($row = mysqli_fetch_assoc($sql_reminders)) { + $invoice_id = intval($row['invoice_id']); + $days = intval($row['days_late']); + $invoice = billingRow('invoice', $invoice_id, false); + if (!$invoice) { + continue; + } + $balance = invoiceState($invoice, invoicePaid($invoice_id))['balance']; + $number = billingNumber('invoice', $invoice); + // Nothing actually owed (paid in full but status lagging) - skip + if ($balance <= 0) { + continue; } + // Late fee - every 30 days late, as a line of its own, at most once a day + if ($config_invoice_late_fee_enable == 1 && $days > 0 && $days % 30 === 0 && !cronInvoiceHistoryToday($invoice_id, 'Cron applied a late fee')) { + $late_fee = round($balance * $config_invoice_late_fee_percent / 100, 2); + if ($late_fee > 0) { + billingItemSave('invoice', $invoice_id, ['name' => 'Late Fee', 'description' => floatval($config_invoice_late_fee_percent) . '% late fee applied on ' . date('Y-m-d'), 'qty' => 1, 'price' => $late_fee, 'tax_id' => 0]); + billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Cron applied a late fee of ' . billingMoney($late_fee, $invoice['invoice_currency_code'])); + appNotify("Invoice Late Charge", escapeSql("Invoice $number for {$invoice['client_name']} with a balance of " . billingMoney($balance, $invoice['invoice_currency_code']) . " was charged a late fee of " . billingMoney($late_fee, $invoice['invoice_currency_code'])), "/agent/invoice.php?invoice_id=$invoice_id", intval($invoice['client_id'])); + $invoice = billingRow('invoice', $invoice_id, false); + $balance = invoiceState($invoice, invoicePaid($invoice_id))['balance']; + } + } + + 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'])); + } + + // 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')) { + continue; + } + + $recipients = billingEmailRecipients($invoice['client_id']); + if (!$recipients) { + 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']); + $attach = []; + if ($reminder_rules['attach_pdf'] && ($file = billingEmailPdf(billingPdf('invoice', $invoice)))) { + $attach[] = $file; + } + $sent = billingEmailQueue($recipients, $subject, $email, ['attach' => $attach]); + billingLog('invoice', $invoice_id, $invoice['invoice_status'], 'Reminder emailed to ' . implode(', ', $sent) . ' - ' . billingReminderWhen($days)); + } + + // Statements each month, on the day in the invoice settings, to every client with a balance + if ($reminder_rules['statement_monthly'] && intval(date('j')) === $reminder_rules['statement_day'] && !empty($config_smtp_provider)) { + $sql_statements = mysqli_query($mysqli, "SELECT DISTINCT client_id FROM invoices + JOIN clients ON client_id = invoice_client_id + WHERE invoice_status IN ('Sent', 'Viewed', 'Partial') AND client_reminders = 1 AND client_archived_at IS NULL"); + 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")); + $statement = billingStatement($client_id); + if ($already || $statement['total'] <= 0) { + continue; + } + $sent = billingStatementSend($statement, null, ['attach' => $reminder_rules['attach_pdf']]); + if ($sent) { + logAudit("Client", "Statement", escapeSql("Cron emailed the monthly statement (" . count($statement['invoices']) . " invoices, " . billingMoney($statement['total'], $statement['currency']) . " due) to " . implode(', ', $sent)), $client_id); + } + } } } -// Logging -// logAudit("Cron", "Task", "Cron created notifications for past due invoices and sent out notifications to the primary and billing contacts email"); + // 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 @@ -692,37 +672,12 @@ while ($row = mysqli_fetch_assoc($sql_recurring_payments)) { mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$pi_date', payment_amount = $pi_amount_paid, payment_currency_code = '$pi_currency', payment_account_id = $account_id, payment_method = 'Stripe', payment_reference = 'Stripe - $pi_id', payment_invoice_id = $invoice_id"); mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Paid', history_description = 'Online Payment added (autopay)', history_invoice_id = $invoice_id"); - // RECEIPT EMAIL + // The client's receipt, and the paid notification address - functions/billing_email.php if (!empty($config_smtp_provider)) { - $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; - - $data = [[ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ]]; - - // Internal notification - if (!empty($config_invoice_paid_notification_email)) { - $subject_int = "Payment Received - $client_name - Invoice $invoice_prefix$invoice_number"; - $body_int = "This is a notification that an invoice has been paid in ITFlow. Below is a copy of the receipt sent to the client:-

--------

$body"; - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $config_invoice_paid_notification_email, - 'recipient_name' => $contact_name, - 'subject' => $subject_int, - 'body' => $body_int, - ]; + $receipt_to = billingPaymentSend($invoice_id, $pi_amount_paid, ['date' => $pi_date, 'method' => 'Card', 'reference' => "Stripe - $pi_id", 'how' => 'Automatic card'], true); + if ($receipt_to) { + logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to " . escapeSql(implode(', ', $receipt_to)), $client_id, $invoice_id); } - $mail = addToMailQueue($data); - $email_id = mysqli_insert_id($mysqli); - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $invoice_id"); - logAudit("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $invoice_id); } // LOGGING diff --git a/db.sql b/db.sql index 5b77bc67f..1544057dc 100644 --- a/db.sql +++ b/db.sql @@ -700,6 +700,7 @@ CREATE TABLE `clients` ( `client_rate` decimal(15,2) DEFAULT NULL, `client_currency_code` varchar(200) NOT NULL, `client_net_terms` int(10) NOT NULL, + `client_reminders` tinyint(1) NOT NULL DEFAULT 1, `client_tax_id_number` varchar(255) DEFAULT NULL, `client_abbreviation` varchar(10) DEFAULT NULL, `client_notes` text DEFAULT NULL, @@ -2543,6 +2544,11 @@ CREATE TABLE `settings` ( `config_recurring_auto_send_invoice` tinyint(1) NOT NULL DEFAULT 1, `config_enable_alert_domain_expire` tinyint(1) NOT NULL DEFAULT 1, `config_send_invoice_reminders` tinyint(1) NOT NULL DEFAULT 1, + `config_invoice_reminder_days` varchar(200) NOT NULL DEFAULT '1,30', + `config_invoice_reminder_repeat` int(11) NOT NULL DEFAULT 30, + `config_statement_monthly` tinyint(1) NOT NULL DEFAULT 0, + `config_statement_day` tinyint(2) NOT NULL DEFAULT 1, + `config_billing_email_attach_pdf` tinyint(1) NOT NULL DEFAULT 1, `config_azure_client_id` varchar(200) DEFAULT NULL, `config_azure_client_secret` varchar(200) DEFAULT NULL, `config_module_enable_itdoc` tinyint(1) NOT NULL DEFAULT 1, diff --git a/functions.php b/functions.php index f2533a7e5..b887053b4 100644 --- a/functions.php +++ b/functions.php @@ -52,3 +52,4 @@ require_once __DIR__ . '/functions/client_export.php'; require_once __DIR__ . '/functions/share.php'; require_once __DIR__ . '/functions/billing.php'; require_once __DIR__ . '/functions/products.php'; +require_once __DIR__ . '/functions/billing_email.php'; diff --git a/functions/billing.php b/functions/billing.php index 1fac28e89..e6e1c4018 100644 --- a/functions/billing.php +++ b/functions/billing.php @@ -1776,41 +1776,24 @@ function recurringInvoiceGenerate($recurring_invoice_id, $by = 'Cron', $early = billingLog('invoice', $invoice_id, 'Draft', "Made from $recurring_number by $by, for {$period['{period}']}" . ($seat_changes ? ' - seats updated' : '')); billingLog('recurring', $recurring_invoice_id, 'Invoiced', "$invoice_number made by $by, for {$period['{period}']} - next on $next"); - // Send it, when it sends itself + // Send it, when it sends itself - to the primary and billing contacts, on the billing email (functions/billing_email.php) $sent_to = []; if (intval($row['recurring_invoice_auto_send']) === 1 && intval($row['recurring_invoice_email_notify']) === 1 && intval($settings['config_recurring_auto_send_invoice'] ?? 0) === 1 && !empty($settings['config_smtp_provider'])) { - $company = billingCompany(); - $money = billingMoney($invoice['invoice_amount'], $invoice['invoice_currency_code']); - $link = 'https://' . $config_base_url . '/guest/guest_view_invoice.php?invoice_id=' . $invoice_id . '&url_key=' . $url_key; - $subject = "Invoice $invoice_number"; - $contacts = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL - AND (contact_primary = 1 OR contact_billing = 1) AND contact_email IS NOT NULL AND contact_email <> '' ORDER BY contact_primary DESC, contact_name ASC"); - $data = []; - while ($contact = mysqli_fetch_assoc($contacts)) { - if (!filter_var($contact['contact_email'], FILTER_VALIDATE_EMAIL) || isset($sent_to[strtolower($contact['contact_email'])])) { - continue; + $recipients = billingEmailRecipients($client_id); + if ($recipients) { + [$subject, $email] = billingInvoiceEmail($invoice); + $attach = []; + if (billingReminderRules()['attach_pdf'] && ($file = billingEmailPdf(billingPdf('invoice', $invoice)))) { + $attach[] = $file; } - $sent_to[strtolower($contact['contact_email'])] = $contact['contact_email']; - $body = 'Hello ' . htmlspecialchars($contact['contact_name']) . ',

An invoice regarding "' . htmlspecialchars($invoice['invoice_scope']) . '" has been generated. Please view the details below.' - . "

Invoice: $invoice_number
Issue Date: {$invoice['invoice_date']}
Total: " . htmlspecialchars($money) . "
Due Date: {$invoice['invoice_due']}" - . '


To view your invoice, please click here.


--
' . htmlspecialchars($company['company_name'] ?? '') . ' - Billing
' - . htmlspecialchars($settings['config_invoice_from_email'] ?? '') . '
' . htmlspecialchars($company['phone_display'] ?? ''); - $data[] = [ - 'from' => escapeSql($settings['config_invoice_from_email'] ?? ''), - 'from_name' => escapeSql($settings['config_invoice_from_name'] ?? ''), - 'recipient' => escapeSql($contact['contact_email']), - 'recipient_name' => escapeSql($contact['contact_name']), - 'subject' => escapeSql($subject), - 'body' => mysqli_real_escape_string($mysqli, $body), - ]; + $sent_to = billingEmailQueue($recipients, $subject, $email, ['attach' => $attach]); } - if ($data && addToMailQueue($data) === true) { + if ($sent_to) { mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Sent' WHERE invoice_id = $invoice_id"); - billingLog('invoice', $invoice_id, 'Sent', 'Emailed to ' . implode(', ', $sent_to)); + billingLog('invoice', $invoice_id, 'Sent', 'Emailed to ' . implode(', ', $sent_to) . ($attach ? ' with the PDF' : '')); } else { - $sent_to = []; - billingLog('invoice', $invoice_id, 'Draft', $data ? 'Could not be queued to email - left as a draft' : 'Nobody to email it to - no primary or billing contact with an email address'); + billingLog('invoice', $invoice_id, 'Draft', 'Nobody to email it to - no primary or billing contact with an email address'); } } diff --git a/functions/billing_email.php b/functions/billing_email.php new file mode 100644 index 000000000..17e1dabd5 --- /dev/null +++ b/functions/billing_email.php @@ -0,0 +1,773 @@ + false, 'days' => [1, 30], 'repeat' => 30, 'statement_monthly' => false, 'statement_day' => 1, 'attach_pdf' => true]; + try { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_send_invoice_reminders, config_invoice_reminder_days, config_invoice_reminder_repeat, + config_statement_monthly, config_statement_day, config_billing_email_attach_pdf FROM settings WHERE company_id = 1")); + } catch (mysqli_sql_exception $e) { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_send_invoice_reminders FROM settings WHERE company_id = 1")); + } + if ($row) { + $rules['enabled'] = intval($row['config_send_invoice_reminders'] ?? 0) === 1; + if (array_key_exists('config_invoice_reminder_days', $row)) { + $rules['days'] = billingReminderDaysParse($row['config_invoice_reminder_days']); + $rules['repeat'] = max(0, min(365, intval($row['config_invoice_reminder_repeat']))); + $rules['statement_monthly'] = intval($row['config_statement_monthly']) === 1; + $rules['statement_day'] = max(1, min(28, intval($row['config_statement_day']))); + $rules['attach_pdf'] = intval($row['config_billing_email_attach_pdf']) === 1; + } + } + return $rules; +} + +/** Days from a list - "-3, 0, 7 14" - as whole days from 60 before to a year after, sorted, each once. */ +function billingReminderDaysParse($text) { + $days = []; + foreach (preg_split('/[\s,;]+/', trim((string) $text)) as $part) { + if (preg_match('/^[+-]?\d{1,3}$/', $part)) { + $day = intval($part); + if ($day >= -60 && $day <= 365) { + $days[$day] = $day; + } + } + } + sort($days); + return array_values($days); +} + +/** Is a reminder due for an invoice $days after its due date (negative before it)? */ +function billingReminderOnDay($days, ?array $rules = null) { + $rules = $rules ?? billingReminderRules(); + $days = intval($days); + if (in_array($days, $rules['days'], true)) { + return true; + } + $last = $rules['days'] ? max(max($rules['days']), 0) : 0; + return $rules['repeat'] > 0 && $days > $last && ($days - $last) % $rules['repeat'] === 0; +} + +/** The schedule in words - "3 days before it is due, on the day, 7 and 30 days late, then every 30 days". */ +function billingReminderScheduleText(?array $rules = null) { + $rules = $rules ?? billingReminderRules(); + $parts = []; + $before = array_reverse(array_map('abs', array_filter($rules['days'], function ($day) { + return $day < 0; + }))); + $after = array_values(array_filter($rules['days'], function ($day) { + return $day > 0; + })); + $list = function ($days) { + return count($days) > 1 ? implode(', ', array_slice($days, 0, -1)) . ' and ' . end($days) : (string) reset($days); + }; + if ($before) { + $parts[] = $list($before) . ' day' . (end($before) === 1 && count($before) === 1 ? '' : 's') . ' before it is due'; + } + if (in_array(0, $rules['days'], true)) { + $parts[] = 'on the due date'; + } + if ($after) { + $parts[] = $list($after) . ' day' . (end($after) === 1 && count($after) === 1 ? '' : 's') . ' late'; + } + if ($rules['repeat'] > 0) { + $parts[] = ($parts ? 'then ' : '') . 'every ' . $rules['repeat'] . ' day' . ($rules['repeat'] === 1 ? '' : 's') . ($after || in_array(0, $rules['days'], true) ? '' : ' after it is due') . ' until it is paid'; + } + return $parts ? implode(', ', $parts) : 'never'; +} + +/** + * 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. + */ +function billingReminderNext(array $invoice, ?array $rules = null, $late_only = false) { + $rules = $rules ?? billingReminderRules(); + $due = substr((string) ($invoice['invoice_due'] ?? ''), 0, 10); + if (!$rules['enabled'] || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $due)) { + return null; + } + $today = new DateTime('today'); + $due_date = new DateTime($due); + $from = (int) $due_date->diff($today)->format('%r%a') + 1; + if ($late_only) { + $from = max($from, 1); + } + for ($days = $from; $days <= $from + 400; $days++) { + if (billingReminderOnDay($days, $rules)) { + $date = (clone $due_date)->modify(($days >= 0 ? '+' : '') . $days . ' days'); + return ['date' => $date->format('Y-m-d'), 'days' => $days]; + } + } + return null; +} + +/** Will a recurring autopay charge this invoice on its due date? Then it isn't reminded before. */ +function billingReminderAutopay(array $invoice) { + global $mysqli; + $recurring_id = intval($invoice['invoice_recurring_invoice_id'] ?? 0); + return $recurring_id > 0 && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_id LIMIT 1")) > 0; +} + +/** How late an invoice is, in words - "due in 3 days", "due today", "7 days late". */ +function billingReminderWhen($days) { + $days = intval($days); + if ($days < 0) { + return 'due in ' . (-$days) . ' day' . ($days === -1 ? '' : 's'); + } + return $days === 0 ? 'due today' : $days . ' day' . ($days === 1 ? '' : 's') . ' late'; +} + +/* ------------------------------------------------------------ The email */ + +/** A date for an email - "Oct 20, 2026". */ +function billingEmailDate($date) { + $time = strtotime((string) $date); + return $time ? date('M j, Y', $time) : (string) $date; +} + +/** + * One billing email as HTML. $email, every value raw - it is escaped here: + * kind the small heading - Invoice, Payment reminder, Receipt + * tone its colour - primary, success, warning or danger + * title the heading + * name who it is to - "Hello Name," (none for an internal one) + * intro paragraphs before the summary + * note the agent's own words, kept as typed + * summary label => value; strong names the label to make stand out + * lines a table - ['head' => [...], 'align' => [...], 'rows' => [[cell, ...]]], a cell + * plain text or ['text' => ..., 'url' => ..., 'tone' => danger] + * button ['label' => ..., 'url' => ...] + * after paragraphs after the button + * footnote a line under the card - why they got it + */ +function billingEmailHtml(array $email) { + global $config_base_url; + $e = function ($value) { + return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); + }; + $tones = ['primary' => '#0d6efd', 'success' => '#198754', 'warning' => '#b35c00', 'danger' => '#c42b37']; + $accent = $tones[$email['tone'] ?? 'primary'] ?? $tones['primary']; + $text = '#212529'; + $muted = '#6c757d'; + $line = '#e5e7eb'; + $font = "font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;"; + $company = billingCompany(); + $company_name = (string) ($company['company_name'] ?? ''); + $paragraph = function ($text_value) use ($e, $text) { + return '

' . nl2br($e($text_value)) . '

'; + }; + + $logo = !empty($company['logo_url']) && !empty($config_base_url) + ? '' . $e($company_name) . '' + : '
' . $e($company_name) . '
'; + + $body = ''; + if (!empty($email['name'])) { + $body .= $paragraph('Hello ' . $email['name'] . ','); + } + foreach ((array) ($email['intro'] ?? []) as $text_value) { + $body .= $paragraph($text_value); + } + if (trim((string) ($email['note'] ?? '')) !== '') { + $body .= '' + . '
' . $e(trim($email['note'])) . '
'; + } + if (!empty($email['summary'])) { + $rows = ''; + $strong = (string) ($email['strong'] ?? ''); + $first = true; + foreach ($email['summary'] as $label => $value) { + $big = $label === $strong; + // The figure that matters stands out - with a rule above it when it closes the box + $rule = $big && !$first ? 'border-top:1px solid ' . $line . ';padding-top:11px;' : ''; + $rows .= '' . $e($label) . '' + . '' . $e($value) . ''; + $first = false; + } + $body .= '' + . '
' . $rows . '
'; + } + if (!empty($email['lines']['rows'])) { + $align = (array) ($email['lines']['align'] ?? []); + $head = ''; + foreach ((array) $email['lines']['head'] as $i => $heading) { + $head .= '' . $e($heading) . ''; + } + $rows = ''; + foreach ($email['lines']['rows'] as $cells) { + $rows .= ''; + foreach (array_values($cells) as $i => $cell) { + $cell = is_array($cell) ? $cell : ['text' => $cell]; + $color = !empty($cell['tone']) ? ($tones[$cell['tone']] ?? $text) : $text; + $content = !empty($cell['url']) + ? '' . $e($cell['text']) . '' + : $e($cell['text']); + $rows .= '' . $content . ''; + } + $rows .= ''; + } + $body .= '' . $head . '' . $rows . '
'; + } + if (!empty($email['button']['url'])) { + $body .= '
' + . '' . $e($email['button']['label']) . '' + . '
'; + } + foreach ((array) ($email['after'] ?? []) as $text_value) { + $body .= '

' . nl2br($e($text_value)) . '

'; + } + + $foot = array_filter([ + $company_name, + formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '), + implode(' · ', array_filter([$company['phone_display'] ?? '', $company['company_email'] ?? '', $company['company_website'] ?? ''])), + ]); + + return '' . $e($email['title'] ?? '') . '' + . '' + . '
' + . '' + . '' + . '' + . '' + . '
' . $logo . '
' + . '
' . $e($email['kind'] ?? '') . '
' + . '

' . $e($email['title'] ?? '') . '

' + . $body + . '
' . implode('
', array_map($e, $foot)) . '
' + . (!empty($email['footnote']) ? '
' . $e($email['footnote']) . '
' : '') + . '
'; +} + +/** Who billing emails come from - invoices and quotes each have their own address. */ +function billingEmailFrom($which = 'invoice') { + global $mysqli; + static $from = null; + if ($from === null) { + $from = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_invoice_from_email, config_invoice_from_name, config_quote_from_email, config_quote_from_name, + config_invoice_paid_notification_email, config_smtp_provider FROM settings WHERE company_id = 1")) ?: []; + } + if ($which === 'quote' && !empty($from['config_quote_from_email'])) { + return ['email' => (string) $from['config_quote_from_email'], 'name' => (string) $from['config_quote_from_name']]; + } + if ($which === 'notify') { + return ['email' => (string) ($from['config_invoice_paid_notification_email'] ?? ''), 'name' => '']; + } + if ($which === 'ready') { + return ['email' => (string) ($from['config_smtp_provider'] ?? ''), 'name' => '']; + } + return ['email' => (string) ($from['config_invoice_from_email'] ?? ''), 'name' => (string) ($from['config_invoice_from_name'] ?? '')]; +} + +/** Can billing emails go out at all - mail is set up? */ +function billingEmailReady() { + return billingEmailFrom('ready')['email'] !== '' && billingEmailFrom()['email'] !== ''; +} + +/** + * A client's contacts to email: the ones picked (any of the client's with an + * email address), or with none picked the defaults for $type - the primary + * and billing contacts, or for a quote the primary contact. + * [['id', 'name', 'email'], ...], each address once. + */ +function billingEmailRecipients($client_id, ?array $contact_ids = null, $type = 'invoice') { + global $mysqli; + $client_id = intval($client_id); + if ($contact_ids !== null) { + $contact_ids = array_filter(array_map('intval', $contact_ids)); + if (!$contact_ids) { + return []; + } + $filter = 'AND contact_id IN (' . implode(', ', $contact_ids) . ')'; + } else { + $filter = documentDefaultContactFilterSql($type === 'quote' ? 'quote' : 'invoice'); + } + $recipients = []; + $sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email FROM contacts + WHERE contact_client_id = $client_id AND contact_archived_at IS NULL AND contact_email IS NOT NULL AND contact_email != '' $filter + ORDER BY contact_primary DESC, contact_billing DESC, contact_name ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $key = strtolower(trim($row['contact_email'])); + if (!filter_var(trim($row['contact_email']), FILTER_VALIDATE_EMAIL) || isset($recipients[$key])) { + continue; + } + $recipients[$key] = ['id' => intval($row['contact_id']), 'name' => (string) $row['contact_name'], 'email' => trim($row['contact_email'])]; + } + return array_values($recipients); +} + +/** + * Queue a billing email to each recipient, greeting each by name. $opts: + * from ('invoice' or 'quote' - whose address it comes from) and attach (a + * list of billingEmailPdf() files). Who it was queued to, "Name (email)". + */ +function billingEmailQueue(array $recipients, $subject, array $email, array $opts = []) { + global $mysqli; + $from = billingEmailFrom($opts['from'] ?? 'invoice'); + $attachments = array_values(array_filter((array) ($opts['attach'] ?? []))); + $data = []; + $sent = []; + foreach ($recipients as $recipient) { + $address = trim((string) ($recipient['email'] ?? '')); + if (!filter_var($address, FILTER_VALIDATE_EMAIL) || isset($sent[strtolower($address)])) { + continue; + } + $name = (string) ($recipient['name'] ?? ''); + $html = billingEmailHtml(['name' => array_key_exists('greet', $recipient) ? $recipient['greet'] : $name] + $email); + $data[] = [ + 'from' => mysqli_real_escape_string($mysqli, $from['email']), + 'from_name' => mysqli_real_escape_string($mysqli, $from['name']), + 'recipient' => mysqli_real_escape_string($mysqli, $address), + 'recipient_name' => mysqli_real_escape_string($mysqli, $name), + 'subject' => mysqli_real_escape_string($mysqli, $subject), + 'body' => mysqli_real_escape_string($mysqli, $html), + 'attachments' => $attachments, + ]; + $sent[strtolower($address)] = $name !== '' ? "$name ($address)" : $address; + } + if ($data) { + addToMailQueue($data); + } + return array_values($sent); +} + +/** + * A document's PDF, saved where the mail queue can attach it - ['path' => + * app-relative path, 'name' => file name], or null when it can't be made. + * They go in uploads/tmp/billing_mail, which the web can't reach, and the + * nightly run clears them out after a week. $pdf is a billingPdf() or + * billingStatementPdf() result. + */ +function billingEmailPdf(array $pdf) { + $dir = 'uploads/tmp/billing_mail/' . bin2hex(random_bytes(12)); + $full = dirname(__DIR__) . '/' . $dir; + if (!is_dir($full) && !@mkdir($full, 0775, true)) { + return null; + } + $name = preg_replace('/[^A-Za-z0-9._-]+/', '-', (string) $pdf['name']); + if (@file_put_contents("$full/$name", $pdf['data']) === false) { + return null; + } + return ['path' => "$dir/$name", 'name' => $name]; +} + +/** Clear PDFs made for emails more than $days days ago. How many went. */ +function billingEmailPdfCleanup($days = 7) { + $base = dirname(__DIR__) . '/uploads/tmp/billing_mail'; + if (!is_dir($base)) { + return 0; + } + $cutoff = time() - max(1, intval($days)) * 86400; + $removed = 0; + foreach (glob("$base/*", GLOB_ONLYDIR) ?: [] as $dir) { + if (filemtime($dir) >= $cutoff) { + continue; + } + foreach (glob("$dir/*") ?: [] as $file) { + @unlink($file); + } + if (@rmdir($dir)) { + $removed++; + } + } + return $removed; +} + +/* ----------------------------------------------- What each one says */ + +/** The footnote for a client's billing contact. */ +function billingEmailFootnote($client_name) { + $company = billingCompany(); + return "You received this email as a billing contact for $client_name with " . ($company['company_name'] ?? 'us') . '.'; +} + +/** + * An invoice email - [subject, email]. $opts: + * kind invoice (the default), or reminder + * note the agent's own words + * Paid, it is a receipt. A reminder says when it is or was due and what is + * still owed - firmer once it is late. + */ +function billingInvoiceEmail(array $invoice, array $opts = []) { + $number = billingNumber('invoice', $invoice); + $currency = (string) $invoice['invoice_currency_code']; + $paid = invoicePaid($invoice['invoice_id']); + $state = invoiceState($invoice, $paid); + $company = billingCompany(); + $company_name = (string) ($company['company_name'] ?? ''); + $scope = trim((string) $invoice['invoice_scope']); + $url = billingGuestUrl('invoice', $invoice); + $owed = $state['balance'] > 0 && !in_array($invoice['invoice_status'], ['Paid', 'Cancelled', 'Non-Billable'], true); + $pay = $owed && billingOnlinePayments(); + $kind = ($opts['kind'] ?? 'invoice') === 'reminder' && $owed ? 'reminder' : 'invoice'; + $contact_line = 'Questions? Reply to this email' . (!empty($company['phone_display']) ? ' or call us on ' . $company['phone_display'] : '') . '.'; + + $summary = ['Invoice' => $number]; + if ($scope !== '') { + $summary['For'] = $scope; + } + $summary['Issued'] = billingEmailDate($invoice['invoice_date']); + if ($owed) { + $summary['Due'] = billingEmailDate($invoice['invoice_due']); + } + $summary['Total'] = billingMoney($invoice['invoice_amount'], $currency); + if ($paid > 0) { + $summary['Paid'] = billingMoney($paid, $currency); + } + $email = [ + 'note' => $opts['note'] ?? '', + 'button' => ['label' => $pay ? 'View and pay invoice' : 'View invoice', 'url' => $url], + 'footnote' => billingEmailFootnote($invoice['client_name']), + ]; + + if (!$owed && $invoice['invoice_status'] === 'Paid') { + return ["Receipt for invoice $number from $company_name", $email + [ + 'kind' => 'Receipt', 'tone' => 'success', 'title' => "Invoice $number is paid", + 'intro' => ['Thank you - invoice ' . $number . ($scope !== '' ? " for \"$scope\"" : '') . ' is paid in full.'], + 'summary' => $summary, 'strong' => 'Paid', + 'after' => ['Please keep this email for your records. You can download the invoice as a PDF from its page.'], + ]]; + } + + if ($kind === 'reminder') { + $days = $state['days'] !== null ? -intval($state['days']) : 0; + $balance = billingMoney($state['balance'], $currency); + $summary['Balance due'] = $balance; + if ($days < 0) { + $subject = "Reminder: invoice $number is due " . billingEmailDate($invoice['invoice_due']); + $intro = ["A friendly reminder that invoice $number" . ($scope !== '' ? " for \"$scope\"" : '') . " is due on " . billingEmailDate($invoice['invoice_due']) . ", with $balance to pay."]; + $tone = 'primary'; + $title = 'Due ' . billingEmailDate($invoice['invoice_due']); + } elseif ($days === 0) { + $subject = "Reminder: invoice $number is due today"; + $intro = ["A friendly reminder that invoice $number" . ($scope !== '' ? " for \"$scope\"" : '') . " is due today, with $balance to pay."]; + $tone = 'warning'; + $title = 'Due today'; + } else { + $subject = "Overdue: invoice $number is $days day" . ($days === 1 ? '' : 's') . ' past due'; + $intro = ["Invoice $number" . ($scope !== '' ? " for \"$scope\"" : '') . ' was due on ' . billingEmailDate($invoice['invoice_due']) . " and $balance is still outstanding. Please arrange payment as soon as you can."]; + $tone = 'danger'; + $title = "$days day" . ($days === 1 ? '' : 's') . ' past due'; + } + return [$subject, $email + [ + 'kind' => 'Payment reminder', 'tone' => $tone, 'title' => "Invoice $number - $title", + 'intro' => $intro, 'summary' => $summary, 'strong' => 'Balance due', + 'after' => ["If you have already paid, thank you, and please disregard this reminder. $contact_line"], + ]]; + } + + $summary[$owed ? 'Balance due' : 'Balance'] = billingMoney($state['balance'], $currency); + return ["Invoice $number from $company_name", $email + [ + 'kind' => 'Invoice', 'tone' => 'primary', 'title' => "Invoice $number", + 'intro' => ['Here is your invoice' . ($scope !== '' ? " for \"$scope\"" : '') . '.' . ($owed ? ' Payment is due by ' . billingEmailDate($invoice['invoice_due']) . '.' : '')], + 'summary' => $summary, 'strong' => $owed ? 'Balance due' : 'Balance', + 'after' => [($pay ? 'You can pay online by card from the invoice page, and download it as a PDF. ' : 'You can download it as a PDF from the invoice page. ') . $contact_line], + ]]; +} + +/** A quote email - [subject, email]. $opts: note. */ +function billingQuoteEmail(array $quote, array $opts = []) { + $number = billingNumber('quote', $quote); + $currency = (string) $quote['quote_currency_code']; + $company = billingCompany(); + $scope = trim((string) $quote['quote_scope']); + $groups = quoteGroups($quote); + $summary = ['Quote' => $number]; + if ($scope !== '') { + $summary['For'] = $scope; + } + $summary['Date'] = billingEmailDate($quote['quote_date']); + $summary['Valid until'] = billingEmailDate($quote['quote_expire']); + $strong = 'Total'; + if (quoteHasRecurring($groups)) { + foreach ($groups as $group) { + if ($group['items'] || $group['frequency'] === '') { + $label = $group['frequency'] === '' ? 'Up front' : $group['label']; + $summary[$label] = billingMoney($group['total'], $currency); + if ($group['frequency'] === '') { + $strong = $label; + } + } + } + } else { + $summary['Total'] = billingMoney($quote['quote_amount'], $currency); + } + return ["Quote $number from " . ($company['company_name'] ?? '') . ($scope !== '' ? " - $scope" : ''), [ + 'kind' => 'Quote', 'tone' => 'primary', 'title' => "Quote $number", + 'intro' => ['Thank you for the opportunity. Here is our quote' . ($scope !== '' ? " for \"$scope\"" : '') . ', valid until ' . billingEmailDate($quote['quote_expire']) . '.'], + 'note' => $opts['note'] ?? '', + 'summary' => $summary, 'strong' => $strong, + 'button' => ['label' => 'View and accept quote', 'url' => billingGuestUrl('quote', $quote)], + 'after' => ['You can accept or decline it online, and download it as a PDF. Questions? Reply to this email.'], + 'footnote' => billingEmailFootnote($quote['client_name']), + ]]; +} + +/** + * A payment received - [subject, email]. $applied: what went on each + * invoice, [['invoice' => billingRow(), 'amount' => ...], ...]. $payment: + * date, method, reference, currency. + */ +function billingPaymentEmail(array $applied, array $payment) { + $currency = (string) ($payment['currency'] ?? ($applied[0]['invoice']['invoice_currency_code'] ?? '')); + $total = array_sum(array_column($applied, 'amount')); + $first = $applied[0]['invoice']; + $summary = ['Amount paid' => billingMoney($total, $currency), 'Date' => billingEmailDate($payment['date'] ?? date('Y-m-d'))]; + if (!empty($payment['method'])) { + $summary['Method'] = $payment['method']; + } + if (!empty($payment['reference'])) { + $summary['Reference'] = $payment['reference']; + } + $email = ['kind' => 'Payment received', 'tone' => 'success', 'footnote' => billingEmailFootnote($first['client_name'])]; + if (count($applied) === 1) { + $number = billingNumber('invoice', $first); + $balance = invoiceState($first, invoicePaid($first['invoice_id']))['balance']; + $summary['Invoice'] = $number; + $summary[$balance > 0 ? 'Still to pay' : 'Invoice balance'] = $balance > 0 ? billingMoney($balance, $currency) : 'Paid in full'; + return ["Payment received for invoice $number", $email + [ + 'title' => 'Thank you for your payment', + 'intro' => ['We have received your payment of ' . billingMoney($total, $currency) . " for invoice $number."], + 'summary' => $summary, 'strong' => 'Amount paid', + 'button' => ['label' => 'View invoice', 'url' => billingGuestUrl('invoice', $first)], + 'after' => ['Please keep this email as your receipt.'], + ]]; + } + $rows = []; + foreach ($applied as $entry) { + $balance = invoiceState($entry['invoice'], invoicePaid($entry['invoice']['invoice_id']))['balance']; + $rows[] = [['text' => billingNumber('invoice', $entry['invoice']), 'url' => billingGuestUrl('invoice', $entry['invoice'])], + billingMoney($entry['amount'], $currency), $balance > 0 ? billingMoney($balance, $currency) : 'Paid']; + } + return ['Payment received - ' . count($applied) . ' invoices', $email + [ + 'title' => 'Thank you for your payment', + 'intro' => ['We have received your payment of ' . billingMoney($total, $currency) . ' and applied it to these invoices.'], + 'summary' => $summary, 'strong' => 'Amount paid', + 'lines' => ['head' => ['Invoice', 'Applied', 'Balance'], 'align' => ['left', 'right', 'right'], 'rows' => $rows], + 'after' => ['Please keep this email as your receipt.'], + ]]; +} + +/** An email to one of our own addresses - no greeting, from the invoice or quote address. Who it went to. */ +function billingNotifyEmail($to, $subject, array $email, $from = 'invoice') { + $to = trim((string) $to); + if (!filter_var($to, FILTER_VALIDATE_EMAIL)) { + return []; + } + return billingEmailQueue([['email' => $to, 'name' => '', 'greet' => '']], $subject, $email, ['from' => $from]); +} + +/** + * Tell our team a client answered a quote online - to the quote notification + * address in the quote settings. $accepted or declined. + */ +function billingQuoteAnsweredNotify($quote_id, $accepted) { + global $mysqli, $config_base_url; + $quote = billingRow('quote', $quote_id, false); + $to = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_quote_notification_email FROM settings WHERE company_id = 1"))[0] ?? ''); + if (!$quote || $to === '') { + return []; + } + $number = billingNumber('quote', $quote); + $word = $accepted ? 'accepted' : 'declined'; + return billingNotifyEmail($to, 'Quote ' . ucfirst($word) . " - {$quote['client_name']} - Quote $number", [ + 'kind' => 'Quote ' . $word, 'tone' => $accepted ? 'success' : 'danger', 'title' => "{$quote['client_name']} $word $number", + 'intro' => ["{$quote['client_name']} $word quote $number online" . (trim((string) $quote['quote_scope']) !== '' ? " - \"{$quote['quote_scope']}\"" : '') . '.'], + 'summary' => ['Client' => $quote['client_name'], 'Quote' => $number, 'Total' => billingMoney($quote['quote_amount'], $quote['quote_currency_code'])], + 'button' => ['label' => 'Open in ITFlow', 'url' => "https://$config_base_url/agent/quote.php?quote_id=" . intval($quote['quote_id'])], + ], 'quote'); +} + +/** + * Tell the paid notification address (Invoice settings) that an invoice was + * paid - for online and automatic payments. Nothing when none is set. + */ +function billingPaymentNotify(array $invoice, $amount, $how) { + global $config_base_url; + $to = billingEmailFrom('notify')['email']; + if ($to === '') { + return; + } + $number = billingNumber('invoice', $invoice); + $currency = (string) $invoice['invoice_currency_code']; + $balance = invoiceState($invoice, invoicePaid($invoice['invoice_id']))['balance']; + billingNotifyEmail($to, "Payment received - {$invoice['client_name']} - invoice $number", [ + 'kind' => 'Payment received', 'tone' => 'success', 'title' => "{$invoice['client_name']} paid $number", + 'intro' => ["$how payment of " . billingMoney($amount, $currency) . " on invoice $number for {$invoice['client_name']}."], + 'summary' => ['Client' => $invoice['client_name'], 'Invoice' => $number, 'Amount paid' => billingMoney($amount, $currency), 'Balance' => $balance > 0 ? billingMoney($balance, $currency) : 'Paid in full'], + 'strong' => 'Amount paid', + 'button' => ['label' => 'Open in ITFlow', 'url' => "https://$config_base_url/agent/invoice.php?invoice_id=" . intval($invoice['invoice_id'])], + ]); +} + +/** + * Send a payment received email for a payment on one invoice - to its + * client's primary and billing contacts - and log it on the invoice. + * $notify also tells the paid notification address. The addresses it went to. + */ +function billingPaymentSend($invoice_id, $amount, array $payment, $notify = false) { + $invoice = billingRow('invoice', $invoice_id, false); + if (!$invoice) { + return []; + } + [$subject, $email] = billingPaymentEmail([['invoice' => $invoice, 'amount' => $amount]], $payment + ['currency' => $invoice['invoice_currency_code']]); + $sent = billingEmailQueue(billingEmailRecipients($invoice['client_id']), $subject, $email); + if ($sent) { + billingLog('invoice', $invoice['invoice_id'], 'Sent', 'Payment receipt emailed to ' . implode(', ', $sent)); + } + if ($notify) { + billingPaymentNotify($invoice, $amount, $payment['how'] ?? 'Online'); + } + return $sent; +} + +/* ------------------------------------------------------------ Statements */ + +/** + * A client's statement - their invoices sent and not cancelled, dated up to + * $to (and from $from), the open ones only unless $include_paid, with what + * has been paid on each: + * client the client, with its currency + * from, to the period + * invoices each with paid, balance and days (late, negative while not due) + * total what is owed on them + * overdue what of it is past due + * aging current, 1-30, 31-60, 61-90 and 90+ days late + */ +function billingStatement($client_id, $from = '', $to = '', $include_paid = false) { + global $mysqli, $session_company_currency; + $client_id = intval($client_id); + $to = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $to) ? $to : date('Y-m-d'); + $from = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) $from) ? $from : ''; + $client = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT client_id, client_name, client_currency_code, client_reminders FROM clients WHERE client_id = $client_id")) ?: null; + $statement = ['client' => $client, 'from' => $from, 'to' => $to, 'include_paid' => (bool) $include_paid, 'invoices' => [], 'total' => 0.0, 'overdue' => 0.0, + 'aging' => ['Current' => 0.0, '1-30 days' => 0.0, '31-60 days' => 0.0, '61-90 days' => 0.0, 'Over 90 days' => 0.0], + 'currency' => (string) (($client['client_currency_code'] ?? '') ?: ($session_company_currency ?? '') ?: (billingCompany()['company_currency'] ?? ''))]; + if (!$client) { + return $statement; + } + $sql = mysqli_query($mysqli, "SELECT invoice_id, invoice_prefix, invoice_number, invoice_scope, invoice_date, invoice_due, invoice_status, invoice_amount, + invoice_currency_code, invoice_url_key, COALESCE(paid.amount, 0) AS paid + FROM invoices + LEFT JOIN (SELECT payment_invoice_id, SUM(payment_amount) AS amount FROM payments WHERE payment_archived_at IS NULL GROUP BY payment_invoice_id) AS paid + ON paid.payment_invoice_id = invoice_id + WHERE invoice_client_id = $client_id AND invoice_status NOT IN ('Draft', 'Cancelled', 'Non-Billable') + AND invoice_date <= '$to'" . ($from !== '' ? " AND invoice_date >= '$from'" : '') . " + ORDER BY invoice_date ASC, invoice_number ASC"); + $today = strtotime(date('Y-m-d')); + while ($row = mysqli_fetch_assoc($sql)) { + $row['balance'] = round(floatval($row['invoice_amount']) - floatval($row['paid']), 2); + if ($row['balance'] <= 0 && !$include_paid) { + continue; + } + $row['days'] = intval(round(($today - strtotime($row['invoice_due'])) / 86400)); + $row['client_name'] = $client['client_name']; + if ($row['balance'] > 0) { + $statement['total'] += $row['balance']; + $days = $row['days']; + $bucket = $days <= 0 ? 'Current' : ($days <= 30 ? '1-30 days' : ($days <= 60 ? '31-60 days' : ($days <= 90 ? '61-90 days' : 'Over 90 days'))); + $statement['aging'][$bucket] += $row['balance']; + if ($days > 0) { + $statement['overdue'] += $row['balance']; + } + } + $statement['invoices'][] = $row; + } + $statement['total'] = round($statement['total'], 2); + $statement['overdue'] = round($statement['overdue'], 2); + return $statement; +} + +/** A statement's period in words - "up to Oct 16, 2026", "Jul 1, 2026 to Oct 16, 2026". */ +function billingStatementPeriod(array $statement) { + return ($statement['from'] !== '' ? billingEmailDate($statement['from']) . ' to ' : 'up to ') . billingEmailDate($statement['to']); +} + +/** A statement as a PDF - ['name', 'data']. See functions/billing_pdf.php. */ +function billingStatementPdf(array $statement) { + require_once __DIR__ . '/../libs/TCPDF/tcpdf.php'; + require_once __DIR__ . '/billing_pdf.php'; + return billingStatementPdfRender($statement); +} + +/** A statement email - [subject, email]. $opts: note. */ +function billingStatementEmail(array $statement, array $opts = []) { + $currency = $statement['currency']; + $company = billingCompany(); + $rows = []; + foreach ($statement['invoices'] as $invoice) { + $late = $invoice['balance'] > 0 && $invoice['days'] > 0; + $rows[] = [ + ['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'], + ]; + } + $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; + }))]; + if ($statement['overdue'] > 0) { + $summary['Overdue'] = billingMoney($statement['overdue'], $currency); + } + $summary['Total due'] = billingMoney($statement['total'], $currency); + return ['Statement from ' . ($company['company_name'] ?? '') . ' - ' . billingEmailDate($statement['to']), [ + 'kind' => 'Statement', 'tone' => $statement['overdue'] > 0 ? 'warning' : 'primary', 'title' => 'Your account statement', + '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], + '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']), + ]]; +} + +/** + * 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. + */ +function billingStatementSend(array $statement, ?array $contact_ids = null, array $opts = []) { + [$subject, $email] = billingStatementEmail($statement, $opts); + $attach = []; + if (!empty($opts['attach'])) { + $file = billingEmailPdf(billingStatementPdf($statement)); + if ($file) { + $attach[] = $file; + } + } + return billingEmailQueue(billingEmailRecipients($statement['client']['client_id'], $contact_ids), $subject, $email, ['attach' => $attach]); +} diff --git a/functions/billing_pdf.php b/functions/billing_pdf.php index eed62228b..8961ecd86 100644 --- a/functions/billing_pdf.php +++ b/functions/billing_pdf.php @@ -38,12 +38,25 @@ class BillingPdf extends TCPDF { } } +/** The footers and the tax ID setting - a page has them loaded, the nightly run reads them here. */ +function billingPdfConfig() { + global $mysqli, $config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id; + if (isset($config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id)) { + return; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_invoice_footer, config_quote_footer, config_invoice_show_tax_id FROM settings WHERE company_id = 1")) ?: []; + $config_invoice_footer = $config_invoice_footer ?? (string) ($row['config_invoice_footer'] ?? ''); + $config_quote_footer = $config_quote_footer ?? (string) ($row['config_quote_footer'] ?? ''); + $config_invoice_show_tax_id = $config_invoice_show_tax_id ?? intval($row['config_invoice_show_tax_id'] ?? 0); +} + /** * Draw an invoice, quote or recurring invoice - or an invoice's packing slip * ($variant 'packing') - and return ['name' => file name, 'data' => the PDF]. */ function billingPdfRender($type, array $row, $variant = 'document') { global $mysqli, $config_invoice_footer, $config_quote_footer, $config_invoice_show_tax_id; + billingPdfConfig(); $t = billingType($type); $c = $t['col']; @@ -351,3 +364,126 @@ function billingPdfRender($type, array $row, $variant = 'document') { $name = preg_replace('/[^A-Za-z0-9_\-]+/', '_', trim("{$date}_{$row['client_name']}_" . str_replace(' ', '_', $title) . "_$number", '_')) . '.pdf'; return ['name' => $name, 'data' => $pdf->Output($name, 'S')]; } + +/** + * A client's statement as a PDF - billingStatement() - in the same look: + * who it is from and for, the date and period, what is owed and how late, + * then each invoice with what was billed, paid and is left. ['name', 'data']. + */ +function billingStatementPdfRender(array $statement) { + global $config_invoice_footer; + billingPdfConfig(); + + $company = billingCompany(); + $client = $statement['client']; + $bill_to = billingBillTo($client['client_id']); + $currency = $statement['currency']; + $e = function ($value) { + return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); + }; + $money = function ($amount) use ($currency, $e) { + return $e(billingMoney($amount, $currency)); + }; + $grey = '#6c757d'; + $red = '#c42b37'; + $label = function ($text) use ($grey, $e) { + return '' . $e(strtoupper($text)) . ''; + }; + + $format = in_array($company['company_country'] ?? '', ['United States', 'USA', 'US', 'Canada'], true) ? 'LETTER' : 'A4'; + $pdf = new BillingPdf('P', 'mm', $format, true, 'UTF-8', false); + $pdf->SetCreator('ITFlow'); + $pdf->SetAuthor((string) ($company['company_name'] ?? '')); + $pdf->SetTitle('Statement ' . $client['client_name']); + $pdf->SetMargins(16, 14, 16); + $pdf->SetHeaderMargin(0); + $pdf->SetFooterMargin(12); + $pdf->SetAutoPageBreak(true, 20); + $pdf->setFontSubsetting(true); + $pdf->setImageScale(1.5); + $pdf->footer_label = trim(($company['company_name'] ?? '') . ' · Statement · ' . $client['client_name'], ' ·'); + $pdf->AddPage(); + $margins = $pdf->getMargins(); + $width = $pdf->getPageWidth() - $margins['left'] - $margins['right']; + + // Who it is from, and what it is + $from_lines = array_filter([ + formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', "\n"), + implode(' · ', array_filter([$company['company_email'] ?? '', $company['phone_display'] ?? ''])), + $company['company_website'] ?? '', + ]); + $logo = !empty($company['logo_path']) ? '
' : ''; + $dates = ['Statement date' => date('Y-m-d'), 'Period' => $statement['from'] !== '' ? $statement['from'] . ' to ' . $statement['to'] : 'Up to ' . $statement['to']]; + $dates_html = ''; + foreach ($dates as $date_label => $value) { + $dates_html .= '' . $e($date_label) . '' . $e($value) . ''; + } + $html = ' + + +
' . $logo . '' . $e($company['company_name'] ?? '') . '
' . nl2br($e(implode("\n", $from_lines))) . '
STATEMENT
' . $e($client['client_name']) . '
+ ' . $dates_html . '
'; + $pdf->SetFont('dejavusans', '', 8.5); + $pdf->SetTextColor(33, 37, 41); + $pdf->writeHTML($html, true, false, true, false, ''); + $pdf->SetDrawColor(222, 226, 230); + $pdf->SetLineWidth(0.2); + $pdf->Ln(1); + $pdf->Line($margins['left'], $pdf->GetY(), $margins['left'] + $width, $pdf->GetY()); + $pdf->Ln(4); + + // Who it is for, and what is owed + $to_lines = array_filter([ + formatAddress($bill_to['location_address'] ?? '', $bill_to['location_city'] ?? '', $bill_to['location_state'] ?? '', $bill_to['location_zip'] ?? '', $bill_to['location_country'] ?? '', "\n"), + $bill_to['contact_name'] ?? '', + implode(' · ', array_filter([$bill_to['contact_email'] ?? '', $bill_to['contact_phone'] ?? ''])), + ]); + $html = ' + + +
' . $label('Statement for') . '
' . $e($bill_to['client_name'] ?? $client['client_name']) . '
' . nl2br($e(implode("\n", $to_lines))) . '
' . $label('Total due') . '
' . $money($statement['total']) . '' + . ($statement['overdue'] > 0 ? '
' . $money($statement['overdue']) . ' of it overdue' : '') . '
'; + $pdf->writeHTML($html, true, false, true, false, ''); + $pdf->Ln(2); + + // How late it is + $cells = ''; + foreach ($statement['aging'] as $bucket => $amount) { + $late = $bucket !== 'Current' && $amount > 0; + $cells .= '' . $label($bucket) . '
' . $money($amount) . ''; + } + $pdf->writeHTML('' . $cells . '
', true, false, true, false, ''); + $pdf->Ln(3); + + // Each invoice + $th = 'font-size:6.5pt; color:' . $grey . '; font-weight:bold; border-bottom:0.6px solid #adb5bd;'; + $td = 'border-bottom:0.3px solid #dee2e6;'; + $html = ' + + '; + foreach ($statement['invoices'] as $invoice) { + $late = $invoice['balance'] > 0 && $invoice['days'] > 0; + $html .= ' + + + + + '; + } + if (!$statement['invoices']) { + $html .= ''; + } + $html .= '
DATEINVOICEDUETOTALPAIDBALANCE
' . $e($invoice['invoice_date']) . '' . $e(billingNumber('invoice', $invoice)) . '' . (trim((string) $invoice['invoice_scope']) !== '' ? '
' . $e($invoice['invoice_scope']) . '' : '') . '
' . $e($invoice['invoice_due']) . ($late ? '
' . intval($invoice['days']) . ' days late' : '') . '
' . $money($invoice['invoice_amount']) . '' . (floatval($invoice['paid']) > 0 ? $money($invoice['paid']) : '-') . '' . ($invoice['balance'] > 0 ? $money($invoice['balance']) : 'Paid') . '
Nothing owed in this period.
Total due' . $money($statement['total']) . '
'; + $pdf->writeHTML($html, true, false, true, false, ''); + + $footer = trim((string) $config_invoice_footer); + if ($footer !== '') { + $pdf->Ln(4); + $pdf->SetFont('dejavusans', '', 7.5); + $pdf->SetTextColor(108, 117, 125); + $pdf->MultiCell($width, 4, $footer, 0, 'C', false, 1); + } + + $name = preg_replace('/[^A-Za-z0-9_\-]+/', '_', trim($statement['to'] . '_' . $client['client_name'] . '_Statement', '_')) . '.pdf'; + return ['name' => $name, 'data' => $pdf->Output($name, 'S')]; +} diff --git a/guest/guest_pay_invoice_stripe.php b/guest/guest_pay_invoice_stripe.php index 46a738df3..db7797e7f 100644 --- a/guest/guest_pay_invoice_stripe.php +++ b/guest/guest_pay_invoice_stripe.php @@ -252,46 +252,10 @@ if (isset($_GET['invoice_id'], $_GET['url_key']) && !isset($_GET['payment_intent } mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Payment', log_action = 'Create', log_description = 'Stripe payment of $pi_currency $pi_amount_paid against invoice $invoice_prefix$invoice_number - $pi_id $extended_log_desc', log_ip = '$ip', log_user_agent = '$user_agent', log_client_id = $pi_client_id"); - // Email Receipt - $sql_settings = mysqli_query($mysqli, "SELECT config_invoice_from_email, config_invoice_from_name, - config_invoice_paid_notification_email, config_smtp_host FROM settings WHERE company_id = 1"); - $settings = mysqli_fetch_assoc($sql_settings); - - $config_smtp_host = $settings['config_smtp_host']; - $config_invoice_from_name = escapeSql($settings['config_invoice_from_name']); - $config_invoice_from_email = escapeSql($settings['config_invoice_from_email']); - $config_invoice_paid_notification_email = escapeSql($settings['config_invoice_paid_notification_email']); - + // The client's receipt, and the paid notification address - functions/billing_email.php + $config_smtp_host = mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_smtp_host FROM settings WHERE company_id = 1"))[0] ?? ''; if (!empty($config_smtp_host)) { - $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

We have received online payment for the amount of " . $pi_currency . $pi_amount_paid . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount: " . numfmt_format_currency($currency_format, $pi_amount_paid, $invoice_currency_code) . "

Thank you for your business!


~
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - $data = [ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - // Internal notification - if (!empty($config_invoice_paid_notification_email)) { - $subject_internal = "Payment Received - $client_name - Invoice $invoice_prefix$invoice_number"; - $body_internal = "This is a notification that an invoice has been paid in ITFlow. Below is a copy of the receipt sent to the client:-

--------

$body"; - $data[] = [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $config_invoice_paid_notification_email, - 'recipient_name' => $contact_name, - 'subject' => $subject_internal, - 'body' => $body_internal, - ]; - } - $mail = addToMailQueue($data); - // Email logging - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Emailed Receipt!', history_invoice_id = $invoice_id"); + billingPaymentSend($invoice_id, $pi_amount_paid, ['date' => $pi_date, 'method' => 'Card', 'reference' => "Stripe - $pi_id", 'how' => 'Online card'], true); } // Redirect user to invoice diff --git a/guest/guest_post.php b/guest/guest_post.php index a9f95eba7..d42cf7234 100644 --- a/guest/guest_post.php +++ b/guest/guest_post.php @@ -64,19 +64,9 @@ if (isset($_GET['accept_quote'], $_GET['url_key'])) { $config_quote_notification_email = escapeSql($row['config_quote_notification_email']); $config_base_url = escapeSql($config_base_url); + // Our team hears - functions/billing_email.php if (!empty($config_smtp_host) && !empty($config_quote_notification_email)) { - $subject = "Quote Accepted - $client_name - Quote $quote_prefix$quote_number"; - $body = "Hello,

This is a notification that a quote has been accepted in ITFlow.

Client: $client_name
Quote: $quote_prefix$quote_number

~
$company_name - Billing
$config_quote_from_email"; - - $data[] = [ - 'from' => $config_quote_from_email, - 'from_name' => $config_quote_from_name, - 'recipient' => $config_quote_notification_email, - 'subject' => $subject, - 'body' => $body, - ]; - - $mail = addToMailQueue($data); + billingQuoteAnsweredNotify($quote_id, true); } flashAlert("Quote Accepted"); @@ -139,19 +129,9 @@ if (isset($_GET['decline_quote'], $_GET['url_key'])) { $config_quote_notification_email = escapeSql($row['config_quote_notification_email']); $config_base_url = escapeSql($config_base_url); + // Our team hears - functions/billing_email.php if (!empty($config_smtp_host) && !empty($config_quote_notification_email)) { - $subject = "Quote Declined - $client_name - Quote $quote_prefix$quote_number"; - $body = "Hello,

This is a notification that a quote has been declined in ITFlow.

Client: $client_name
Quote: $quote_prefix$quote_number

~
$company_name - Billing
$config_quote_from_email"; - - $data[] = [ - 'from' => $config_quote_from_email, - 'from_name' => $config_quote_from_name, - 'recipient' => $config_quote_notification_email, - 'subject' => $subject, - 'body' => $body, - ]; - - $mail = addToMailQueue($data); + billingQuoteAnsweredNotify($quote_id, false); } flashAlert("Quote Declined", 'danger');