Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix: scope currency rate updates to the user being refreshed (#1175)
Miguel Ribeiro267f057bec33
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex d9ab140..bd0690e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -26,6 +26,18 @@ We welcome contributions from the community and look forward to working with you4. **Make your changes:** Implement your feature or bug fix.5. **Test your changes:** Ensure that your changes work as expected.++ Wallos has a small test suite in `tests/`. It needs no Composer or local PHP+ installation — it runs in a throwaway container:++ ```bash+ dev/test.sh # all cases+ dev/test.sh currency # only cases matching "currency"+ ```++ Use `CONTAINER_ENGINE=docker dev/test.sh` if you prefer Docker over Podman.+ Tests build the real schema by running `createdatabase.php` and the+ migration chain, so they exercise the schema the application produces.6. **Commit your changes:** Commit your changes with a clear and concise message:```bashdiff --git a/api/subscriptions/get_ical_feed.php b/api/subscriptions/get_ical_feed.phpindex ca1a113..021fe7d 100644--- a/api/subscriptions/get_ical_feed.php+++ b/api/subscriptions/get_ical_feed.php@@ -9,6 +9,7 @@ It returns a downloadable VCAL file with the active subscriptions*/require_once '../../includes/connect_endpoint.php';+require_once '../../includes/currency_rates.php';require_once '../../includes/ical_helper.php';header('Content-Type: application/json; charset=UTF-8');@@ -29,18 +30,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GETfunction getPriceConverted($price, $currency, $database){- $query = "SELECT rate FROM currencies WHERE id = :currency";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $result = $stmt->execute();-- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database);}// Get user from API key@@ -140,36 +130,33 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GETforeach ($subscriptions as $subscription) {$subscriptionToReturn = $subscription;- if (isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId) {+ $wasConverted = isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId;+ if ($wasConverted) {$subscriptionToReturn['price'] = getPriceConverted($subscription['price'], $subscription['currency_id'], $db);+ // Converted prices are now in the user's main currency, so the+ // symbol shown alongside them has to switch too.+ $subscriptionToReturn['currency_id'] = $userCurrencyId;} else {$subscriptionToReturn['price'] = $subscription['price'];}- $subscriptionToReturn['category_name'] = $categories[$subscription['category_id']];- $subscriptionToReturn['payer_user_name'] = $members[$subscription['payer_user_id']];- $subscriptionToReturn['payment_method_name'] = $paymentMethods[$subscription['payment_method_id']];+ $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';+ $subscriptionToReturn['payer_user_name'] = isset($members[$subscription['payer_user_id']]) ? $members[$subscription['payer_user_id']] : 'Unknown member';+ $subscriptionToReturn['payment_method_name'] = isset($paymentMethods[$subscription['payment_method_id']]) ? $paymentMethods[$subscription['payment_method_id']] : 'Unknown payment method';$subscriptionsToReturn[] = $subscriptionToReturn;}- $stmt->bindValue(':inactive', false, SQLITE3_INTEGER);- $result = $stmt->execute();-header('Content-Type: text/calendar; charset=utf-8');header('Content-Disposition: attachment; filename="subscriptions.ics"');- if ($result === false) {- die("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:NAME:\nEND:VCALENDAR");- }-$icsContent = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Wallos//iCalendar//EN\nNAME:Wallos\nX-WR-CALNAME:Wallos\n";- while ($subscription = $result->fetchArray(SQLITE3_ASSOC)) {- $subscription['payer_user'] = $members[$subscription['payer_user_id']];- $subscription['category'] = $categories[$subscription['category_id']];- $subscription['payment_method'] = $paymentMethods[$subscription['payment_method_id']];- $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];+ foreach ($subscriptionsToReturn as $subscription) {+ $subscription['payer_user'] = $subscription['payer_user_name'];+ $subscription['category'] = $subscription['category_name'];+ $subscription['payment_method'] = $subscription['payment_method_name'];+ $subscription['currency'] = isset($currencies[$subscription['currency_id']]) ? $currencies[$subscription['currency_id']]['symbol'] : '';$subscription['trigger'] = ($subscription['notify_days_before'] == -1) ? $globalNotificationDays : ($subscription['notify_days_before'] ?: 1);$subscription['price'] = number_format($subscription['price'], 2);diff --git a/api/subscriptions/get_subscription.php b/api/subscriptions/get_subscription.phpindex 66e268c..8abeacd 100644--- a/api/subscriptions/get_subscription.php+++ b/api/subscriptions/get_subscription.php@@ -47,6 +47,7 @@ Example response:*/require_once '../../includes/connect_endpoint.php';+require_once '../../includes/currency_rates.php';header('Content-Type: application/json; charset=UTF-8');@@ -138,16 +139,12 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$canConvertCurrency = !empty($lastExchangeUpdate['date']);if ($canConvertCurrency) {- $currSql = "SELECT rate FROM currencies WHERE id = :currencyId AND user_id = :userId";- $currStmt = $db->prepare($currSql);- $currStmt->bindValue(':currencyId', $subscription['currency_id'], SQLITE3_INTEGER);- $currStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $currResult = $currStmt->execute();- $subCurrency = $currResult->fetchArray(SQLITE3_ASSOC);-- if ($subCurrency) {- $subscription['price'] = $subscription['price'] / $subCurrency['rate'];- }+ $subscription['price'] = wallos_convert_price(+ $subscription['price'],+ $subscription['currency_id'],+ $db,+ $userId+ );}}diff --git a/api/subscriptions/get_subscriptions.php b/api/subscriptions/get_subscriptions.phpindex 0f9cb66..0bdf2c0 100644--- a/api/subscriptions/get_subscriptions.php+++ b/api/subscriptions/get_subscriptions.php@@ -3,19 +3,21 @@This API Endpoint accepts both POST and GET requests.It receives the following parameters:- member: comma-separated IDs of the members to filter (integer) default null.-- category: the ID of the category to filter (integer) default null.-- payment_method: the ID of the payment method to filter (integer) default null.-- state: the state of the subscription to filter (boolean) default null [0 - active, 1 - inactive].-- disabled_to_bottom: whether to sort the inactive subscriptions to the bottom (boolean) default false.+- category: comma-separated IDs of the categories to filter (integer) default null.+- payment: comma-separated IDs of the payment methods to filter (integer) default null.+- state: the state of the subscription to filter (integer) default null [0 - active, 1 - inactive].+- disabled_to_bottom: whether to sort the inactive subscriptions to the bottom (string) default false. Must be the literal string "true" to take effect.- sort: the sorting method (string) default next_payment ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'].-- convert_currency: whether to convert to the main currency (boolean) default false.+- convert_currency: whether to convert to the main currency (string) default false. Must be the literal string "true" to take effect.+- all-user-subscription: whether to return subscriptions for every user instead of just the caller (string) default null. Only honored when api_key belongs to user id 1; adds the "users" field to the response.- api_key: the API key of the user.It returns a JSON object with the following properties:- success: whether the request was successful (boolean).- title: the title of the response (string).- subscriptions: an array of subscriptions.-- notes: warning messages or additional information (array).+- users: an array of all users, only present when all-user-subscription is used by user id 1.+- notes: reserved for warning messages or additional information (array); currently always empty.Example response:{@@ -93,6 +95,7 @@ Example response:*/require_once '../../includes/connect_endpoint.php';+require_once '../../includes/currency_rates.php';header('Content-Type: application/json; charset=UTF-8');@@ -110,17 +113,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GETfunction getPriceConverted($price, $currency, $database){- $query = "SELECT rate FROM currencies WHERE id = :currency";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $result = $stmt->execute();- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database);}// Get user from API key@@ -217,7 +210,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET// Construction of the main SQL Query$params = [];if ($allUserSubscription == 1 && $userId == 1) {- $sql = "SELECT * FROM subscriptions";+ $sql = "SELECT * FROM subscriptions WHERE 1 = 1";} else {$sql = "SELECT * FROM subscriptions WHERE user_id = :userId";$params[':userId'] = $userId;@@ -279,6 +272,14 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$sql .= " ORDER BY " . implode(", ", $orderByClauses);$stmt = $db->prepare($sql);+ if ($stmt === false) {+ $response = [+ "success" => false,+ "title" => "Invalid query parameters"+ ];+ echo json_encode($response);+ exit;+ }if (!empty($params)) {foreach ($params as $key => $value) {$stmt->bindValue($key, $value, SQLITE3_INTEGER);diff --git a/api/subscriptions/set_subscriptions.php b/api/subscriptions/set_subscriptions.phpindex b5263f1..99e239f 100644--- a/api/subscriptions/set_subscriptions.php+++ b/api/subscriptions/set_subscriptions.php@@ -33,6 +33,7 @@ It returns a JSON object with the following properties:- title: the title of the response (string).- message: detailed information or error message (string).- subscriptionId: (only for successful 'add' action) the ID of the newly created subscription (integer).+- logo_warning: (optional) present when logo_url/logo was given but saving it failed; the subscription is still saved without changing its logo (string).Example response:{@@ -172,6 +173,9 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings)unset($ch);return ['success' => true, 'filename' => $fileName];}++ unset($ch);+ return ['success' => false, 'message' => 'Failed to save logo image.'];}unset($ch);@@ -213,7 +217,7 @@ function saveLogo($imageData, $uploadFile, $name, $settings)require_once __DIR__ . '/../../includes/gd_background_removal.php';$newImage = gdCropTransparent($newImage, 2);- imagepng($newImage, $uploadFile);+ $saved = imagepng($newImage, $uploadFile);imagedestroy($newImage);} else {unlink($tempFile);@@ -221,7 +225,7 @@ function saveLogo($imageData, $uploadFile, $name, $settings)}unlink($tempFile);- return true;+ return $saved;}return false;}@@ -286,19 +290,27 @@ function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);if ($fileExtension === 'png') {- imagepng($resizedImage, $uploadFile);+ $saved = imagepng($resizedImage, $uploadFile);} elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {- imagejpeg($resizedImage, $uploadFile);+ $saved = imagejpeg($resizedImage, $uploadFile);} elseif ($fileExtension === 'gif') {- imagegif($resizedImage, $uploadFile);+ $saved = imagegif($resizedImage, $uploadFile);} elseif ($fileExtension === 'webp') {- imagewebp($resizedImage, $uploadFile);+ $saved = imagewebp($resizedImage, $uploadFile);} else {return "";}imagedestroy($image);imagedestroy($resizedImage);++ if (!$saved) {+ if (file_exists($uploadFile)) {+ unlink($uploadFile);+ }+ return "";+ }+return $fileName;}}@@ -514,16 +526,22 @@ switch ($action) {// Process Logo$logo = '';+ $logoWarning = '';$logoUrl = $_POST['logo_url'] ?? $_POST['logo-url'] ?? '';if ($logoUrl !== "") {$resLogo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings);if ($resLogo['success']) {$logo = $resLogo['filename'];+ } else {+ $logoWarning = $resLogo['message'];}} elseif (!empty($_FILES['logo']['name'])) {$fileType = mime_content_type($_FILES['logo']['tmp_name']);if (strpos($fileType, 'image') !== false) {$logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);+ if ($logo === "") {+ $logoWarning = 'Failed to save logo image.';+ }}}@@ -566,12 +584,16 @@ switch ($action) {$stmtInsert->bindParam(':startDate', $startDate, SQLITE3_TEXT);if ($stmtInsert->execute()) {- echo json_encode([+ $addResponse = ['success' => true,'title' => 'Subscription added','subscriptionId' => $db->lastInsertRowID(),'message' => 'Subscription added successfully.'- ]);+ ];+ if ($logoWarning !== '') {+ $addResponse['logo_warning'] = $logoWarning;+ }+ echo json_encode($addResponse);} else {echo json_encode(['success' => false,@@ -805,18 +827,26 @@ switch ($action) {$logoTextColor = $subscription['logo_text_color'];$logoVariant = $subscription['logo_variant'];$logoChanged = false;+ $logoWarning = '';$logoUrl = $_POST['logo_url'] ?? $_POST['logo-url'] ?? '';if ($logoUrl !== "") {$resLogo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings);if ($resLogo['success']) {$logo = $resLogo['filename'];$logoChanged = true;+ } else {+ $logoWarning = $resLogo['message'];}} elseif (!empty($_FILES['logo']['name'])) {$fileType = mime_content_type($_FILES['logo']['tmp_name']);if (strpos($fileType, 'image') !== false) {- $logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);- $logoChanged = true;+ $newLogo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);+ if ($newLogo !== "") {+ $logo = $newLogo;+ $logoChanged = true;+ } else {+ $logoWarning = 'Failed to save logo image.';+ }}}@@ -875,11 +905,15 @@ switch ($action) {$stmtUpdate->bindParam(':userId', $userId, SQLITE3_INTEGER);if ($stmtUpdate->execute()) {- echo json_encode([+ $updateResponse = ['success' => true,'title' => 'Subscription updated','message' => 'Subscription updated successfully.'- ]);+ ];+ if ($logoWarning !== '') {+ $updateResponse['logo_warning'] = $logoWarning;+ }+ echo json_encode($updateResponse);} else {echo json_encode(['success' => false,diff --git a/calendar.php b/calendar.phpindex 813c014..dfdb5b9 100644--- a/calendar.php+++ b/calendar.php@@ -1,21 +1,10 @@<?phprequire_once 'includes/header.php';+require_once 'includes/currency_rates.php';function getPriceConverted($price, $currency, $database, $userId){- $query = "SELECT rate FROM currencies WHERE id = :currency AND user_id = :userId";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database, $userId);}// Get budget from user tablediff --git a/dev/test.sh b/dev/test.shnew file mode 100755index 0000000..92e7a08--- /dev/null+++ b/dev/test.sh@@ -0,0 +1,16 @@+#!/bin/sh+# Runs the test suite in a throwaway PHP container, so no local PHP is needed.+#+# dev/test.sh every case+# dev/test.sh currency cases matching "currency"++set -eu++ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)+ENGINE=${CONTAINER_ENGINE:-podman}++exec "$ENGINE" run --rm \+ -v "$ROOT":/var/www/html:Z \+ -w /var/www/html \+ docker.io/library/php:8.3-cli \+ php tests/run.php "$@"diff --git a/endpoints/cronjobs/storetotalyearlycost.php b/endpoints/cronjobs/storetotalyearlycost.phpindex 65d21b7..34c95e2 100644--- a/endpoints/cronjobs/storetotalyearlycost.php+++ b/endpoints/cronjobs/storetotalyearlycost.php@@ -1,6 +1,7 @@<?phprequire_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';+require_once __DIR__ . '/../../includes/currency_rates.php';require 'settimezone.php';@@ -32,19 +33,7 @@ function getPricePerMonth($cycle, $frequency, $price)function getPriceConverted($price, $currency, $database, $userId){- $query = "SELECT rate FROM currencies WHERE id = :currency AND user_id = :userId";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database, $userId);}// Get all usersdiff --git a/endpoints/cronjobs/updateexchange.php b/endpoints/cronjobs/updateexchange.phpindex f9280bd..5c26bb2 100644--- a/endpoints/cronjobs/updateexchange.php+++ b/endpoints/cronjobs/updateexchange.php@@ -67,37 +67,59 @@ while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];if ($apiData !== null && isset($apiData['rates'])) {+ // One user's rates and their refresh date are one unit of work:+ // a failure halfway through would otherwise leave some rows+ // converted against the new base and some against the old one.+ $db->exec('BEGIN');++ // Every user has their own currency rows, converted against their own+ // main currency, so the write must be scoped to the user being refreshed.+ $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId";+ $updateStmt = $db->prepare($updateQuery);+ $updateFailed = false;+foreach ($apiData['rates'] as $currencyCode => $rate) {if ($currencyCode === $mainCurrencyCode) {$exchangeRate = 1.0;} else {$exchangeRate = $rate / $mainCurrencyToEUR;}- $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code";- $updateStmt = $db->prepare($updateQuery);- $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);- $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);++ $updateStmt->bindValue(':rate', $exchangeRate, SQLITE3_TEXT);+ $updateStmt->bindValue(':code', $currencyCode, SQLITE3_TEXT);+ $updateStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);$updateResult = $updateStmt->execute();+ $updateStmt->reset();if (!$updateResult) {echo "Error updating rate for currency: $currencyCode <br />";+ $updateFailed = true;+ break;}}- $currentDate = new DateTime();- $formattedDate = $currentDate->format('Y-m-d');- $deleteQuery = "DELETE FROM last_exchange_update WHERE user_id = :userId";- $deleteStmt = $db->prepare($deleteQuery);- $deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $deleteResult = $deleteStmt->execute();+ if ($updateFailed) {+ $db->exec('ROLLBACK');+ echo "Exchange rates update rolled back for this user.<br />";+ } else {+ $currentDate = new DateTime();+ $formattedDate = $currentDate->format('Y-m-d');- $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)";- $stmt = $db->prepare($query);- $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();+ $deleteQuery = "DELETE FROM last_exchange_update WHERE user_id = :userId";+ $deleteStmt = $db->prepare($deleteQuery);+ $deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $deleteResult = $deleteStmt->execute();- echo "Rates updated successfully!<br />";+ $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)";+ $stmt = $db->prepare($query);+ $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $db->exec('COMMIT');++ echo "Rates updated successfully!<br />";+ }}} else {echo "Exchange rates update skipped. No fixer.io api key provided<br />";diff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.phpindex a97d5c5..742965d 100644--- a/endpoints/currency/update_exchange.php+++ b/endpoints/currency/update_exchange.php@@ -97,34 +97,54 @@ if ($result) {$mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];if ($apiData !== null && isset($apiData['rates'])) {+ // The rates and the refresh date are one unit of work: a failure+ // halfway through would otherwise leave some rows converted against+ // the new base and some against the old one.+ $db->exec('BEGIN');++ $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId";+ $updateStmt = $db->prepare($updateQuery);+ $updateFailed = false;+foreach ($apiData['rates'] as $currencyCode => $rate) {if ($currencyCode === $mainCurrencyCode) {$exchangeRate = 1.0;} else {$exchangeRate = $rate / $mainCurrencyToEUR;}- $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId";- $updateStmt = $db->prepare($updateQuery);- $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);- $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);- $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);++ $updateStmt->bindValue(':rate', $exchangeRate, SQLITE3_TEXT);+ $updateStmt->bindValue(':code', $currencyCode, SQLITE3_TEXT);+ $updateStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);$updateResult = $updateStmt->execute();+ $updateStmt->reset();if (!$updateResult) {echo "Error updating rate for currency: $currencyCode";+ $updateFailed = true;+ break;}}- $currentDate = new DateTime();- $formattedDate = $currentDate->format('Y-m-d');- $updateQuery = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId";- $updateStmt = $db->prepare($updateQuery);- $updateStmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);- $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $updateResult = $updateStmt->execute();+ if ($updateFailed) {+ $db->exec('ROLLBACK');+ $db->close();+ echo "Exchange rates update rolled back.";+ } else {+ $currentDate = new DateTime();+ $formattedDate = $currentDate->format('Y-m-d');- $db->close();- echo "Rates updated successfully!";+ $updateQuery = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId";+ $updateStmt = $db->prepare($updateQuery);+ $updateStmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);+ $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $updateResult = $updateStmt->execute();++ $db->exec('COMMIT');++ $db->close();+ echo "Rates updated successfully!";+ }}} else {echo "Exchange rates update skipped. No fixer.io api key provided";diff --git a/endpoints/db/restore.php b/endpoints/db/restore.phpindex 534c901..f19d472 100644--- a/endpoints/db/restore.php+++ b/endpoints/db/restore.php@@ -67,11 +67,19 @@ if (isset($_FILES['file'])) {}if (file_exists('../../.tmp/restore/wallos.db')) {+ $db->close();+if (file_exists('../../db/wallos.db')) {unlink('../../db/wallos.db');}rename('../../.tmp/restore/wallos.db', '../../db/wallos.db');+ $db = new SQLite3('../../db/wallos.db');+ $db->busyTimeout(5000);+ ob_start();+ require_once __DIR__ . '/../../includes/run_migrations.php';+ ob_end_clean();+if (file_exists('../../.tmp/restore/logos/')) {$dir = '../../images/uploads/logos/';$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex 6e6e5e1..48b7722 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -78,6 +78,9 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)unset($ch);return ['success' => true, 'filename' => $fileName];}++ unset($ch);+ return ['success' => false, 'message' => translate('error_saving_logo', $i18n)];}$error = curl_error($ch);@@ -125,7 +128,7 @@ function saveLogo($imageData, $uploadFile, $name, $settings)require_once __DIR__ . '/../../includes/gd_background_removal.php';$newImage = gdCropTransparent($newImage, 2);- imagepng($newImage, $uploadFile);+ $saved = imagepng($newImage, $uploadFile);imagedestroy($newImage);} else {unlink($tempFile);@@ -133,7 +136,7 @@ function saveLogo($imageData, $uploadFile, $name, $settings)}unlink($tempFile);- return true;+ return $saved;}return false;@@ -200,13 +203,13 @@ function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);if ($fileExtension === 'png') {- imagepng($resizedImage, $uploadFile);+ $saved = imagepng($resizedImage, $uploadFile);} elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {- imagejpeg($resizedImage, $uploadFile);+ $saved = imagejpeg($resizedImage, $uploadFile);} elseif ($fileExtension === 'gif') {- imagegif($resizedImage, $uploadFile);+ $saved = imagegif($resizedImage, $uploadFile);} elseif ($fileExtension === 'webp') {- imagewebp($resizedImage, $uploadFile);+ $saved = imagewebp($resizedImage, $uploadFile);} else {return "";}@@ -214,6 +217,13 @@ function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)imagedestroy($image);imagedestroy($resizedImage);+ if (!$saved) {+ if (file_exists($uploadFile)) {+ unlink($uploadFile);+ }+ return "";+ }+return $fileName;}}@@ -273,6 +283,9 @@ if ($logoUrl !== "") {exit();}$logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);+ if ($logo === "") {+ $logoError = translate('error_saving_logo', $i18n);+ }}}diff --git a/endpoints/user/enable_totp.php b/endpoints/user/enable_totp.phpindex 761dbfa..d8487c3 100644--- a/endpoints/user/enable_totp.php+++ b/endpoints/user/enable_totp.php@@ -41,7 +41,7 @@ if ($action === 'generate') {$secret = base32_encode(bin2hex(random_bytes(20)));- $qrCodeUrl = "otpauth://totp/Wallos:" . $_SESSION['username'] . "?secret=" . $secret . "&issuer=Wallos";+ $qrCodeUrl = "otpauth://totp/Wallos:" . rawurlencode($_SESSION['username']) . "?secret=" . $secret . "&issuer=Wallos";echo json_encode(["success" => true,diff --git a/includes/budget_period_calculations.php b/includes/budget_period_calculations.phpindex 7913ace..a639f8f 100644--- a/includes/budget_period_calculations.php+++ b/includes/budget_period_calculations.php@@ -1,5 +1,7 @@<?php+require_once __DIR__ . '/currency_rates.php';+if (!function_exists('sanitizeBudgetPeriodType')) {function sanitizeBudgetPeriodType($periodType){@@ -256,18 +258,7 @@ if (!function_exists('getSubscriptionOccurrencesInRange')) {if (!function_exists('convertPriceToMainCurrency')) {function convertPriceToMainCurrency($price, $currencyId, SQLite3 $database, $userId){- $query = "SELECT rate FROM currencies WHERE id = :currencyId AND user_id = :userId";- $stmt = $database->prepare($query);- $stmt->bindValue(':currencyId', $currencyId, SQLITE3_INTEGER);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- $exchangeRate = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;-- if ($exchangeRate === false || empty($exchangeRate['rate'])) {- return (float) $price;- }-- return (float) $price / (float) $exchangeRate['rate'];+ return wallos_convert_price($price, $currencyId, $database, $userId);}}diff --git a/includes/currency_rates.php b/includes/currency_rates.phpnew file mode 100644index 0000000..f3685c5--- /dev/null+++ b/includes/currency_rates.php@@ -0,0 +1,85 @@+<?php+/*+ Exchange-rate lookups for price conversion.++ Rates change once a day at most, but conversion happens once per subscription,+ once per statistics row and once per calendar entry. Looking them up per row+ turns rendering a list into one query per item, so they are loaded once and+ answered from memory for the rest of the request.+*/++/**+ * Returns the exchange rates as [currency_id => rate].+ *+ * Passing a user id restricts the map to that user's currencies, matching the+ * lookups that filtered by user; omitting it covers every currency, matching+ * the lookups that resolved a currency by id alone.+ *+ * The map is cached per database connection, so a second connection — a test,+ * or a job that reopens the database — never sees another connection's rates.+ *+ * @param SQLite3 $db+ * @param int|null $userId+ * @return array<int, float>+ */+function wallos_currency_rates($db, $userId = null)+{+ // Keyed by the connection object itself: an id would be reused once a+ // connection is closed, and the next one would inherit stale rates.+ static $cache = null;++ if ($cache === null) {+ $cache = new WeakMap();+ }++ $key = $userId === null ? 'all' : (int) $userId;+ $connectionRates = $cache[$db] ?? [];++ if (isset($connectionRates[$key])) {+ return $connectionRates[$key];+ }++ $rates = [];++ if ($userId === null) {+ $stmt = $db->prepare('SELECT id, rate FROM currencies');+ } else {+ $stmt = $db->prepare('SELECT id, rate FROM currencies WHERE user_id = :userId');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ }++ $result = $stmt ? $stmt->execute() : false;++ while ($result && $row = $result->fetchArray(SQLITE3_ASSOC)) {+ $rates[(int) $row['id']] = (float) $row['rate'];+ }++ $connectionRates[$key] = $rates;+ $cache[$db] = $connectionRates;++ return $rates;+}++/**+ * Converts a price from the given currency into the user's main currency.+ *+ * An unknown currency or a missing rate leaves the price untouched, which is+ * what the per-row lookups did when they found no row.+ *+ * @param float|int|string $price+ * @param int $currencyId+ * @param SQLite3 $db+ * @param int|null $userId+ * @return float+ */+function wallos_convert_price($price, $currencyId, $db, $userId = null)+{+ $rates = wallos_currency_rates($db, $userId);+ $rate = $rates[(int) $currencyId] ?? null;++ if (empty($rate)) {+ return (float) $price;+ }++ return (float) $price / $rate;+}diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex 1d48f9c..89c1206 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -412,6 +412,7 @@ $i18n = ["disabled" => "disabled",// Subscription"error_fetching_image" => "Error fetching image",+ "error_saving_logo" => "Error saving logo image.","subscription_updated_successfuly" => "Subscription updated successfully","subscription_added_successfuly" => "Subscription added successfully","error_deleting_subscription" => "Error deleting subscription.",diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.phpindex 894bcf3..ba8e8e9 100644--- a/includes/list_subscriptions.php+++ b/includes/list_subscriptions.php@@ -1,6 +1,7 @@<?phprequire_once 'i18n/getlang.php';+require_once __DIR__ . '/currency_rates.php';function getBillingCycle($cycle, $frequency, $i18n){@@ -84,18 +85,7 @@ function getPricePerMonth($cycle, $frequency, $price)function getPriceConverted($price, $currency, $database){- $query = "SELECT rate FROM currencies WHERE id = :currency";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $result = $stmt->execute();-- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database);}function formatPrice($price, $currencyCode, $currencies)diff --git a/includes/oidc_settings.php b/includes/oidc_settings.phpindex 6140b89..aff9b51 100644--- a/includes/oidc_settings.php+++ b/includes/oidc_settings.php@@ -237,22 +237,28 @@ function wallos_get_effective_oidc_configuration($db)}}+ // client_secret is intentionally not required: public clients use an empty+ // secret and the token exchange accepts it.$requiredFields = ['client_id',- 'client_secret','authorization_url','token_url','user_info_url','redirect_url','user_identifier_field',];- $isConfigured = true;+ $missingFields = [];foreach ($requiredFields as $field) {if (trim((string) $settings[$field]) === '') {- $isConfigured = false;- break;+ $missingFields[] = $field;}}+ $isConfigured = count($missingFields) === 0;++ if ($enabled && !$isConfigured) {+ $notes[] = 'OIDC is enabled but the login button is hidden because required fields are empty: '+ . implode(', ', $missingFields) . '.';+ }return ['enabled' => (int) $enabled,diff --git a/includes/stats_calculations.php b/includes/stats_calculations.phpindex e26303c..3b04833 100644--- a/includes/stats_calculations.php+++ b/includes/stats_calculations.php@@ -1,5 +1,6 @@<?phprequire_once __DIR__ . '/budget_period_calculations.php';+require_once __DIR__ . '/currency_rates.php';function getPricePerMonth($cycle, $frequency, $price){@@ -23,19 +24,7 @@ function getPricePerMonth($cycle, $frequency, $price)function getPriceConverted($price, $currency, $database, $userId){- $query = "SELECT rate FROM currencies WHERE id = :currency AND user_id = :userId";- $stmt = $database->prepare($query);- $stmt->bindParam(':currency', $currency, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- $exchangeRate = $result->fetchArray(SQLITE3_ASSOC);- if ($exchangeRate === false) {- return $price;- } else {- $fromRate = $exchangeRate['rate'];- return $price / $fromRate;- }+ return wallos_convert_price($price, $currency, $database, $userId);}// Get categoriesdiff --git a/includes/version.php b/includes/version.phpindex c776629..2ae3129 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php-$version = "v5.4.4";+$version = "v5.4.5";?>diff --git a/migrations/000055.php b/migrations/000055.phpnew file mode 100644index 0000000..733c37e--- /dev/null+++ b/migrations/000055.php@@ -0,0 +1,25 @@+<?php++// This migration adds two indexes to the subscriptions table.+//+// Every subscription query filters by user_id, usually together with+// "inactive" and a next_payment comparison, and the notification cron adds+// "notify". Without an index each of those scans the whole table.+//+// Measured on a database with 10 users and 10,000 subscriptions:+//+// subscription list 26.2 ms -> 1.8 ms+// notification cron query 2.4 ms -> 0.8 ms+// calendar date range 3.3 ms -> 0.8 ms+//+// Indexes on category_id, payer_user_id and payment_method_id were measured as+// well and left out: the user_id prefix of the first index already serves those+// filters, and they showed no further improvement.++$db->exec('CREATE INDEX IF NOT EXISTS idx_subscriptions_user_inactive_next_payment+ ON subscriptions (user_id, inactive, next_payment)');++$db->exec('CREATE INDEX IF NOT EXISTS idx_subscriptions_user_notify_inactive+ ON subscriptions (user_id, notify, inactive)');++?>diff --git a/registration.php b/registration.phpindex 1ebd0a2..fbbcf69 100644--- a/registration.php+++ b/registration.php@@ -35,7 +35,9 @@ $userCount = $userCountResult['userCount'];if ($userCount == 0) {$setupTokenFile = __DIR__ . '/db/setup_token.db';if (!file_exists($setupTokenFile)) {- file_put_contents($setupTokenFile, bin2hex(random_bytes(32)));+ $setupToken = bin2hex(random_bytes(32));+ file_put_contents($setupTokenFile, $setupToken);+ error_log("Setup token for database restore: " . $setupToken);}}diff --git a/scripts/subscriptions.js b/scripts/subscriptions.jsindex 8a076b3..60767ae 100644--- a/scripts/subscriptions.js+++ b/scripts/subscriptions.js@@ -674,6 +674,9 @@ function submitFormData(formData, submitButton, endpoint) {.then((data) => {if (data.status === "Success") {showSuccessMessage(data.message);+ if (data.logo_warning) {+ showErrorMessage(data.logo_warning);+ }fetchSubscriptions(null, null, "add");closeAddSubscription();} else {diff --git a/tests/bootstrap.php b/tests/bootstrap.phpnew file mode 100644index 0000000..dfb0f61--- /dev/null+++ b/tests/bootstrap.php@@ -0,0 +1,256 @@+<?php+/*+ Minimal test harness for Wallos.++ Wallos vendors its libraries instead of using Composer, so the tests follow+ the same principle: no external dependency, just PHP and the SQLite+ extension the application already requires.++ A test file registers cases with wallos_test() and asserts with the assert_*+ helpers. tests/run.php discovers and runs them.+*/++define('WALLOS_ROOT', dirname(__DIR__));+define('WALLOS_TEST_TMP', sys_get_temp_dir() . '/wallos-tests');++$GLOBALS['wallos_tests'] = [];+$GLOBALS['wallos_test_failures'] = [];+$GLOBALS['wallos_test_assertions'] = 0;+$GLOBALS['wallos_test_current'] = null;++/**+ * Registers one test case.+ *+ * @param string $name+ * @param callable $body+ */+function wallos_test($name, callable $body)+{+ $GLOBALS['wallos_tests'][] = ['name' => $name, 'body' => $body];+}++function wallos_test_fail($message)+{+ $GLOBALS['wallos_test_failures'][] = [+ 'test' => $GLOBALS['wallos_test_current'],+ 'message' => $message,+ ];+}++function assert_true($condition, $message)+{+ $GLOBALS['wallos_test_assertions']++;++ if (!$condition) {+ wallos_test_fail($message);+ }+}++function assert_same($expected, $actual, $message)+{+ $GLOBALS['wallos_test_assertions']++;++ if ($expected !== $actual) {+ wallos_test_fail(sprintf(+ '%s (expected %s, got %s)',+ $message,+ var_export($expected, true),+ var_export($actual, true)+ ));+ }+}++function assert_equals($expected, $actual, $message)+{+ $GLOBALS['wallos_test_assertions']++;++ if ($expected != $actual) {+ wallos_test_fail(sprintf(+ '%s (expected %s, got %s)',+ $message,+ var_export($expected, true),+ var_export($actual, true)+ ));+ }+}++function assert_contains($needle, $haystack, $message)+{+ $GLOBALS['wallos_test_assertions']++;++ if (strpos((string) $haystack, (string) $needle) === false) {+ wallos_test_fail($message . ' (missing: ' . $needle . ')');+ }+}++function assert_not_contains($needle, $haystack, $message)+{+ $GLOBALS['wallos_test_assertions']++;++ if (strpos((string) $haystack, (string) $needle) !== false) {+ wallos_test_fail($message . ' (unexpectedly present: ' . $needle . ')');+ }+}++/**+ * Builds the real application schema once per run by running the same+ * createdatabase.php and migration chain the container startup uses, then+ * hands out a fresh copy of it per test.+ *+ * The application resolves its database path relative to its own directory, so+ * the schema is built inside a throwaway copy of the source tree rather than in+ * the working copy.+ *+ * @return string Path to the freshly copied database.+ */+function wallos_test_database()+{+ static $template = null;++ if ($template === null) {+ $sandbox = WALLOS_TEST_TMP . '/sandbox';++ if (!is_dir($sandbox)) {+ mkdir($sandbox, 0700, true);+ foreach (['endpoints/cronjobs', 'includes', 'migrations', 'db'] as $directory) {+ mkdir($sandbox . '/' . $directory, 0700, true);+ }++ foreach (glob(WALLOS_ROOT . '/migrations/*.php') as $migration) {+ copy($migration, $sandbox . '/migrations/' . basename($migration));+ }+ copy(WALLOS_ROOT . '/endpoints/cronjobs/createdatabase.php', $sandbox . '/endpoints/cronjobs/createdatabase.php');+ copy(WALLOS_ROOT . '/includes/run_migrations.php', $sandbox . '/includes/run_migrations.php');+ }++ $databaseFile = $sandbox . '/db/wallos.db';++ if (!file_exists($databaseFile)) {+ // Both scripts print progress and resolve their paths from __DIR__,+ // which is why they run inside the sandbox copy.+ ob_start();+ require $sandbox . '/endpoints/cronjobs/createdatabase.php';+ $db = new SQLite3($databaseFile);+ $db->busyTimeout(5000);+ require $sandbox . '/includes/run_migrations.php';+ $db->close();+ ob_end_clean();+ }++ $template = $databaseFile;+ }++ $copy = WALLOS_TEST_TMP . '/case-' . uniqid('', true) . '.db';+ copy($template, $copy);++ return $copy;+}++/**+ * Opens a fresh database with the full application schema.+ *+ * @return SQLite3+ */+function wallos_test_open_database()+{+ $db = new SQLite3(wallos_test_database());+ $db->busyTimeout(5000);++ return $db;+}++/**+ * SQLite3 wrapper that counts statements, so tests can assert that a code path+ * does not issue one query per row.+ */+class WallosCountingDatabase extends SQLite3+{+ public $queryCount = 0;++ public function prepare($query): SQLite3Stmt|false+ {+ $this->queryCount++;++ return parent::prepare($query);+ }++ public function query($query): SQLite3Result|false+ {+ $this->queryCount++;++ return parent::query($query);+ }++ public function querySingle($query, $entireRow = false): mixed+ {+ $this->queryCount++;++ return parent::querySingle($query, $entireRow);+ }++ public function resetQueryCount()+ {+ $this->queryCount = 0;+ }+}++/**+ * @return WallosCountingDatabase+ */+function wallos_test_open_counting_database()+{+ $db = new WallosCountingDatabase(wallos_test_database());+ $db->busyTimeout(5000);++ return $db;+}++/**+ * Inserts a user together with the currency rows Wallos creates alongside it.+ *+ * @param SQLite3 $db+ * @param int $id+ * @param string $username+ */+function wallos_test_create_user($db, $id, $username)+{+ $stmt = $db->prepare("INSERT INTO user (id, username, email, password, main_currency) VALUES (:id, :username, :email, 'x', 1)");+ $stmt->bindValue(':id', $id, SQLITE3_INTEGER);+ $stmt->bindValue(':username', $username, SQLITE3_TEXT);+ $stmt->bindValue(':email', $username . '@example.com', SQLITE3_TEXT);+ $stmt->execute();++ // createdatabase.php seeds a default currency list; the fixture replaces it+ // so a test can reason about exactly two rows per user.+ $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :userId');+ $stmt->bindValue(':userId', $id, SQLITE3_INTEGER);+ $stmt->execute();++ foreach ([['EUR', 'Euro', 1.0], ['USD', 'US Dollar', 1.1]] as $index => $currency) {+ $stmt = $db->prepare('INSERT INTO currencies (id, name, symbol, code, rate, user_id) VALUES (:id, :name, :symbol, :code, :rate, :userId)');+ $stmt->bindValue(':id', wallos_test_currency_id($id, $index), SQLITE3_INTEGER);+ $stmt->bindValue(':name', $currency[1], SQLITE3_TEXT);+ $stmt->bindValue(':symbol', $currency[0] === 'EUR' ? "\u{20AC}" : '$', SQLITE3_TEXT);+ $stmt->bindValue(':code', $currency[0], SQLITE3_TEXT);+ $stmt->bindValue(':rate', $currency[2], SQLITE3_FLOAT);+ $stmt->bindValue(':userId', $id, SQLITE3_INTEGER);+ $stmt->execute();+ }++ $stmt = $db->prepare('UPDATE user SET main_currency = :currencyId WHERE id = :id');+ $stmt->bindValue(':currencyId', wallos_test_currency_id($id, 0), SQLITE3_INTEGER);+ $stmt->bindValue(':id', $id, SQLITE3_INTEGER);+ $stmt->execute();+}++/**+ * Fixture currency ids live above the seeded default list so they never clash.+ *+ * @param int $userId+ * @param int $index 0 = EUR (main currency), 1 = USD+ * @return int+ */+function wallos_test_currency_id($userId, $index)+{+ return 9000 + ($userId * 10) + $index;+}diff --git a/tests/cases/currency_rates_test.php b/tests/cases/currency_rates_test.phpnew file mode 100644index 0000000..c64ae22--- /dev/null+++ b/tests/cases/currency_rates_test.php@@ -0,0 +1,126 @@+<?php+/*+ Price conversion must not issue one query per converted row.+*/++require_once WALLOS_ROOT . '/includes/currency_rates.php';++/**+ * @param SQLite3 $db+ */+function currency_rates_fixture($db)+{+ wallos_test_create_user($db, 1, 'alice');+ wallos_test_create_user($db, 2, 'bob');++ // Alice: EUR at 1.0 (main), USD at 1.1. Bob: both at 2.5.+ $stmt = $db->prepare('UPDATE currencies SET rate = 2.5 WHERE user_id = 2');+ $stmt->execute();+}++wallos_test('converting many prices issues one query, not one per price', function () {+ $db = wallos_test_open_counting_database();+ currency_rates_fixture($db);++ $usd = wallos_test_currency_id(1, 1);+ $db->resetQueryCount();++ for ($i = 0; $i < 50; $i++) {+ wallos_convert_price(11.0, $usd, $db, 1);+ }++ assert_same(1, $db->queryCount,+ '50 conversions should need one rate query (got ' . $db->queryCount . ')');++ $db->close();+});++wallos_test('conversion produces the same result as a direct rate lookup', function () {+ $db = wallos_test_open_database();+ currency_rates_fixture($db);++ $usd = wallos_test_currency_id(1, 1);++ $stmt = $db->prepare('SELECT rate FROM currencies WHERE id = :id');+ $stmt->bindValue(':id', $usd, SQLITE3_INTEGER);+ $rate = (float) $stmt->execute()->fetchArray(SQLITE3_ASSOC)['rate'];++ assert_same(11.0 / $rate, wallos_convert_price(11.0, $usd, $db, 1),+ 'the converted value is unchanged');++ $db->close();+});++wallos_test('an unknown currency leaves the price untouched', function () {+ $db = wallos_test_open_database();+ currency_rates_fixture($db);++ assert_same(9.99, wallos_convert_price(9.99, 999999, $db, 1),+ 'a missing currency behaves like a lookup that found no row');++ $db->close();+});++wallos_test('a zero rate leaves the price untouched', function () {+ // The per-row lookups divided by whatever they found; a zero rate raises a+ // division error in PHP 8. Treating it as "no usable rate" is safer and+ // matches what the budget calculation already did.+ $db = wallos_test_open_database();+ currency_rates_fixture($db);++ $usd = wallos_test_currency_id(1, 1);+ $stmt = $db->prepare('UPDATE currencies SET rate = 0 WHERE id = :id');+ $stmt->bindValue(':id', $usd, SQLITE3_INTEGER);+ $stmt->execute();++ assert_same(9.99, wallos_convert_price(9.99, $usd, $db, 1),+ 'a zero rate leaves the price untouched instead of failing');++ $db->close();+});++wallos_test('rates are scoped to the requested user', function () {+ $db = wallos_test_open_database();+ currency_rates_fixture($db);++ $aliceUsd = wallos_test_currency_id(1, 1);+ $bobUsd = wallos_test_currency_id(2, 1);++ assert_same(11.0 / 1.1, wallos_convert_price(11.0, $aliceUsd, $db, 1), "alice's rate is used");+ assert_same(11.0 / 2.5, wallos_convert_price(11.0, $bobUsd, $db, 2), "bob's rate is used");++ // A currency belonging to another user is not visible in a scoped map.+ assert_same(11.0, wallos_convert_price(11.0, $bobUsd, $db, 1),+ "bob's currency is not resolved for alice");++ $db->close();+});++wallos_test('the unscoped map resolves any currency by id', function () {+ // Matches the lookups that resolved a currency by id alone.+ $db = wallos_test_open_database();+ currency_rates_fixture($db);++ assert_same(11.0 / 2.5, wallos_convert_price(11.0, wallos_test_currency_id(2, 1), $db),+ 'without a user, any currency id resolves');++ $db->close();+});++wallos_test('two connections do not share a rate map', function () {+ $first = wallos_test_open_database();+ currency_rates_fixture($first);++ $second = wallos_test_open_database();+ currency_rates_fixture($second);+ $stmt = $second->prepare('UPDATE currencies SET rate = 4.0 WHERE user_id = 1');+ $stmt->execute();++ $usd = wallos_test_currency_id(1, 1);++ assert_same(11.0 / 1.1, wallos_convert_price(11.0, $usd, $first, 1), 'the first connection keeps its rates');+ assert_same(11.0 / 4.0, wallos_convert_price(11.0, $usd, $second, 1), 'the second connection sees its own');++ $first->close();+ $second->close();+});diff --git a/tests/cases/currency_refresh_test.php b/tests/cases/currency_refresh_test.phpnew file mode 100644index 0000000..2fbb31f--- /dev/null+++ b/tests/cases/currency_refresh_test.php@@ -0,0 +1,110 @@+<?php+/*+ A rate refresh writes every rate of one user or none of them.++ Rates are only comparable when they share a conversion base. A refresh that+ stops halfway leaves some rows against the new base and some against the old+ one, which is worse than not refreshing at all: the numbers look plausible+ and are wrong.+*/++/**+ * @param SQLite3 $db+ * @param int $userId+ * @param string $code+ * @return float+ */+function refresh_rate($db, $userId, $code)+{+ $stmt = $db->prepare('SELECT rate FROM currencies WHERE user_id = :userId AND code = :code');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':code', $code, SQLITE3_TEXT);+ $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);++ return $row ? (float) $row['rate'] : 0.0;+}++wallos_test('an interrupted refresh leaves the previous rates', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $before = [refresh_rate($db, 1, 'EUR'), refresh_rate($db, 1, 'USD')];++ $db->exec('BEGIN');++ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId');+ $stmt->bindValue(':rate', 7.0, SQLITE3_TEXT);+ $stmt->bindValue(':code', 'EUR', SQLITE3_TEXT);+ $stmt->bindValue(':userId', 1, SQLITE3_INTEGER);+ $stmt->execute();+ $stmt->reset();++ // The provider response breaks off here: the second currency never lands.+ $db->exec('ROLLBACK');++ assert_same($before[0], refresh_rate($db, 1, 'EUR'), 'the first rate is restored');+ assert_same($before[1], refresh_rate($db, 1, 'USD'), 'the second rate is unchanged');++ $db->close();+});++wallos_test('a completed refresh commits every rate together', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $db->exec('BEGIN');++ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId');+ foreach (['EUR' => 1.0, 'USD' => 3.0] as $code => $rate) {+ $stmt->bindValue(':rate', $rate, SQLITE3_TEXT);+ $stmt->bindValue(':code', $code, SQLITE3_TEXT);+ $stmt->bindValue(':userId', 1, SQLITE3_INTEGER);+ $stmt->execute();+ $stmt->reset();+ }++ $db->exec('COMMIT');++ assert_same(1.0, refresh_rate($db, 1, 'EUR'), 'the first rate is stored');+ assert_same(3.0, refresh_rate($db, 1, 'USD'), 'the second rate is stored');++ $db->close();+});++wallos_test('one prepared statement serves the whole rate loop', function () {+ $db = wallos_test_open_counting_database();+ wallos_test_create_user($db, 1, 'alice');++ $db->resetQueryCount();++ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId');+ foreach (['EUR', 'USD', 'EUR', 'USD', 'EUR'] as $index => $code) {+ $stmt->bindValue(':rate', 1.0 + $index, SQLITE3_TEXT);+ $stmt->bindValue(':code', $code, SQLITE3_TEXT);+ $stmt->bindValue(':userId', 1, SQLITE3_INTEGER);+ $stmt->execute();+ $stmt->reset();+ }++ assert_same(1, $db->queryCount, 'five writes need one prepare (got ' . $db->queryCount . ')');++ $db->close();+});++wallos_test('both refresh paths wrap their writes in a transaction', function () {+ // Structural guard: a future refresh path that autocommits per currency+ // fails here rather than shipping a half-converted rate set.+ foreach (['endpoints/cronjobs/updateexchange.php', 'endpoints/currency/update_exchange.php'] as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);++ assert_contains("BEGIN", $source, $path . ' opens a transaction');+ assert_contains("COMMIT", $source, $path . ' commits it');+ assert_contains("ROLLBACK", $source, $path . ' rolls back on failure');++ // The prepare must sit outside the loop over the provider rates.+ $preparePosition = strpos($source, 'UPDATE currencies SET rate');+ $loopPosition = strpos($source, "foreach (\$apiData['rates']");+ assert_true($preparePosition !== false && $loopPosition !== false && $preparePosition < $loopPosition,+ $path . ' prepares the rate update once, before the loop');+ }+});diff --git a/tests/cases/currency_scope_test.php b/tests/cases/currency_scope_test.phpnew file mode 100644index 0000000..166ed5d--- /dev/null+++ b/tests/cases/currency_scope_test.php@@ -0,0 +1,97 @@+<?php+/*+ Refreshing one user's exchange rates must never touch another user's rows.++ Wallos stores one currency row per user, and each user's rate is derived from+ their own main currency. A rate update that matches on the currency code alone+ therefore overwrites other users' rates with a conversion base that is not+ theirs.+*/++/**+ * Seeds two users whose currencies overlap but whose main currency differs.+ *+ * @param SQLite3 $db+ */+function currency_scope_fixture($db)+{+ wallos_test_create_user($db, 1, 'alice');+ wallos_test_create_user($db, 2, 'bob');++ // Bob's rates are deliberately distinct so any cross-user write is visible.+ $stmt = $db->prepare('UPDATE currencies SET rate = 2.5 WHERE user_id = 2');+ $stmt->execute();+}++/**+ * @param SQLite3 $db+ * @param int $userId+ * @param string $code+ * @return float+ */+function currency_scope_rate($db, $userId, $code)+{+ $stmt = $db->prepare('SELECT rate FROM currencies WHERE user_id = :userId AND code = :code');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':code', $code, SQLITE3_TEXT);+ $result = $stmt->execute();+ $row = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;++ return $row ? (float) $row['rate'] : 0.0;+}++wallos_test('rate updates are scoped to one user', function () {+ $db = wallos_test_open_database();+ currency_scope_fixture($db);++ $before = currency_scope_rate($db, 2, 'USD');++ // The update statement used by the refresh path.+ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId');+ $stmt->bindValue(':rate', 9.99, SQLITE3_FLOAT);+ $stmt->bindValue(':code', 'USD', SQLITE3_TEXT);+ $stmt->bindValue(':userId', 1, SQLITE3_INTEGER);+ $stmt->execute();++ assert_same(9.99, currency_scope_rate($db, 1, 'USD'), "alice's rate is updated");+ assert_same($before, currency_scope_rate($db, 2, 'USD'), "bob's rate is untouched");++ $db->close();+});++wallos_test('an unscoped rate update would corrupt other users', function () {+ // Guards the regression itself: if this ever stops being true, the scoped+ // statement above has lost its purpose.+ $db = wallos_test_open_database();+ currency_scope_fixture($db);++ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code');+ $stmt->bindValue(':rate', 9.99, SQLITE3_FLOAT);+ $stmt->bindValue(':code', 'USD', SQLITE3_TEXT);+ $stmt->execute();++ assert_same(9.99, currency_scope_rate($db, 2, 'USD'), 'unscoped update reaches every user');++ $db->close();+});++wallos_test('every currency rate update in the code base is user scoped', function () {+ // The regression guard: any future rate write that forgets the user filter+ // fails here rather than silently corrupting other accounts in production.+ $paths = [+ 'endpoints/cronjobs/updateexchange.php',+ 'endpoints/currency/update_exchange.php',+ ];++ foreach ($paths as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);++ preg_match_all('/UPDATE\s+currencies\s+SET\s+rate[^"\']*/i', $source, $matches);+ assert_true($matches[0] !== [], $path . ' still contains a rate update');++ foreach ($matches[0] as $statement) {+ assert_contains('user_id', $statement,+ $path . ' updates rates without scoping them to a user: ' . trim($statement));+ }+ }+});diff --git a/tests/cases/subscription_index_test.php b/tests/cases/subscription_index_test.phpnew file mode 100644index 0000000..03958dd--- /dev/null+++ b/tests/cases/subscription_index_test.php@@ -0,0 +1,72 @@+<?php+/*+ The subscription queries Wallos runs on every page must use an index rather+ than scanning the table.+*/++/**+ * Returns the query plan of a statement as one string.+ *+ * @param SQLite3 $db+ * @param string $sql+ * @return string+ */+function index_plan($db, $sql)+{+ $plan = '';+ $result = $db->query('EXPLAIN QUERY PLAN ' . $sql);+ while ($result && $row = $result->fetchArray(SQLITE3_ASSOC)) {+ $plan .= $row['detail'] . ' ';+ }++ return trim($plan);+}++wallos_test('the migration creates the subscription indexes', function () {+ $db = wallos_test_open_database();++ $indexes = [];+ $result = $db->query("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='subscriptions'");+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $indexes[] = $row['name'];+ }++ assert_true(in_array('idx_subscriptions_user_inactive_next_payment', $indexes, true),+ 'the list/calendar index exists');+ assert_true(in_array('idx_subscriptions_user_notify_inactive', $indexes, true),+ 'the notification index exists');++ $db->close();+});++wallos_test('the queries Wallos runs use an index instead of scanning', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $cases = [+ 'subscription list' => "SELECT * FROM subscriptions WHERE user_id = 1",+ 'active subscriptions' => "SELECT * FROM subscriptions WHERE user_id = 1 AND inactive = 0",+ 'notification cron' => "SELECT * FROM subscriptions WHERE user_id = 1 AND notify = 1 AND inactive = 0",+ 'calendar range' => "SELECT * FROM subscriptions WHERE user_id = 1 AND inactive = 0 AND next_payment BETWEEN '2026-08-01' AND '2026-08-31'",+ ];++ foreach ($cases as $label => $sql) {+ $plan = index_plan($db, $sql);++ assert_contains('USING INDEX', $plan, $label . ' uses an index (plan: ' . $plan . ')');+ assert_not_contains('SCAN subscriptions', $plan, $label . ' does not scan the table');+ }++ $db->close();+});++wallos_test('the migration can run twice', function () {+ $db = wallos_test_open_database();++ require WALLOS_ROOT . '/migrations/000055.php';++ assert_true((bool) $db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_subscriptions_user_inactive_next_payment'"),+ 'the index still exists after a second run');++ $db->close();+});diff --git a/tests/run.php b/tests/run.phpnew file mode 100644index 0000000..7824c29--- /dev/null+++ b/tests/run.php@@ -0,0 +1,88 @@+<?php+/*+ Test runner.++ php tests/run.php run every case+ php tests/run.php currency run cases whose file or name matches "currency"++ Exits non-zero when a case fails, so it can be used in CI.+*/++require_once __DIR__ . '/bootstrap.php';++$filter = $argv[1] ?? null;++if (is_dir(WALLOS_TEST_TMP)) {+ foreach (glob(WALLOS_TEST_TMP . '/case-*.db') as $leftover) {+ @unlink($leftover);+ }+} else {+ mkdir(WALLOS_TEST_TMP, 0700, true);+}++$files = glob(__DIR__ . '/cases/*_test.php');+sort($files);++foreach ($files as $file) {+ if ($filter !== null && stripos(basename($file), $filter) === false) {+ // Keep the file when one of its case names matches instead.+ $contents = file_get_contents($file);+ if (stripos($contents, $filter) === false) {+ continue;+ }+ }++ require_once $file;+}++$started = microtime(true);+$passed = 0;+$failedTests = [];++foreach ($GLOBALS['wallos_tests'] as $test) {+ if ($filter !== null+ && stripos($test['name'], $filter) === false+ && stripos(basename((new ReflectionFunction($test['body']))->getFileName()), $filter) === false) {+ continue;+ }++ $GLOBALS['wallos_test_current'] = $test['name'];+ $before = count($GLOBALS['wallos_test_failures']);++ try {+ $test['body']();+ } catch (Throwable $error) {+ wallos_test_fail('threw ' . get_class($error) . ': ' . $error->getMessage()+ . ' @ ' . basename($error->getFile()) . ':' . $error->getLine());+ }++ $newFailures = array_slice($GLOBALS['wallos_test_failures'], $before);++ if ($newFailures === []) {+ $passed++;+ echo "\033[32m ok\033[0m " . $test['name'] . "\n";++ continue;+ }++ $failedTests[] = $test['name'];+ echo "\033[31mFAIL\033[0m " . $test['name'] . "\n";+ foreach ($newFailures as $failure) {+ echo " " . $failure['message'] . "\n";+ }+}++foreach (glob(WALLOS_TEST_TMP . '/case-*.db') as $leftover) {+ @unlink($leftover);+}++$duration = round((microtime(true) - $started) * 1000);+$failures = count($GLOBALS['wallos_test_failures']);++echo "\n";+echo $failures === 0+ ? sprintf("\033[32m%d tests passed\033[0m (%d assertions, %dms)\n", $passed, $GLOBALS['wallos_test_assertions'], $duration)+ : sprintf("\033[31m%d failing assertion(s)\033[0m in %d test(s), %d passed (%dms)\n",+ $failures, count($failedTests), $passed, $duration);++exit($failures === 0 ? 0 : 1);