diff --git a/CHANGELOG.md b/CHANGELOG.md index 2abf4523e..5b0a9a85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.3 -Update from Maintenance > Update as usual - this release has fifteen database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, 4.3.1 encrypts the mail passwords and tokens, 4.3.2 keeps the email the ticket mailbox took but couldn't make a ticket from, for your team to sort, 4.3.3 adds Undo send and Reply-To for ticket emails, 4.3.4 lets the links in emails stop working once they're done with and keeps your own wording for the emails about a ticket, and 4.3.5 adds ignored senders and ties a bounce to the email that bounced, and 4.3.6 lets text messaging be receive only. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. On nginx, where ITFlow's .htaccess files aren't read, add `location ^~ /uploads/mail_unprocessed/ { deny all; }` beside the other private folders - it holds copies of the email kept for Unprocessed Email. Emailed and texted replies now wait 10 seconds on the ticket page, with Undo, before they go - Admin > Settings > Tickets sets how long, or turns it off. Ticket emails sent from another address than the mailbox ITFlow reads now ask for replies at that mailbox (Reply-To) - turn that off in the same place if the From address is an alias of that mailbox and you'd rather clients only saw it. The links in emails that open a ticket, an invoice or a quote without signing in now stop working 90 days after it is done - a ticket closed, an invoice paid, a quote answered or run out - so after the update, links to ones done longer ago than that no longer open them. The client portal still shows them, and Admin > Settings > Security sets how long, or keeps them working as before. +Update from Maintenance > Update as usual - this release has sixteen database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, 4.3.1 encrypts the mail passwords and tokens, 4.3.2 keeps the email the ticket mailbox took but couldn't make a ticket from, for your team to sort, 4.3.3 adds Undo send and Reply-To for ticket emails, 4.3.4 lets the links in emails stop working once they're done with and keeps your own wording for the emails about a ticket, 4.3.5 adds ignored senders and ties a bounce to the email that bounced, 4.3.6 lets text messaging be receive only, and 4.3.7 lets invoices offer autopay to clients who haven't set it up. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. On nginx, where ITFlow's .htaccess files aren't read, add `location ^~ /uploads/mail_unprocessed/ { deny all; }` beside the other private folders - it holds copies of the email kept for Unprocessed Email. Emailed and texted replies now wait 10 seconds on the ticket page, with Undo, before they go - Admin > Settings > Tickets sets how long, or turns it off. Ticket emails sent from another address than the mailbox ITFlow reads now ask for replies at that mailbox (Reply-To) - turn that off in the same place if the From address is an alias of that mailbox and you'd rather clients only saw it. The links in emails that open a ticket, an invoice or a quote without signing in now stop working 90 days after it is done - a ticket closed, an invoice paid, a quote answered or run out - so after the update, links to ones done longer ago than that no longer open them. The client portal still shows them, and Admin > Settings > Security sets how long, or keeps them working as before. With Stripe set up, invoices from a recurring invoice without autopay now offer the client a Set up autopay button, in the email and on the invoice - Admin > Settings > Invoices turns that off, or a recurring invoice's page for one client. ### Security @@ -89,6 +89,10 @@ Update from Maintenance > Update as usual - this release has fifteen database ch - A support mailbox shared with other email: with From unknown senders too off, ITFlow takes out of the inbox only what is its own - email from contacts and clients' domains, replies to tickets, and bounces, delay notices and out-of-office replies that are about a ticket, an email ITFlow sent or a contact. The rest stays in the inbox, flagged so it isn't looked at again: a stranger's email, their out-of-office to an email someone sent from the mailbox by hand, a bounce for such an email (nobody gets a notice about it), and email from the mailbox's own address that ITFlow didn't send - a scanner emailing itself, a note to self - which is still never a ticket. With unknown senders on the mailbox is all ITFlow's, and everything is taken as before. - Bounces come back to the email they were about: a reply on a ticket says "Email to ... bounced" with what the mail server said, where it said it was emailed, and an invoice's or quote's history says its email bounced. The Mail Queue has a Bounced tab, and the email's window shows the mail server's reason. Each email ITFlow sends now has its own Message-ID, so the bounce finds it - one sent before the update is found by its address and subject. A bounce from an address the email wasn't sent to - someone's mail sent on to another mailbox - says where it came back from, and on an email to several people nobody is singled out for it. - Text messaging can be receive only: in Admin > Text Messaging, set the number to Receive only and texts to it still become tickets, replies on tickets and verification codes, but nothing is texted out - no replies by text, no ticket number texted back, no answers to STOP or HELP and no texts to clients. It needs no SID or secret, and the number doesn't have to be registered for sending, for a service where sending is a hassle to set up. Replies on a ticket that came in by text go by email or the portal, and the reply box says so, with the number to call. Texts waiting to go are cancelled when a number is set to Receive only. +- Autopay offered to clients: an invoice from a recurring invoice with no autopay now offers it - a Set up autopay box in the invoice email, under View and pay invoice, and the same button on the invoice's page. It opens a page that needs no sign-in, saying what autopay pays for that recurring invoice: how much each month, quarter or year, when the next invoice comes, whether this invoice is charged too, and the card fee when the client pays one. The client enters their name and email, ticks the box to agree, and adds a card in Stripe's own form on the page - autopay is then on, and each invoice after is charged on its due date. Needs Stripe set up in Payment Providers, and isn't offered for a recurring invoice that bills more than its card limit. +- When a client sets autopay up that way, the card is saved for them, the recurring invoice's history keeps who set it up, from which invoice and what they agreed to, agents get a notification, and whoever set it up gets a confirmation email with the card, the amount, when it's charged and how to stop it. Coming back to the same page again changes nothing, and once autopay is on the page says so. +- In the client portal, an invoice from a recurring invoice with no autopay offers it too: a contact with a card saved picks it and clicks Turn on autopay right there; one without goes to the same page to add a card, with their name and email filled in. Autopay turned on or off in the portal now goes in the recurring invoice's history, and agents are told when it's turned on. +- Offering autopay can be turned off: Admin > Settings > Invoices has Offer autopay on recurring invoices under Paid online, on to start with, and a recurring invoice's Autopay card has Offer autopay to the client, to stop asking one client who pays another way. The card says why it isn't offered when it isn't - the setting is off, the recurring invoice is paused, or it bills more than the card limit. ### Bug Fixes @@ -179,6 +183,7 @@ Update from Maintenance > Update as usual - this release has fifteen database ch - Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. A report naming an address that isn't on the email, or nobody: on an email to one person it is theirs ("address: why"); on one to several the named address is kept in email_bounce as it is, nobody on it is marked, and the reply has elsewhere => [address or '' => why]. A billing email's history is written the first time and for each address more. With config_ticket_email_parse_unknown_senders off the parser moves only what is ITFlow's: addBounce() takes $take_all and returns whether it was (a ticket by Message-ID or subject, emailMessageIdOurs() - itflow..@ or itflow.q.@, or in email_queue - mailQueueBounceRow(), the find split from mailQueueBounced(), or a contact's address), the own-address step moves only an email with ITFlow's Message-ID, a ticket's number in its subject or a ticket's email that it answers, and an auto-reply answering no ticket is set aside only from a contact, a client's domain or in answer to an ITFlow Message-ID (In-Reply-To, References); the rest is flagged and left, as a stranger's email is. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. - Text messaging receive only: database 4.3.6 adds sms_providers.sms_provider_send (1, or 0 for Receive only). smsSends() reads it; smsReady() is false when a provider doesn't send, so smsQueue() and everything that texts stops there, and smsNotSendingWhy() says why. smsReceiveOnly() and smsTicketTextedInNumber() drive the notes on Text Messaging, Text Messages, Settings > Notifications and Tickets and the ticket reply box; smsProviderCheck() needs the SID and secret only when sending; setting a provider to Receive only cancels the texts waiting to go (smsCancelWaiting()). Inbound (api/sms/skyetel.php, smsInbound()) is unchanged. - RMM sync (forum #3236): rmmSync() skips the client listing when $only is given, gives it half of $max_seconds through rmmDeadline() (rmmPastDeadline() for a kind to leave out what can wait), always syncs at least one linked client, records each synced client's device count, keeps the stored count when a kind returns devices null, and marks clients gone only from a whole list (a kind returns 'partial' with what it left). rmmUnifiSites() for unifi_cloud takes counts from Site Manager's GET /v1/sites (rmmUnifiSiteManagerSites(), by hostId and meta.name = internalReference), asks a console's connector for sites only when it has sites not in rmm_clients (rmmUnifiKnownSites()), and stops asking at the deadline; unifi_os counts per site only up to UNIFI_COUNT_SITES_MAX (50). rmmHttp() waits out a 429 with Retry-After up to RMM_RETRY_WAIT (10 s) and retries once (rmmHttpOnce() is one request), with a 'rate' hint. rmmWithoutSession() closes the PHP session around the slow calls in admin/post/rmm.php and agent/post/asset.php and reopens it for the message. +- Offering autopay: database 4.3.7 adds settings.config_invoice_offer_autopay and recurring_invoices.recurring_invoice_offer_autopay (both 1). functions/billing_pay.php: autopayOfferOn() reads the setting (guarded with settingsColumnExists()); autopayOfferBlocked(billingRow('recurring')) gives why a recurring invoice isn't offered, or '' - autopay on (recurring_payment_id), billingStripeProvider() null, the setting or the recurring invoice's switch off, status not 1 or archived, or billingOnlinePayAllowed() false for its amount; autopayOffer($invoice) is null for no recurring invoice, a Cancelled or Non-Billable invoice, no url key or another client's recurring invoice, else autopayOfferDetails() - number, title, amount, currency, period, fee (billingCardFeeTerms(billingCardFeeFor())), this_invoice (still owed and due after today, which the nightly autopay charges on its due date) and url (autopayOfferUrl(), guest/guest_autopay.php with the invoice's id and url key). autopayConsentText() is what the client agrees to. billingInvoiceEmail() puts billingAutopayOfferEmail() in the invoice kind only - not receipts or reminders - as emailHtml()'s new offer part (title, text, button, small; a box after the button with an outlined button). guest/guest_autopay.php checks the key with hash_equals() and guestLinkExpired(), says when autopay is on (invoiceAutopay()) or blocked, and otherwise posts name, email and agree through js/guest_autopay_stripe.js to guest_ajax.php?guest_autopay_checkout, where autopayCheckoutStart() makes the Stripe customer if the client has none (under GET_LOCK, retried once after billingStripeCustomerGone() with billingStripeCustomerForget()) and a Checkout Session - mode setup, ui_mode embedded_page, payment_method_types card, the customer, metadata itflow_autopay_invoice_id, itflow_recurring_invoice_id, itflow_client_id, itflow_consent_name, itflow_consent_email and itflow_consent - returning its client secret for stripe.initEmbeddedCheckout(). Its return_url is guest_post.php?guest_autopay_done with the invoice's id and key, where autopayCheckoutFinish() (under GET_LOCK per recurring invoice) treats a session already in an Autopay history line as done, then retrieves the session, requires mode setup, status complete, the metadata's invoice and recurring invoice and the client's own customer, retrieves its SetupIntent (succeeded) and PaymentMethod, saves the card once per payment method id in client_saved_payment_methods, replaces the recurring_payments row, writes billingLog('recurring', ..., 'Autopay') with the card, who, the invoice, the consent and the session id, logAudit(), appNotify('Autopay') and billingMailAutopayOn() (functions/billing_email.php, with autopayChangeText()). guest_view_invoice.php and client/invoice.php show [data-autopay-offer]; the portal's posts set_recurring_payment with a saved card that hasn't expired, and set_recurring_payment (client/post.php) now writes Autopay history and appNotify() when turned on. agent/recurring_invoice.php's Autopay card posts set_recurring_offer_autopay (agent/post/recurring_invoice.php, module_sales 2) while there is no autopay and Stripe is set up. guest_autopay_checkout, guest_autopay_done and set_recurring_offer_autopay are refused in demo mode. ## [26.12.2] diff --git a/admin/database_updates/4.3.7.php b/admin/database_updates/4.3.7.php new file mode 100644 index 000000000..7ec029a81 --- /dev/null +++ b/admin/database_updates/4.3.7.php @@ -0,0 +1,32 @@ + Invoices > Paid online), when + * card payments are on. The button opens a page that needs no sign-in: the client agrees, adds a card through + * Stripe, and each invoice from then on is charged on its due date. + * recurring_invoices.recurring_invoice_offer_autopay - the same for one recurring invoice (1), turned off on its + * page for a client who pays another way. + * + * Both start on. Re-runnable: each column is made only where it isn't there. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_offer_columns = [ + 'settings' => ['config_invoice_offer_autopay', 'config_invoice_paid_lead_to_client'], + 'recurring_invoices' => ['recurring_invoice_offer_autopay', 'recurring_invoice_email_notify'], + ]; + foreach ($itflow_offer_columns as $itflow_table => [$itflow_column, $itflow_after]) { + $itflow_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_column' LIMIT 1"); + if (!$itflow_exists || mysqli_num_rows($itflow_exists) === 0) { + $itflow_after_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_after' LIMIT 1"); + $itflow_place = $itflow_after_exists && mysqli_num_rows($itflow_after_exists) > 0 ? " AFTER `$itflow_after`" : ''; + mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_column` tinyint(1) NOT NULL DEFAULT 1$itflow_place"); + } + } diff --git a/admin/post/settings_invoice.php b/admin/post/settings_invoice.php index 6e22c3268..4932a8e64 100644 --- a/admin/post/settings_invoice.php +++ b/admin/post/settings_invoice.php @@ -51,6 +51,11 @@ if (isset($_POST['edit_invoice_settings'])) { $before += settingsCurrent(['config_invoice_paid_lead_to_client']); $after['config_invoice_paid_lead_to_client'] = empty($_POST['config_invoice_paid_lead_to_client']) ? 0 : 1; } + // From 4.3.7 - invoices offer autopay (autopayOffer()) + if (settingsColumnExists($mysqli, 'config_invoice_offer_autopay')) { + $before += settingsCurrent(['config_invoice_offer_autopay']); + $after['config_invoice_offer_autopay'] = empty($_POST['config_invoice_offer_autopay']) ? 0 : 1; + } // Late fees - a percent of what is owed $late_fee = billingNumberInput(str_replace('%', '', (string) $in['config_invoice_late_fee_percent'])); diff --git a/admin/settings_invoice.php b/admin/settings_invoice.php index 6a53c1b7b..9d44d62c2 100644 --- a/admin/settings_invoice.php +++ b/admin/settings_invoice.php @@ -77,6 +77,10 @@ echo settingsPageStart('invoice'); 'However it is paid in full - online, by autopay or a payment you record. A ticket linked to the invoice that is On Hold opens again at the same time, and its agent is told.']) ?> + + 'An invoice from a recurring invoice without autopay gets a Set up autopay button, in its email and on its page. The client agrees, adds a card through Stripe with no sign-in, and each invoice after that is charged on its due date. Turn it off for one recurring invoice on its page.']) ?> + diff --git a/agent/post/recurring_invoice.php b/agent/post/recurring_invoice.php index ce25e38c4..7f7ddd2bd 100644 --- a/agent/post/recurring_invoice.php +++ b/agent/post/recurring_invoice.php @@ -420,6 +420,41 @@ if (isset($_POST['set_recurring_payment'])) { } +/* + * Whether a recurring invoice's invoices offer the client autopay while it + * has none - its switch in the Autopay card (autopayOffer(), + * functions/billing_pay.php). + */ +if (isset($_POST['set_recurring_offer_autopay'])) { + + validateCSRFToken(); + + enforceUserPermission('module_sales', 2); + + $recurring_invoice_id = intval($_POST['recurring_invoice_id'] ?? 0); + $recurring = billingRow('recurring', $recurring_invoice_id); + if (!$recurring || !array_key_exists('recurring_invoice_offer_autopay', $recurring)) { + flashAlert('That recurring invoice no longer exists.', 'error'); + redirect(); + } + $client_id = intval($recurring['recurring_invoice_client_id']); + + enforceClientAccess(); + + $offer = empty($_POST['offer_autopay']) ? 0 : 1; + $number = billingNumber('recurring', $recurring); + if ($offer !== intval($recurring['recurring_invoice_offer_autopay'])) { + mysqli_query($mysqli, "UPDATE recurring_invoices SET recurring_invoice_offer_autopay = $offer WHERE recurring_invoice_id = $recurring_invoice_id"); + billingLog('recurring', $recurring_invoice_id, 'Autopay', ($offer ? 'Autopay offered to the client again' : 'Autopay no longer offered to the client') . ' - by ' . stripslashes($session_name)); + logAudit("Recurring Invoice", "Edit", "$session_name " . ($offer ? 'turned on' : 'turned off') . " offering autopay for recurring invoice " . escapeSql($number), $client_id, $recurring_invoice_id); + } + + flashAlert($offer ? 'Invoices from ' . escapeHtml($number) . ' offer the client autopay' : 'Invoices from ' . escapeHtml($number) . " no longer offer the client autopay"); + + redirect(); + +} + if (isExportRequest('export_recurring_invoices')) { validateCSRFToken(); diff --git a/agent/recurring_invoice.php b/agent/recurring_invoice.php index 0708fa25a..7677fbdb6 100644 --- a/agent/recurring_invoice.php +++ b/agent/recurring_invoice.php @@ -89,6 +89,10 @@ while ($row = mysqli_fetch_assoc($sql)) { $autopay_id = intval($recurring['recurring_payment_saved_payment_id'] ?? 0); // The card fee autopay adds, when the client pays one (functions/billing_pay.php) $autopay_fee = billingCardFeeFor($client_id); +// Autopay offered to the client in each invoice's email and on its page, while it has none - its switch, and why it isn't offered now when it isn't +$offer_switch = array_key_exists('recurring_invoice_offer_autopay', $recurring) && !$autopay_id && billingStripeProvider(); +$offer_on = intval($recurring['recurring_invoice_offer_autopay'] ?? 0) === 1; +$offer_blocked = $offer_switch ? autopayOfferBlocked($recurring) : ''; // Override Tab Title // No Sanitizing needed as this var will only be used in the tab title $tab_title = $recurring['client_name']; @@ -381,7 +385,27 @@ echo agentBannersHtml($client_id);
-
No card on file for . Once they save one paying an invoice online, it can be charged here automatically.
+
No card on file for . Once they save one, it can be charged here automatically.
+ + +
+ + + +
+ > + +
+
+ + Off - its invoices don't ask the client to set up autopay. + + Not offered just now - . + + Each invoice it makes has a Set up autopay button, in its email and on its page - the client adds a card and turns autopay on, with no sign-in. + +
+
diff --git a/client/invoice.php b/client/invoice.php index 6294bf560..088df9cdf 100644 --- a/client/invoice.php +++ b/client/invoice.php @@ -2,8 +2,9 @@ /* * Client Portal * An invoice - as it prints, with what is owed and by when alongside, Pay, - * the PDF, the payments made with their receipts, and the recurring - * invoice it came from. On a phone, what is owed comes first. + * the PDF, autopay offered when the recurring invoice it came from has none, + * the payments made with their receipts, and the recurring invoice it came + * from. On a phone, what is owed comes first. * * SCOPING: the invoice must be the session's client's, and not a draft. */ @@ -62,6 +63,11 @@ if ($recurring && $owing && intval($recurring['recurring_payment_saved_payment_i } } } +// No autopay on it - offered: turned on with a card they have saved, or set up from the invoice's own link with a new one (functions/billing_pay.php) +$autopay_offer = $recurring ? autopayOffer($invoice) : null; +$offer_cards = $autopay_offer ? array_filter(billingSavedCards($session_client_id), function ($card) { + return !$card['card']['expired']; +}) : []; $paper = [ 'type' => 'invoice', @@ -145,6 +151,34 @@ $paper = [ + +
+
+
Pay automatically from now on
+

Set up autopay once, and the invoice for each is charged to your card on its due date.

+ +
+ + + +
+ + +
+ + +
+ + Set up autopay + +
+
+ +
diff --git a/client/post.php b/client/post.php index 60c1cde80..802b3cdfb 100644 --- a/client/post.php +++ b/client/post.php @@ -1760,13 +1760,22 @@ if (isset($_POST['set_recurring_payment'])) { $recurring_payment_id = mysqli_insert_id($mysqli); logAudit("Recurring Invoice", "Auto Payment", "$session_contact_name created Auto Pay for Recurring Invoice $recurring_invoice_prefix$recurring_invoice_number in the amount of " . billingMoney($recurring_invoice_amount, $recurring_invoice_currency_code), $session_client_id, $recurring_invoice_id); + // In its history, and the agents told - as when it is set up from an invoice's link (autopayCheckoutFinish()) + $card_label = billingCardParts(stripslashes($saved_payment_description))['label']; + billingLog('recurring', $recurring_invoice_id, 'Autopay', "Autopay turned on with $card_label by " . stripslashes($session_contact_name) . ' (' . stripslashes($session_contact_email) . ') in the client portal'); + appNotify("Autopay", stripslashes($session_contact_name) . " set up autopay for " . $session_client_name . "'s recurring invoice " . stripslashes($recurring_invoice_prefix) . "$recurring_invoice_number with $card_label, in the client portal", + "/agent/recurring_invoice.php?recurring_invoice_id=$recurring_invoice_id", $session_client_id, $recurring_invoice_id); flashAlert("Automatic payment with $saved_payment_description turned on for recurring invoice $recurring_invoice_prefix$recurring_invoice_number"); } else { // Delete mysqli_query($mysqli, "DELETE FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_invoice_id"); + $was_on = mysqli_affected_rows($mysqli) > 0; logAudit("Recurring Invoice", "Auto Payment", "$session_contact_name removed Auto Pay for Recurring Invoice $recurring_invoice_prefix$recurring_invoice_number in the amount of " . billingMoney($recurring_invoice_amount, $recurring_invoice_currency_code), $session_client_id, $recurring_invoice_id); + if ($was_on) { + billingLog('recurring', $recurring_invoice_id, 'Autopay', 'Autopay turned off by ' . stripslashes($session_contact_name) . ' (' . stripslashes($session_contact_email) . ') in the client portal'); + } flashAlert("Automatic payment turned off for recurring invoice $recurring_invoice_prefix$recurring_invoice_number"); } diff --git a/db.sql b/db.sql index 778be0257..bcf67a4e1 100644 --- a/db.sql +++ b/db.sql @@ -3503,6 +3503,7 @@ CREATE TABLE `recurring_invoices` ( `recurring_invoice_note` text DEFAULT NULL, `recurring_invoice_auto_send` tinyint(1) NOT NULL DEFAULT 1, `recurring_invoice_email_notify` tinyint(1) NOT NULL DEFAULT 1, + `recurring_invoice_offer_autopay` tinyint(1) NOT NULL DEFAULT 1, `recurring_invoice_created_at` datetime NOT NULL DEFAULT current_timestamp(), `recurring_invoice_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), `recurring_invoice_archived_at` datetime DEFAULT NULL, @@ -4161,6 +4162,7 @@ CREATE TABLE `settings` ( `config_invoice_late_fee_percent` decimal(5,2) NOT NULL DEFAULT 0.00, `config_invoice_paid_notification_email` varchar(200) DEFAULT NULL, `config_invoice_paid_lead_to_client` tinyint(1) NOT NULL DEFAULT 1, + `config_invoice_offer_autopay` tinyint(1) NOT NULL DEFAULT 1, `config_invoice_show_tax_id` tinyint(1) NOT NULL DEFAULT 0, `config_tax_default_id` int(11) NOT NULL DEFAULT 0, `config_tax_time` tinyint(1) NOT NULL DEFAULT 0, diff --git a/functions/billing_email.php b/functions/billing_email.php index 7fac27bf8..10a95d9de 100644 --- a/functions/billing_email.php +++ b/functions/billing_email.php @@ -437,10 +437,67 @@ function billingInvoiceEmail(array $invoice, array $opts = []) { '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', + 'offer' => billingAutopayOfferEmail($invoice), '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], ]]; } +/** + * The autopay an invoice email offers (autopayOffer(), functions/billing_pay.php) - + * emailHtml()'s offer box, or null when there is none to offer. + */ +function billingAutopayOfferEmail(array $invoice) { + $offer = autopayOffer($invoice); + if (!$offer) { + return null; + } + $what = $offer['title'] !== $offer['number'] ? "the invoice for \"{$offer['title']}\"" : "the invoice from {$offer['number']}"; + return [ + 'title' => 'Pay automatically from now on', + 'text' => "Set up autopay once, and $what each {$offer['period']} is charged to your card on its due date - no paying each one by hand. It takes a minute, with no sign-in." + . ($offer['this_invoice'] ? ' This invoice is included, on ' . billingEmailDate($invoice['invoice_due']) . '.' : ''), + 'button' => ['label' => 'Set up autopay', 'url' => $offer['url']], + 'small' => ($offer['fee'] !== '' ? "Each charge has a card fee added: {$offer['fee']}. " : '') . autopayChangeText(), + ]; +} + +/** How a client changes the card or turns autopay off - in the client portal when it is on, else by asking. */ +function autopayChangeText() { + global $config_client_portal_enable; + return 'To change the card or turn autopay off later, ' . (!empty($config_client_portal_enable) ? 'sign in to the client portal or ask us.' : 'just ask us.'); +} + +/** + * Confirm autopay set up from an invoice's link (guest/guest_autopay.php) to + * whoever set it up - the recurring invoice, the card, what is charged and + * when. $offer is autopayOffer() as it stood, $invoice the invoice it was set + * up from. Who it went to. + */ +function billingMailAutopayOn($email, $name, array $offer, $card_label, array $invoice) { + $recurring = $offer['recurring']; + $summary = ['Recurring invoice' => $offer['number']]; + if ($offer['title'] !== $offer['number']) { + $summary['For'] = $offer['title']; + } + $summary['Each ' . $offer['period']] = billingMoney($offer['amount'], $offer['currency']); + $summary['Card'] = $card_label; + $summary['Next invoice'] = billingEmailDate($recurring['recurring_invoice_next_date']); + $first = $offer['this_invoice'] + ? 'The first charge is invoice ' . billingNumber('invoice', $invoice) . ', on its due date, ' . billingEmailDate($invoice['invoice_due']) . '.' + : 'Invoice ' . billingNumber('invoice', $invoice) . " isn't charged by autopay - pay it as usual if it is still owed. Autopay starts with the next one."; + return billingEmailQueue([['email' => (string) $email, 'name' => (string) $name]], 'Autopay is on for ' . $offer['title'], [ + 'kind' => 'Autopay', 'tone' => 'success', 'preview' => "Each invoice is charged to $card_label on its due date", + 'title' => 'Autopay is on', + 'intro' => ["Thank you - from now on, each invoice from recurring invoice {$offer['number']} is charged to $card_label on its due date, and a receipt is emailed each time. $first"], + 'summary' => $summary, 'strong' => 'Each ' . $offer['period'], + 'after' => array_values(array_filter([ + $offer['fee'] !== '' ? "Each charge has a card fee added: {$offer['fee']}." : '', + 'Your card details are kept by Stripe, our payment processor - not by us. ' . autopayChangeText(), + ])), + 'footnote' => 'You received this email because you set up autopay for ' . $recurring['client_name'] . ' with ' . (billingCompany()['company_name'] ?? 'us') . '.', + ], ['about' => 'invoice:' . intval($invoice['invoice_id'])]); +} + /** A quote email - [subject, email]. $opts: note. */ function billingQuoteEmail(array $quote, array $opts = []) { $number = billingNumber('quote', $quote); diff --git a/functions/billing_pay.php b/functions/billing_pay.php index 1cc116ccf..f6f3c93b5 100644 --- a/functions/billing_pay.php +++ b/functions/billing_pay.php @@ -470,6 +470,299 @@ function invoiceAutopayStatus(array $invoice, array $state, $autopay) { 'detail' => "$done on its due date, $due - for what is still owed then."]; } +/* -------------------------------------------------------- Offering autopay */ + +/* + * An invoice from a recurring invoice with no autopay offers it - a Set up + * autopay button in its email and on its page that opens + * guest/guest_autopay.php from the invoice's own link, so no sign-in is + * needed: the client agrees, adds a card through Stripe's form, and autopay + * is on for that recurring invoice. Settings > Invoices turns the offer off + * for everyone, and a recurring invoice's page for one. + */ + +/** Whether invoices offer autopay - Settings > Invoices > Paid online (DB 4.3.7). */ +function autopayOfferOn() { + global $mysqli; + static $on = null; + if ($on === null) { + $on = settingsColumnExists($mysqli, 'config_invoice_offer_autopay') + && intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_invoice_offer_autopay FROM settings WHERE company_id = 1"))[0] ?? 0) === 1; + } + return $on; +} + +/** + * Why a recurring invoice's client isn't offered autopay - '' when they are, + * or would be once an invoice from it is sent. Its autopay is already on, + * cards are off, the offer is off here or in Settings > Invoices, it is + * paused or archived, or it bills more than a card can take. $recurring is + * billingRow('recurring'). + */ +function autopayOfferBlocked(array $recurring) { + if (intval($recurring['recurring_payment_id'] ?? 0) > 0) { + return 'Autopay is on'; + } + if (!billingStripeProvider()) { + return "Card payments are off - Stripe isn't set up in Payment Providers"; + } + if (!autopayOfferOn()) { + return 'Offering autopay is off in Settings > Invoices'; + } + if (intval($recurring['recurring_invoice_offer_autopay'] ?? 1) !== 1) { + return 'Turned off for this recurring invoice'; + } + if (intval($recurring['recurring_invoice_status']) !== 1 || !empty($recurring['recurring_invoice_archived_at'])) { + return "It isn't active"; + } + if (!billingOnlinePayAllowed($recurring['recurring_invoice_amount'])) { + return 'It bills more than the card limit in Payment Providers'; + } + return ''; +} + +/** + * The autopay an invoice offers for the recurring invoice it came from - or + * null when it offers none (autopayOfferBlocked(), or the invoice is + * cancelled or not billed). autopayOfferDetails() says what is in it. + */ +function autopayOffer(array $invoice) { + $recurring_id = intval($invoice['invoice_recurring_invoice_id'] ?? 0); + if ($recurring_id <= 0 || in_array((string) $invoice['invoice_status'], ['Cancelled', 'Non-Billable'], true) || (string) ($invoice['invoice_url_key'] ?? '') === '') { + return null; + } + $recurring = billingRow('recurring', $recurring_id, false); + if (!$recurring || intval($recurring['recurring_invoice_client_id']) !== intval($invoice['invoice_client_id']) || autopayOfferBlocked($recurring) !== '') { + return null; + } + return autopayOfferDetails($invoice, $recurring); +} + +/** + * What autopay for $recurring, offered from $invoice, comes to - ['recurring' + * => its row, 'number', 'title' => its scope, else its number, 'amount', + * 'currency', 'period' => month, quarter or year, 'fee' => the card fee's + * terms, or '', 'this_invoice' => whether $invoice is charged too - still + * owed, and due after today, 'url' => the setup page]. + */ +function autopayOfferDetails(array $invoice, array $recurring) { + $currency = (string) $recurring['recurring_invoice_currency_code']; + $owed = in_array((string) $invoice['invoice_status'], ['Draft', 'Sent', 'Viewed', 'Partial'], true) + && round(floatval($invoice['invoice_amount']) - invoicePaid($invoice['invoice_id']), 2) > 0; + $number = billingNumber('recurring', $recurring); + return [ + 'recurring' => $recurring, + 'number' => $number, + 'title' => trim((string) $recurring['recurring_invoice_scope']) !== '' ? trim((string) $recurring['recurring_invoice_scope']) : $number, + 'amount' => floatval($recurring['recurring_invoice_amount']), + 'currency' => $currency, + 'period' => recurringInvoicePeriodWord($recurring['recurring_invoice_frequency']), + 'fee' => billingCardFeeTerms(billingCardFeeFor($invoice['invoice_client_id']), $currency), + 'this_invoice' => $owed && (string) $invoice['invoice_due'] > date('Y-m-d'), + 'url' => autopayOfferUrl($invoice), + ]; +} + +/** The page that sets autopay up from an invoice's link. */ +function autopayOfferUrl(array $invoice) { + global $config_base_url; + return "https://$config_base_url/guest/guest_autopay.php?invoice_id=" . intval($invoice['invoice_id']) . '&url_key=' . rawurlencode((string) $invoice['invoice_url_key']); +} + +/** + * What the client agrees to, raw - the charges, the card fee when they pay + * one, and until when. Kept in the recurring invoice's history. + */ +function autopayConsentText(array $offer) { + $company = billingCompany(); + return 'I authorize ' . ($company['company_name'] ?? 'you') . " to charge the card I add for each invoice from recurring invoice {$offer['number']}" + . ($offer['title'] !== $offer['number'] ? " ({$offer['title']})" : '') . ' on its due date' + . ($offer['fee'] !== '' ? ", plus a card fee of {$offer['fee']}" : '') . ', until autopay is turned off.'; +} + +/** + * Start setting autopay up from an invoice's link: the client's Stripe + * customer, made now when they have none, and a Checkout Session that saves + * a card to it - Stripe's own form, on the page. Who agreed and to what goes + * in its metadata, for autopayCheckoutFinish() when Stripe sends them back. + * Its client secret, or '' with $error for the client. $name and $email raw. + */ +function autopayCheckoutStart(array $invoice, $name, $email, &$error = '') { + global $mysqli, $config_base_url; + $offer = autopayOffer($invoice); + $name = trim(mb_substr(preg_replace('/\s+/u', ' ', (string) $name) ?? '', 0, 80)); + $email = trim(mb_substr((string) $email, 0, 120)); + if (!$offer) { + $error = "Autopay can't be set up from this invoice just now - get in touch and we'll help."; + return ''; + } + if ($name === '') { + $error = 'Enter your name.'; + return ''; + } + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + $error = 'Enter your email address, for the confirmation.'; + return ''; + } + $provider = billingStripeProvider(); + $stripe = billingStripeClient(); + $client_id = intval($invoice['invoice_client_id']); + $provider_id = intval($provider['payment_provider_id']); + $invoice_id = intval($invoice['invoice_id']); + $invoice_number = billingNumber('invoice', $invoice); + $recurring_id = intval($offer['recurring']['recurring_invoice_id']); + $ids = ['itflow_autopay_invoice_id' => $invoice_id, 'itflow_recurring_invoice_id' => $recurring_id, 'itflow_client_id' => $client_id]; + + for ($try = 0; $try < 2; $try++) { + $customer = billingStripeCustomer($client_id); + try { + if ($customer === '') { + // One customer a client - two setups at once take turns here + $lock = "itflow_stripe_customer_$client_id"; + mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)"); + try { + $customer = billingStripeCustomer($client_id); + if ($customer === '') { + $made = $stripe->customers->create([ + 'name' => (string) $offer['recurring']['client_name'], + 'email' => $email, + 'metadata' => ['itflow_client_id' => $client_id, 'consent_by' => $name], + ]); + $customer = (string) $made->id; + mysqli_query($mysqli, "INSERT INTO client_payment_provider SET client_id = $client_id, payment_provider_id = $provider_id, + payment_provider_client = '" . escapeSql($customer) . "', client_payment_provider_created_at = NOW()"); + logAudit("Stripe", "Create", "Guest $name ($email) created Stripe customer for {$offer['recurring']['client_name']} as $customer, setting up autopay from invoice $invoice_number", $client_id); + } + } finally { + mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')"); + } + } + $session = $stripe->checkout->sessions->create([ + 'mode' => 'setup', + 'ui_mode' => 'embedded_page', + 'currency' => strtolower($offer['currency']), + 'customer' => $customer, + 'payment_method_types' => ['card'], + 'return_url' => "https://$config_base_url/guest/guest_post.php?guest_autopay_done=1&invoice_id=$invoice_id&url_key=" . rawurlencode((string) $invoice['invoice_url_key']) . '&session_id={CHECKOUT_SESSION_ID}', + 'metadata' => $ids + [ + 'itflow_consent_name' => $name, + 'itflow_consent_email' => $email, + 'itflow_consent' => mb_substr(autopayConsentText($offer), 0, 500), + ], + 'setup_intent_data' => ['description' => "Autopay for recurring invoice {$offer['number']}", 'metadata' => $ids], + ]); + return (string) $session->client_secret; + } catch (\Throwable $e) { + // A customer Stripe no longer has - forgotten, and made again once + if ($try === 0 && $customer !== '' && billingStripeCustomerGone($e)) { + billingStripeCustomerForget($client_id, $customer); + continue; + } + logApp("Stripe", "error", "Setting up autopay from invoice $invoice_number couldn't start: " . $e->getMessage()); + break; + } + } + $error = "Card details can't be taken just now - try again in a few minutes."; + return ''; +} + +/** + * Finish setting autopay up once Stripe sends the client back from + * autopayCheckoutStart()'s form: the session checked with Stripe - complete, + * and for this invoice, its recurring invoice and the client's customer - + * the card saved, and autopay on for the recurring invoice with it, in place + * of any it had. Kept in its history with what they agreed to, logged, the + * agents told and the client sent a confirmation. Coming back to the same + * address again changes nothing. ['ok' => bool, 'again' => true when it was + * done already, 'card' => "Visa •••• 4242", 'emailed' => whether the + * confirmation went, 'error' => for the client]. + */ +function autopayCheckoutFinish(array $invoice, $session_id) { + global $mysqli; + $fail = function ($error) { + return ['ok' => false, 'again' => false, 'emailed' => false, 'card' => '', 'error' => $error]; + }; + $session_id = (string) $session_id; + $provider = billingStripeProvider(); + $stripe = billingStripeClient(); + $recurring = intval($invoice['invoice_recurring_invoice_id'] ?? 0) ? billingRow('recurring', $invoice['invoice_recurring_invoice_id'], false) : null; + $client_id = intval($invoice['invoice_client_id']); + if (!$provider || !$stripe || !$recurring || intval($recurring['recurring_invoice_client_id']) !== $client_id || !preg_match('/^cs_[A-Za-z0-9_]{8,250}$/', $session_id)) { + return $fail("Autopay couldn't be set up from that link - get in touch and we'll help."); + } + $recurring_id = intval($recurring['recurring_invoice_id']); + $invoice_id = intval($invoice['invoice_id']); + $invoice_number = billingNumber('invoice', $invoice); + + // The same return twice at once - a double click, a reload - takes turns, and the second finds it done + $lock = "itflow_autopay_$recurring_id"; + mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)"); + try { + $done = mysqli_fetch_row(mysqli_query($mysqli, "SELECT history_description FROM history WHERE history_recurring_invoice_id = $recurring_id + AND history_status = 'Autopay' AND history_description LIKE '%" . escapeSql(addcslashes($session_id, '%_\\')) . "%' LIMIT 1")); + if ($done) { + return ['ok' => true, 'again' => true, 'emailed' => false, 'card' => preg_match('/ with (.+?) by /u', (string) $done[0], $m) ? $m[1] : '', 'error' => '']; + } + if (intval($recurring['recurring_invoice_status']) !== 1 || !empty($recurring['recurring_invoice_archived_at'])) { + return $fail("This recurring invoice has ended, so autopay wasn't set up. Nothing will be charged."); + } + $offer = autopayOfferDetails($invoice, $recurring); + $customer = billingStripeCustomer($client_id); + try { + $session = $stripe->checkout->sessions->retrieve($session_id, []); + $meta = $session->metadata ? $session->metadata->toArray() : []; + if ((string) $session->mode !== 'setup' || intval($meta['itflow_autopay_invoice_id'] ?? 0) !== $invoice_id + || intval($meta['itflow_recurring_invoice_id'] ?? 0) !== $recurring_id || $customer === '' || (string) $session->customer !== $customer) { + return $fail("That card setup isn't for this invoice - nothing has changed."); + } + if ((string) $session->status !== 'complete' || empty($session->setup_intent)) { + return $fail("Your card wasn't added, so autopay isn't on yet - try again."); + } + $setup_intent = $stripe->setupIntents->retrieve(is_string($session->setup_intent) ? $session->setup_intent : $session->setup_intent->id, []); + $pm_id = is_string($setup_intent->payment_method) ? $setup_intent->payment_method : (string) ($setup_intent->payment_method->id ?? ''); + if ((string) $setup_intent->status !== 'succeeded' || $pm_id === '') { + return $fail("Your card wasn't added, so autopay isn't on yet - try again."); + } + $pm = $stripe->paymentMethods->retrieve($pm_id, []); + } catch (\Throwable $e) { + logApp("Stripe", "error", "Setting up autopay from invoice $invoice_number couldn't be confirmed ($session_id): " . $e->getMessage()); + return $fail("We couldn't confirm your card with Stripe just now - reload this page in a minute, or get in touch."); + } + + $provider_id = intval($provider['payment_provider_id']); + $pm_sql = escapeSql($pm_id); + $description = !empty($pm->card) + ? "{$pm->card->brand} - {$pm->card->last4} | Exp " . intval($pm->card->exp_month) . '/' . intval($pm->card->exp_year) + : 'Card'; + // The card - saved once, however often it comes back + $saved_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT saved_payment_id FROM client_saved_payment_methods + WHERE saved_payment_client_id = $client_id AND saved_payment_provider_id = $provider_id AND saved_payment_provider_method = '$pm_sql' LIMIT 1"))[0] ?? 0); + if (!$saved_id) { + mysqli_query($mysqli, "INSERT INTO client_saved_payment_methods SET saved_payment_provider_method = '$pm_sql', saved_payment_description = '" . escapeSql($description) . "', + saved_payment_client_id = $client_id, saved_payment_provider_id = $provider_id, saved_payment_created_at = NOW()"); + $saved_id = intval(mysqli_insert_id($mysqli)); + } + $currency = escapeSql($recurring['recurring_invoice_currency_code']); + mysqli_query($mysqli, "DELETE FROM recurring_payments WHERE recurring_payment_recurring_invoice_id = $recurring_id"); + mysqli_query($mysqli, "INSERT INTO recurring_payments SET recurring_payment_currency_code = '$currency', recurring_payment_account_id = " . intval($provider['payment_provider_account']) . ", + recurring_payment_method = 'Credit Card', recurring_payment_recurring_invoice_id = $recurring_id, recurring_payment_saved_payment_id = $saved_id"); + + $card = billingCardParts($description)['label']; + $name = trim((string) ($meta['itflow_consent_name'] ?? '')) ?: 'The client'; + $email = trim((string) ($meta['itflow_consent_email'] ?? '')); + $who = $email !== '' ? "$name ($email)" : $name; + $consent = trim((string) ($meta['itflow_consent'] ?? '')); + billingLog('recurring', $recurring_id, 'Autopay', "Autopay turned on with $card by $who from invoice $invoice_number's link" . ($consent !== '' ? ", agreeing: \"$consent\"" : '') . " - Stripe $session_id"); + logAudit("Recurring Invoice", "Auto Payment", "Guest $who turned on Auto Pay with $card for Recurring Invoice {$offer['number']} from invoice $invoice_number's link", $client_id, $recurring_id); + appNotify("Autopay", "$name set up autopay for {$recurring['client_name']}'s recurring invoice {$offer['number']} with $card, from invoice $invoice_number's link", + "/agent/recurring_invoice.php?recurring_invoice_id=$recurring_id", $client_id, $recurring_id); + $emailed = $email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) && billingEmailReady() && billingMailAutopayOn($email, $name, $offer, $card, $invoice); + return ['ok' => true, 'again' => false, 'card' => $card, 'emailed' => $emailed, 'error' => '']; + } finally { + mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')"); + } +} + /* ------------------------------------------------------- Choosing and paying */ /** diff --git a/functions/demo.php b/functions/demo.php index 64e89e0dc..3357af44f 100644 --- a/functions/demo.php +++ b/functions/demo.php @@ -85,7 +85,7 @@ const DEMO_MODE_LOCKS = [ 'message' => "Card payments and payment providers are turned off in the demo.", 'keys' => ['add_payment_provider', 'check_payment_provider', 'check_payment_provider_connection', 'delete_payment_provider', 'edit_payment_provider', 'record_payment_provider_fees', 'turn_payment_provider_off', 'turn_payment_provider_on', 'delete_saved_payment', 'create_stripe_checkout', - 'create_stripe_customer', 'stripe_save_card', 'set_recurring_payment', 'portal_pay'], + 'create_stripe_customer', 'stripe_save_card', 'set_recurring_payment', 'portal_pay', 'guest_autopay_checkout', 'guest_autopay_done', 'set_recurring_offer_autopay'], ], [ 'message' => "AI providers can't be set up in the demo.", diff --git a/functions/email.php b/functions/email.php index 8263e3985..c3e8840d9 100644 --- a/functions/email.php +++ b/functions/email.php @@ -43,6 +43,8 @@ const EMAIL_REPLY_MARKER = '##- Please type your reply above this line -##'; * callout a paragraph that stands out, in the tone's colour * button ['label' => ..., 'url' => ..., 'show_url' => true to print the address under it, * for a link that has to be copied whole] + * offer something more they can do, in a box of its own after the button - ['title', 'text', + * 'button' => ['label', 'url'], 'small' => a line under its button] (autopay, say) * after paragraphs after the button, smaller * history earlier messages, under a rule at the end - ['label' => the heading, 'items' => [...]], * each item ['by', 'org', 'action', 'when', 'text' => plain text, 'client' => true for @@ -146,6 +148,19 @@ function emailHtml(array $email) { $body .= '

Or copy this into your browser: ' . $e($email['button']['url']) . '

'; } } + if (!empty($email['offer']['button']['url'])) { + $offer = $email['offer']; + $primary = $tones['primary']; + $body .= '' + . '
' + . (trim((string) ($offer['title'] ?? '')) !== '' ? '
' . $e($offer['title']) . '
' : '') + . (trim((string) ($offer['text'] ?? '')) !== '' ? '

' . nl2br($e($offer['text'])) . '

' : '') + . '
' + . '' . $e($offer['button']['label']) . '' + . '
' + . (trim((string) ($offer['small'] ?? '')) !== '' ? '

' . nl2br($e($offer['small'])) . '

' : '') + . '
'; + } foreach ((array) ($email['after'] ?? []) as $text_value) { $body .= '

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

'; } diff --git a/functions/settings.php b/functions/settings.php index aab5d3b85..4aab56711 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -338,6 +338,7 @@ function settingsFields() { 'config_invoice_late_fee_percent' => ['page' => 'invoice', 'section' => 'Late fees', 'label' => 'Late fee %', 'words' => 'late fee percent'], 'config_invoice_paid_notification_email' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'Email invoices paid online to', 'words' => 'paid notification email stripe payment'], 'config_invoice_paid_lead_to_client' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'A lead that pays an invoice becomes a client', 'words' => 'lead client convert paid payment'] + $on_off, + 'config_invoice_offer_autopay' => ['page' => 'invoice', 'section' => 'Paid online', 'label' => 'Offer autopay on recurring invoices', 'words' => 'autopay automatic payment recurring card offer set up'] + $on_off, 'config_send_invoice_reminders' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Email payment reminders', 'words' => 'overdue reminder dunning past due'] + $on_off, 'reminder_before' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Remind before it is due', 'words' => 'reminder days before due'], 'reminder_after' => ['page' => 'invoice', 'section' => 'Reminders and statements', 'label' => 'Remind after it is due', 'words' => 'reminder days late overdue'], diff --git a/guest/guest_ajax.php b/guest/guest_ajax.php index 90c548f44..5fa524c12 100644 --- a/guest/guest_ajax.php +++ b/guest/guest_ajax.php @@ -139,3 +139,44 @@ if (isset($_GET['stripe_create_pi'])) { exit; } + +/* + * Starts setting autopay up from an invoice's link (guest_autopay.php, + * js/guest_autopay_stripe.js) - the client secret of Stripe's form to add + * the card (autopayCheckoutStart(), functions/billing_pay.php). Posted: + * invoice_id, url_key, name, email and agree. The invoice's link key is the + * only proof, matched exactly. + */ +if (isset($_GET['guest_autopay_checkout'])) { + + header('Content-Type: application/json'); + header('Cache-Control: no-store'); + + // logAudit() reads these globals - without them guest audit rows have no IP + $session_ip = escapeSql(getIP()); + $session_user_agent = escapeSql(mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 250)); + + $invoice = billingRow('invoice', intval($_POST['invoice_id'] ?? 0), false); + $url_key = is_string($_POST['url_key'] ?? null) ? $_POST['url_key'] : ''; + if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !$invoice || (string) $invoice['invoice_url_key'] === '' || !hash_equals((string) $invoice['invoice_url_key'], $url_key) + || guestLinkExpired('invoice', $invoice['invoice_id'])) { + http_response_code(404); + echo json_encode(['error' => "This invoice link isn't working - open it again from the email."]); + exit; + } + if (empty($_POST['agree'])) { + http_response_code(400); + echo json_encode(['error' => 'Tick the box to agree to autopay first.']); + exit; + } + + $error = ''; + $secret = autopayCheckoutStart($invoice, is_string($_POST['name'] ?? null) ? $_POST['name'] : '', is_string($_POST['email'] ?? null) ? $_POST['email'] : '', $error); + if ($secret === '') { + http_response_code(400); + echo json_encode(['error' => $error]); + exit; + } + echo json_encode(['clientSecret' => $secret]); + exit; +} diff --git a/guest/guest_autopay.php b/guest/guest_autopay.php new file mode 100644 index 000000000..51cf98091 --- /dev/null +++ b/guest/guest_autopay.php @@ -0,0 +1,185 @@ +View invoice ' . escapeHtml($number) . ''; + +$recurring = intval($invoice['invoice_recurring_invoice_id'] ?? 0) ? billingRow('recurring', $invoice['invoice_recurring_invoice_id'], false) : null; +if (!$recurring || intval($recurring['recurring_invoice_client_id']) !== $client_id) { + echo str_replace('

', '

' . $back . '', guestDeadEndHtml('fa-redo-alt', "Autopay isn't for this invoice", "Autopay pays the invoices that come regularly, and this one doesn't. Get in touch if you'd like to pay another way.")); + require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; + exit(); +} + +$title = trim((string) $recurring['recurring_invoice_scope']) !== '' ? trim((string) $recurring['recurring_invoice_scope']) : billingNumber('recurring', $recurring); + +// On already - what pays it, and whether that will go through +$autopay = intval($recurring['recurring_payment_id'] ?? 0) ? invoiceAutopay($invoice) : null; +if ($autopay) { ?> +
+ +

Autopay is on

+

Each invoice for on its due date - nothing to do.

+ +

It won't go through just now - . Get in touch to change the card.

+ +

+ +
+ ', '

' . $back . '', guestDeadEndHtml('fa-credit-card', "Autopay can't be set up here just now", "Get in touch and we'll set it up with you, or pay this invoice from its page.")); + require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; + exit(); +} + +$offer = autopayOfferDetails($invoice, $recurring); +$state = invoiceState($invoice, invoicePaid($invoice_id)); +$owed = in_array($state['state'], ['open', 'overdue'], true) && $state['balance'] > 0; +$money = function ($amount) use ($offer) { + return escapeHtml(billingMoney($amount, $offer['currency'])); +}; + +// Signed in to the client portal as one of this client's contacts - their name and email to start with +$name = ''; +$email = ''; +if (!empty($_SESSION['client_logged_in']) && intval($_SESSION['client_id'] ?? 0) === $client_id) { + $me = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts WHERE contact_id = " . intval($_SESSION['contact_id'] ?? 0) . " AND contact_client_id = $client_id")); + $name = (string) ($me['contact_name'] ?? ''); + $email = (string) ($me['contact_email'] ?? ''); +} + +?> + +
+
+ +
+
+ +
+ +
+

Set up autopay

+
+
+
+ +

Each invoice for is charged to your card on its due date, with a receipt by email - no paying each one by hand.

+ +
    +
  • + Recurring invoice +
  • +
  • + Each +
  • +
  • + Next invoice +
  • + +
  • + Invoice + +
  • + + +
  • + Card fee, added to each charge +
  • + +
+ +
+ + + +
+ +
+ + +
+
+ +
+ +
+ + +
+
For the confirmation.
+
+ +
+ + +
+ + + + +
+ + + + + +

Your card goes straight to Stripe, our payment processor - we never see its number.

+ +
+
+ + + +
+
+ + + + +' . escapeHtml($result['card']) . '' : '') . '.' . ($result['emailed'] ? ' A confirmation is on its way by email.' : '')); + } + redirect($back); +} + if (isset($_POST['create_stripe_customer'])) { $invoice_url_key = escapeSql($_POST['url_key']); diff --git a/guest/guest_view_invoice.php b/guest/guest_view_invoice.php index 017b10f83..ff73aa650 100644 --- a/guest/guest_view_invoice.php +++ b/guest/guest_view_invoice.php @@ -3,7 +3,8 @@ /* * An invoice as the client opens it from its link - the invoice on the * left, as it prints; on the right what is owed and by when, that autopay - * pays it on its due date when it does, Pay Now when it can be paid online, the PDF, the payments made, and everything else + * pays it on its due date when it does, Pay Now when it can be paid online, the PDF, Set up autopay when the recurring + * invoice it came from offers it, the payments made, and everything else * they owe with a link to each. Opening it marks a sent invoice viewed and * tells the agents. */ @@ -63,6 +64,8 @@ $autopay = $state['state'] === 'open' ? invoiceAutopay($invoice) : null; if ($autopay && $autopay['problem'] !== '') { $autopay = null; } +// No autopay on the recurring invoice it came from - offered, to set up from here (functions/billing_pay.php) +$autopay_offer = autopayOffer($invoice); $paper = [ 'type' => 'invoice', @@ -126,6 +129,19 @@ $paper = [ + +
+
+ +
+
Pay automatically from now on
+

Set up autopay once, and the invoice for each is charged to your card on its due date. It takes a minute, with no sign-in.

+ Set up autopay +
+
+
+ +

Payments

diff --git a/js/guest_autopay_stripe.js b/js/guest_autopay_stripe.js new file mode 100644 index 000000000..f189adb82 --- /dev/null +++ b/js/guest_autopay_stripe.js @@ -0,0 +1,83 @@ +/* + * Setting up autopay from an invoice's link (guest/guest_autopay.php). Their + * name, email and agreement go to guest_ajax.php (guest_autopay_checkout), + * which answers with a Checkout Session's client secret; Stripe's card form + * then takes the place of the form, and sends them on to the return address + * once the card is added. Anything that stops it is said on the page. + */ +(function () { + 'use strict'; + + var form = document.querySelector('form[data-autopay-form]'); + if (!form) { + return; + } + var holder = document.querySelector('[data-autopay-checkout]'); + var errorBox = form.querySelector('[data-autopay-error]'); + var submit = form.querySelector('[data-autopay-submit]'); + var started = false; + + function show(el, on) { + if (el) { + el.hidden = !on; + } + } + + function busy(on) { + submit.disabled = on; + show(form.querySelector('[data-autopay-busy]'), on); + show(form.querySelector('[data-autopay-idle]'), !on); + } + + function fail(message) { + errorBox.textContent = message; + show(errorBox, true); + busy(false); + } + + form.addEventListener('submit', function (e) { + e.preventDefault(); + show(errorBox, false); + if (!form.checkValidity()) { + form.classList.add('was-validated'); + if (!form.querySelector('[name="agree"]').checked) { + fail('Tick the box to agree to autopay first.'); + } + return; + } + if (started) { + return; + } + if (typeof window.Stripe !== 'function') { + show(document.querySelector('[data-autopay-unavailable]'), true); + return; + } + busy(true); + var problem = ''; + var stripe = window.Stripe(form.getAttribute('data-stripe-key')); + stripe.initEmbeddedCheckout({ + fetchClientSecret: function () { + return fetch('guest_ajax.php?guest_autopay_checkout=1', {method: 'POST', body: new FormData(form), credentials: 'same-origin'}) + .then(function (response) { + return response.json().catch(function () { + return {}; + }); + }) + .then(function (data) { + if (!data.clientSecret) { + problem = data.error || ''; + throw new Error(problem || 'No checkout'); + } + return data.clientSecret; + }); + } + }).then(function (checkout) { + started = true; + show(form, false); + show(holder, true); + checkout.mount('#autopay-checkout'); + }).catch(function () { + fail(problem || "The card form couldn't start - try again in a minute, or get in touch."); + }); + }); +})();