mirror of
https://github.com/itflow-org/itflow
synced 2026-12-05 10:39:00 +00:00
A card is saved once per client however often it is entered: billingStripeCardSave matches Stripe's card fingerprint for autopay from an invoice's link, a new card from the expiry reminder's link and the client portal, keeping the one saved card up to date and detaching the payment method it replaces, and the nightly run merges cards already saved twice into the one that runs out last with their autopay moved to it; 26.12.6 changelog
This commit is contained in:
@@ -25,6 +25,7 @@ Update from Maintenance > Update as usual. There is no database change.
|
||||
- Importing a CSV file with accented letters - ü, é, ñ, ø and the like - keeps them. A file saved from Excel as plain **CSV (Comma delimited)**, exported from Outlook, or saved from Excel for Mac as **Comma Separated Values** imported with a ? in place of each accented letter, and one with an accented letter in a heading didn't import at all. Every import - clients, contacts, locations, assets and the rest - now reads the file in whatever it was saved as, and a file whose columns are separated by tabs imports too. Bank statements imported on Expenses and Income read the same way, so one saved on a Mac or in Unicode now imports too.
|
||||
- UniFi gateways come in as **Firewall/Router**. The Cloud Gateway Fiber, the Enterprise Fortress Gateway and other newer gateways came in as a switch or as Other, because UniFi doesn't always say a device is a gateway - ITFlow now knows them by their model too: the Dream Machines, Dream Routers and Dream Wall, the Cloud Gateways, the UXG Gateways, the Enterprise Fortress Gateway and the older Security Gateways. One already brought in as a switch or Other is put right by the next sync, unless you changed its type yourself, and when one goes offline its alert is the site's gateway alert. In-wall access points, which came in as switches, come in as access points.
|
||||
- Connecting Microsoft 365 for mail works with an app that has only Microsoft Graph's permissions, and where your users can't approve apps. Connect asked Microsoft for Exchange's SMTP and IMAP permissions every time and forced the consent screen, so an app with only Graph's Mail.Send and Mail.ReadWrite couldn't connect, and a mailbox account that isn't allowed to approve apps was stopped at "Need admin approval" even after an admin had granted consent. On the OAuth tab, **The app has**, above **Connect Microsoft 365**, says which permissions you gave the app, and Connect asks for just those - Microsoft asks which account to sign in as instead. Coming back, ITFlow says how email now goes, or what the app is missing. **Test OAuth Token Refresh** no longer fails an app with only Graph's permissions: it checks Graph first, and SMTP and IMAP only for what Graph can't do.
|
||||
- A card is saved once per client, however often it's entered. A client who set up autopay on two recurring invoices with the same card - or added it again in the portal - ended up with the card saved twice, once for each, as Stripe gives the card a new reference each time it's entered. ITFlow now knows the same card when it comes back: the one saved card is kept, with the details just entered, and every recurring invoice it pays carries on with it. A card that is already saved twice is merged into one overnight - the copy that runs out last is kept and the autopay on the others moves to it - so you don't need to do anything, and its client isn't sent two expiry reminders for it.
|
||||
|
||||
### Developer Updates
|
||||
|
||||
@@ -35,6 +36,7 @@ Update from Maintenance > Update as usual. There is no database change.
|
||||
- Imports: `csvTextToUtf8($text)` (`functions/import.php`) gives a CSV's text as UTF-8 - UTF-8 as it is with its BOM dropped, UTF-16 LE or BE by its BOM, and otherwise Windows-1252 or Mac Roman, whichever `csvTextMisreads()` finds fewer signs of a wrong reading in (C1 control characters, a capital or symbols in the middle of a word, an opening quote or `š`/`ˆ`/`fl` after a letter), Windows-1252 on a tie. `importFile()` reads the whole upload through it into `php://temp`, turns lone `\r` line ends into `\n`, and takes comma, semicolon or tab, whichever the heading line has most of; `expenseImportRead()` uses it in place of its own BOM strip and Windows-1252 fallback, which also let a UTF-16 statement fail its NUL check, and so do the network IP and interface imports in `agent/post/network_ip.php` and `agent/post/asset_interface.php`. Before, `importFile()` passed the bytes through: `importSqlText()`'s `mb_substr()` turned each invalid byte into `?` before `escapeSql()`'s Windows-1252 fallback could see it, and an invalid byte in a heading made `json_encode()` return false, so `import_check` answered with an empty body. `agent/post/import.php` now encodes its answer with `JSON_INVALID_UTF8_SUBSTITUTE`. CONTRIBUTING.md has the rule.
|
||||
- UniFi: `rmmUnifiGatewayModel($model)` (`functions/rmm_unifi.php`) knows a gateway by its model code or name - UDM, UDR, UDW, UCG, UXG, EFG, USG, UGW, or a name starting Dream, Cloud Gateway or Gateway - but not the Express (UX, UX7), which is a site's gateway or an access point in someone else's network. The official Network API's `features` say `gateway` for some gateways only - a UCG Fiber comes as `switching`, an EFG with none - so `rmmUnifiNetworkDeviceType($features, $model)` takes `gateway` or the model, then `accessPoint` before `switching`, as an in-wall access point has both. `rmmUnifiControllerDevice()` takes a gateway by its `type` (`ugw`, `udm`, `uxg`), its model, or a `wan1` with an `ifname` or `ip`. Assets already brought in follow `rmmAssetFollow()`'s usual rule: a type the sync wrote is updated, one changed in ITFlow is left.
|
||||
- Microsoft 365 mail: `mailMicrosoftConnectScope($way)` (`functions/mail_graph.php`) - `graph` asks for `openid profile offline_access https://graph.microsoft.com/.default`, `exchange` for the IMAP and SMTP scopes as before. The OAuth tab's `oauth_connect_way` picker sets it - `mailMicrosoftConnectWay()`: Graph before a first connect, then Graph when `mailGraphState()` has a mail permission - and `$_SESSION['mail_oauth_way']` carries it to `admin/oauth_microsoft_mail_callback.php`, which redeems the code for the same. `prompt=consent` is now `prompt=select_account`. The callback keeps the access token as `config_mail_oauth_access_token` only for an Exchange sign-in, as a Graph one isn't XOAUTH2's, goes through `mailGraphHttp()` and `MAIL_MICROSOFT_LOGIN_URL`, and ends with `mailMicrosoftCheck($send_ms, $read_ms, $fresh_exchange)`, which Test OAuth Token Refresh now uses for Microsoft too: Graph's Mail.Send and Mail.ReadWrite first, then `mailMicrosoftExchangeToken()` only for a side Graph doesn't cover. `js/settings.js` leaves a `[data-settings-untracked]` field out of a settings form's unsaved changes.
|
||||
- Saved cards: `billingStripeCardSave($stripe, $client_id, $customer, $pm)` (`functions/billing_pay.php`) is how every client-added card is saved - `autopayCheckoutFinish()`, `cardUpdateFinish()` and the client portal's `stripe_save_card` in `client/post.php`, which matched only Stripe's payment method ID, a new one each time a card is entered. It matches `card.fingerprint` among the cards on the client's Stripe customer (`billingStripeCardTwins()`, one `allPaymentMethods` call), points the oldest saved row at the new payment method and its description, clearing `saved_payment_update_key` when the expiry changed as `cardRefresh()` does, detaches the one it replaced (`billingStripeCardDetach()`) and merges any other copies in (`billingStripeCardMerge()`: `recurring_payments` moved, payment method detached, row deleted), under a per-client `GET_LOCK`. Stripe not answering falls back to saving a new row, as before. `billingStripeCardTwinsNightly()` in `cron/nightly_tasks.php`, before `cardExpiryNightly()`, merges cards already saved twice - only for clients with two saved cards of the same brand and last four digits, keeping the one that runs out last.
|
||||
|
||||
## [26.12.5]
|
||||
|
||||
|
||||
@@ -1566,16 +1566,8 @@ if (isset($_GET['stripe_save_card'])) {
|
||||
|
||||
$saved_payment_description = "$card_brand - $last4 | Exp $exp_month/$exp_year";
|
||||
|
||||
// Insert into client_saved_payment_methods
|
||||
mysqli_query($mysqli, "
|
||||
INSERT INTO client_saved_payment_methods
|
||||
SET
|
||||
saved_payment_provider_method = '$payment_method_id',
|
||||
saved_payment_description = '$saved_payment_description',
|
||||
saved_payment_client_id = $session_client_id,
|
||||
saved_payment_provider_id = $stripe_provider_id,
|
||||
saved_payment_created_at = NOW()
|
||||
");
|
||||
// Saved once - a card saved already, entered again, stays the one saved card (functions/billing_pay.php)
|
||||
billingStripeCardSave($stripe, $session_client_id, stripslashes($stripe_customer_id), $payment_method_details);
|
||||
|
||||
} catch (Exception $e) {
|
||||
// Its customer went from Stripe while the card was being entered
|
||||
|
||||
@@ -746,6 +746,12 @@ while ($config_module_enable_accounting && $row = mysqli_fetch_assoc($sql_quotes
|
||||
|
||||
|
||||
|
||||
// A card a client saved more than once kept once - before the expiry reminders, so a card saved twice isn't reminded about twice (functions/billing_pay.php)
|
||||
$card_twins = $config_module_enable_accounting ? billingStripeCardTwinsNightly() : 0;
|
||||
if ($card_twins) {
|
||||
echo "Saved cards: $card_twins saved more than once merged\n";
|
||||
}
|
||||
|
||||
// Saved cards running out - read back from Stripe, and the client and the team told about the ones on autopay (functions/card_expiry.php)
|
||||
$card_expiry = $config_module_enable_accounting ? cardExpiryNightly() : ['checked' => 0, 'notified' => 0];
|
||||
if ($card_expiry['checked'] || $card_expiry['notified']) {
|
||||
|
||||
@@ -389,6 +389,182 @@ function billingSavedCards($client_id) {
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a card the client just added with Stripe ($pm, its payment method, on
|
||||
* their $customer) - its saved_payment_id. Stripe makes a new payment method
|
||||
* each time a card is entered, the same card or not, so the same card is
|
||||
* known by its fingerprint: one saved already stays the one saved card,
|
||||
* taking the new payment method and its expiry, and every recurring invoice
|
||||
* it pays carries on with it. The payment methods it replaces are detached
|
||||
* at Stripe, and any other copies of it merged in (billingStripeCardMerge()).
|
||||
* Every way a client adds a card comes here - autopay from an invoice's link,
|
||||
* a new card from the expiry reminder's link and the client portal.
|
||||
*/
|
||||
function billingStripeCardSave($stripe, $client_id, $customer, $pm) {
|
||||
global $mysqli;
|
||||
$provider = billingStripeProvider();
|
||||
$client_id = intval($client_id);
|
||||
$provider_id = intval($provider['payment_provider_id'] ?? 0);
|
||||
$pm_id = (string) $pm->id;
|
||||
$pm_sql = escapeSql($pm_id);
|
||||
$description = cardDescription($pm->card ?? null);
|
||||
$checked = cardExpiryReady() ? ', saved_payment_checked_at = NOW()' : '';
|
||||
|
||||
// Two cards added at once take turns here
|
||||
$lock = "itflow_stripe_cards_$client_id";
|
||||
mysqli_query($mysqli, "SELECT GET_LOCK('$lock', 15)");
|
||||
try {
|
||||
$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) {
|
||||
return $saved_id;
|
||||
}
|
||||
|
||||
// The same card saved before, by its fingerprint - oldest first
|
||||
$twins = [];
|
||||
$fingerprint = (string) ($pm->card->fingerprint ?? '');
|
||||
if ($fingerprint !== '' && $customer !== '') {
|
||||
$twins = billingStripeCardTwins($stripe, $client_id, $customer)[$fingerprint] ?? [];
|
||||
}
|
||||
if (!$twins) {
|
||||
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()$checked");
|
||||
return intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
|
||||
$keep = array_shift($twins);
|
||||
$keep_id = intval($keep['saved_payment_id']);
|
||||
// A new expiry is a fresh start for the expiry reminders, as cardRefresh() has it
|
||||
$restart = cardExpiryReady() && billingCardParts($description)['expires'] !== billingCardParts($keep['saved_payment_description'])['expires'] ? ', saved_payment_update_key = NULL' : '';
|
||||
mysqli_query($mysqli, "UPDATE client_saved_payment_methods SET saved_payment_provider_method = '$pm_sql', saved_payment_description = '" . escapeSql($description) . "'$checked$restart
|
||||
WHERE saved_payment_id = $keep_id");
|
||||
billingStripeCardDetach($stripe, (string) $keep['saved_payment_provider_method']);
|
||||
if ($twins) {
|
||||
billingStripeCardMerge($stripe, $client_id, $keep_id, $twins);
|
||||
}
|
||||
$label = billingCardParts($description)['label'];
|
||||
logAudit("Client", "Edit", "$label was added again with Stripe - it stays one saved card, with the details just entered", $client_id);
|
||||
return $keep_id;
|
||||
} finally {
|
||||
mysqli_query($mysqli, "SELECT RELEASE_LOCK('$lock')");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The client's saved cards by the fingerprint of the card each is - from the
|
||||
* cards on their Stripe customer, one call. fingerprint => saved rows
|
||||
* (saved_payment_id, saved_payment_provider_method,
|
||||
* saved_payment_description), oldest first. Empty when Stripe can't say.
|
||||
*/
|
||||
function billingStripeCardTwins($stripe, $client_id, $customer) {
|
||||
global $mysqli;
|
||||
$provider = billingStripeProvider();
|
||||
try {
|
||||
$fingerprints = [];
|
||||
foreach ($stripe->customers->allPaymentMethods($customer, ['type' => 'card', 'limit' => 100])->data as $method) {
|
||||
if (!empty($method->card->fingerprint)) {
|
||||
$fingerprints[(string) $method->id] = (string) $method->card->fingerprint;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
logApp("Stripe", "warning", "The cards on Stripe customer $customer couldn't be read: " . $e->getMessage());
|
||||
return [];
|
||||
}
|
||||
$by = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT saved_payment_id, saved_payment_provider_method, saved_payment_description FROM client_saved_payment_methods
|
||||
WHERE saved_payment_client_id = " . intval($client_id) . " AND saved_payment_provider_id = " . intval($provider['payment_provider_id'] ?? 0) . "
|
||||
ORDER BY saved_payment_id ASC");
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$fingerprint = $fingerprints[(string) $row['saved_payment_provider_method']] ?? '';
|
||||
if ($fingerprint !== '') {
|
||||
$by[$fingerprint][] = $row;
|
||||
}
|
||||
}
|
||||
return $by;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge copies of one saved card into the one kept ($keep_id): the recurring
|
||||
* invoices they pay move to it, their payment methods are detached at Stripe
|
||||
* and the copies go. Logged.
|
||||
*/
|
||||
function billingStripeCardMerge($stripe, $client_id, $keep_id, array $twins) {
|
||||
global $mysqli;
|
||||
$client_id = intval($client_id);
|
||||
$keep_id = intval($keep_id);
|
||||
foreach ($twins as $twin) {
|
||||
$twin_id = intval($twin['saved_payment_id']);
|
||||
if ($twin_id === $keep_id) {
|
||||
continue;
|
||||
}
|
||||
mysqli_query($mysqli, "UPDATE recurring_payments SET recurring_payment_saved_payment_id = $keep_id WHERE recurring_payment_saved_payment_id = $twin_id");
|
||||
billingStripeCardDetach($stripe, (string) $twin['saved_payment_provider_method']);
|
||||
mysqli_query($mysqli, "DELETE FROM client_saved_payment_methods WHERE saved_payment_id = $twin_id AND saved_payment_client_id = $client_id");
|
||||
}
|
||||
$label = billingCardParts((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT saved_payment_description FROM client_saved_payment_methods WHERE saved_payment_id = $keep_id"))[0] ?? ''))['label'];
|
||||
$copies = count($twins);
|
||||
logAudit("Client", "Edit", "$label was saved " . ($copies + 1) . " times - merged into one saved card, and the autopay on the " . ($copies === 1 ? 'copy' : 'copies') . " moved to it", $client_id);
|
||||
}
|
||||
|
||||
/** Detach a payment method from its Stripe customer - one Stripe no longer has, or that is detached already, is fine. */
|
||||
function billingStripeCardDetach($stripe, $pm_id) {
|
||||
if ($pm_id === '') {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
$stripe->paymentMethods->detach($pm_id, []);
|
||||
} catch (\Stripe\Exception\InvalidRequestException $e) {
|
||||
if (!in_array($e->getStripeCode(), ['resource_missing', 'payment_method_unexpected_state'], true) && stripos($e->getMessage(), 'not attached') === false) {
|
||||
logApp("Stripe", "warning", "Couldn't detach payment method $pm_id: " . $e->getMessage());
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
logApp("Stripe", "warning", "Couldn't detach payment method $pm_id: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The night's tidy (cron/nightly_tasks.php): a card saved more than once by
|
||||
* the same client - each time it was entered, before billingStripeCardSave()
|
||||
* knew it - kept once. Only clients with two saved cards of the same brand
|
||||
* and last four digits are asked about, their cards' fingerprints read from
|
||||
* Stripe; the copy that runs out last is kept (the oldest of those), the
|
||||
* others merged into it. The number of copies merged.
|
||||
*/
|
||||
function billingStripeCardTwinsNightly() {
|
||||
global $mysqli;
|
||||
$provider = billingStripeProvider();
|
||||
if (!$provider || devModeOn()) {
|
||||
return 0;
|
||||
}
|
||||
$stripe = billingStripeClient();
|
||||
$provider_id = intval($provider['payment_provider_id']);
|
||||
$merged = 0;
|
||||
$sql = mysqli_query($mysqli, "SELECT DISTINCT saved_payment_client_id FROM client_saved_payment_methods
|
||||
WHERE saved_payment_provider_id = $provider_id
|
||||
GROUP BY saved_payment_client_id, SUBSTRING_INDEX(saved_payment_description, ' | ', 1) HAVING COUNT(*) > 1 LIMIT 200");
|
||||
while ($row = mysqli_fetch_row($sql)) {
|
||||
$client_id = intval($row[0]);
|
||||
$customer = billingStripeCustomer($client_id);
|
||||
if ($customer === '') {
|
||||
continue;
|
||||
}
|
||||
foreach (billingStripeCardTwins($stripe, $client_id, $customer) as $twins) {
|
||||
if (count($twins) < 2) {
|
||||
continue;
|
||||
}
|
||||
// The one that runs out last, then the oldest
|
||||
usort($twins, function ($a, $b) {
|
||||
return [billingCardParts($b['saved_payment_description'])['expires'], intval($a['saved_payment_id'])]
|
||||
<=> [billingCardParts($a['saved_payment_description'])['expires'], intval($b['saved_payment_id'])];
|
||||
});
|
||||
$keep = array_shift($twins);
|
||||
billingStripeCardMerge($stripe, $client_id, $keep['saved_payment_id'], $twins);
|
||||
$merged += count($twins);
|
||||
}
|
||||
}
|
||||
return $merged;
|
||||
}
|
||||
|
||||
/*
|
||||
* The autopay on an invoice - the recurring invoice's it came from, which
|
||||
* cron/nightly_tasks.php charges on its due date while it is sent and still
|
||||
@@ -731,19 +907,9 @@ function autopayCheckoutFinish(array $invoice, $session_id) {
|
||||
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));
|
||||
}
|
||||
// The card - saved once, however often it comes back, and however often it's entered
|
||||
$description = cardDescription($pm->card ?? null);
|
||||
$saved_id = billingStripeCardSave($stripe, $client_id, $customer, $pm);
|
||||
$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']) . ",
|
||||
|
||||
@@ -399,17 +399,9 @@ function cardUpdateFinish(array $card, $session_id): array
|
||||
return $fail("We couldn't confirm your card with Stripe just now - reload this page in a minute, or get in touch.");
|
||||
}
|
||||
|
||||
// The new card - saved once, however often it comes back
|
||||
$provider_id = intval($provider['payment_provider_id']);
|
||||
$pm_sql = escapeSql($pm_id);
|
||||
// The new card - saved once, however often it comes back; the same card with a new expiry is the old one, kept up to date
|
||||
$description = cardDescription($pm->card ?? null);
|
||||
$new_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 (!$new_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_payment_checked_at = NOW()");
|
||||
$new_id = intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
$new_id = billingStripeCardSave($stripe, $client_id, $customer, $pm);
|
||||
|
||||
// Every recurring invoice of the client's the old card paid - paused ones too, which would fail on it
|
||||
mysqli_query($mysqli, "UPDATE recurring_payments JOIN recurring_invoices ON recurring_invoice_id = recurring_payment_recurring_invoice_id
|
||||
|
||||
Reference in New Issue
Block a user