Skip to content

Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.

feat: add payment-period budgeting

Uniskela4b8fbe578c8a
diff --git a/api/subscriptions/get_period_budget.php b/api/subscriptions/get_period_budget.php
new file mode 100644
index 0000000..1afa9d3
--- /dev/null
+++ b/api/subscriptions/get_period_budget.php
@@ -0,0 +1,175 @@
+<?php
+/*
+This API Endpoint accepts both POST and GET requests.
+It receives:
+- api_key (or apiKey): the API key of the user.
+- reference_date (optional): date in YYYY-MM-DD format to evaluate the active budget period (defaults to today).
+
+It returns:
+- success: whether the request was successful (boolean).
+- title: endpoint title (string).
+- period_budget: configured period budget amount (float).
+- amount_needed_this_period: projected required amount from reference_date to period_end (float).
+- amount_needed_full_period: projected required amount from period_start to period_end (float).
+- amount_remaining_this_period: remaining amount before hitting budget (float).
+- amount_over_budget: amount above budget, if any (float).
+- is_over_budget: whether projected spend exceeds period budget (boolean).
+- budget_period_type: weekly, fortnightly, monthly.
+- budget_period_anchor_date: anchor date in YYYY-MM-DD.
+- period_start: active period start date in YYYY-MM-DD.
+- period_end: active period end date in YYYY-MM-DD.
+- period_label: human-readable active period label.
+- currency_code: main currency code.
+- currency_symbol: main currency symbol.
+- reference_date: evaluated date in YYYY-MM-DD.
+- notes: warnings or additional information (array).
+*/
+
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/budget_period_calculations.php';
+
+header('Content-Type: application/json; charset=UTF-8');
+
+if ($_SERVER["REQUEST_METHOD"] !== "POST" && $_SERVER["REQUEST_METHOD"] !== "GET") {
+ echo json_encode([
+ "success" => false,
+ "title" => "Invalid request method"
+ ]);
+ exit;
+}
+
+$rawBody = file_get_contents('php://input');
+$jsonData = json_decode($rawBody, true);
+$payload = is_array($jsonData) ? $jsonData : [];
+
+$apiKey = $_REQUEST['api_key']
+ ?? $_REQUEST['apiKey']
+ ?? $payload['api_key']
+ ?? $payload['apiKey']
+ ?? null;
+if (!$apiKey) {
+ echo json_encode([
+ "success" => false,
+ "title" => "Missing parameters"
+ ]);
+ exit;
+}
+
+$referenceDateRaw = $_REQUEST['reference_date']
+ ?? $payload['reference_date']
+ ?? null;
+if ($referenceDateRaw !== null && $referenceDateRaw !== '') {
+ if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $referenceDateRaw)) {
+ echo json_encode([
+ "success" => false,
+ "title" => "Invalid parameter",
+ "notes" => ["reference_date must use YYYY-MM-DD format."]
+ ]);
+ exit;
+ }
+
+ $referenceDate = DateTime::createFromFormat('Y-m-d', $referenceDateRaw);
+ if ($referenceDate === false || $referenceDate->format('Y-m-d') !== $referenceDateRaw) {
+ echo json_encode([
+ "success" => false,
+ "title" => "Invalid parameter",
+ "notes" => ["reference_date must be a valid calendar date."]
+ ]);
+ exit;
+ }
+} else {
+ $referenceDate = new DateTime('now');
+}
+
+$sql = "SELECT id, main_currency, period_budget, budget_period_type, budget_period_anchor_date FROM user WHERE api_key = :apiKey";
+$stmt = $db->prepare($sql);
+$stmt->bindValue(':apiKey', $apiKey, SQLITE3_TEXT);
+$result = $stmt->execute();
+$user = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
+
+if (!$user) {
+ echo json_encode([
+ "success" => false,
+ "title" => "Invalid API key"
+ ]);
+ exit;
+}
+
+$userId = (int) $user['id'];
+$periodBudget = max(0, (float) ($user['period_budget'] ?? 0));
+$periodType = sanitizeBudgetPeriodType($user['budget_period_type'] ?? 'monthly');
+$anchorDate = sanitizeBudgetAnchorDate($user['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());
+
+$activePeriod = getActiveBudgetPeriod($referenceDate, $periodType, $anchorDate);
+
+$subsSql = "SELECT * FROM subscriptions WHERE user_id = :userId AND inactive = 0";
+$subsStmt = $db->prepare($subsSql);
+$subsStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+$subsResult = $subsStmt->execute();
+$subscriptions = [];
+while ($subsResult && ($subscription = $subsResult->fetchArray(SQLITE3_ASSOC))) {
+ $subscriptions[] = $subscription;
+}
+
+$amountNeededFromReference = computeAmountNeededInPeriod(
+ $subscriptions,
+ $referenceDate,
+ $activePeriod['end'],
+ $db,
+ $userId
+);
+
+$amountNeededFullPeriod = computeAmountNeededInPeriod(
+ $subscriptions,
+ $activePeriod['start'],
+ $activePeriod['end'],
+ $db,
+ $userId
+);
+
+$amountRemaining = max(0, $periodBudget - $amountNeededFromReference);
+$amountOverBudget = max(0, $amountNeededFromReference - $periodBudget);
+$isOverBudget = $periodBudget > 0 && $amountNeededFromReference > $periodBudget;
+
+$currencyCode = null;
+$currencySymbol = null;
+$currencySql = "SELECT code, symbol FROM currencies WHERE id = :currencyId AND user_id = :userId LIMIT 1";
+$currencyStmt = $db->prepare($currencySql);
+$currencyStmt->bindValue(':currencyId', (int) $user['main_currency'], SQLITE3_INTEGER);
+$currencyStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+$currencyResult = $currencyStmt->execute();
+$currency = $currencyResult ? $currencyResult->fetchArray(SQLITE3_ASSOC) : false;
+
+if ($currency) {
+ $currencyCode = $currency['code'];
+ $currencySymbol = $currency['symbol'];
+}
+
+$notes = [];
+if ($periodBudget <= 0) {
+ $notes[] = "Period budget is set to 0.";
+}
+
+echo json_encode([
+ "success" => true,
+ "title" => "period_budget",
+ "period_budget" => round($periodBudget, 2),
+ "amount_needed_this_period" => round($amountNeededFromReference, 2),
+ "amount_needed_full_period" => round($amountNeededFullPeriod, 2),
+ "amount_remaining_this_period" => round($amountRemaining, 2),
+ "amount_over_budget" => round($amountOverBudget, 2),
+ "is_over_budget" => $isOverBudget,
+ "budget_period_type" => $periodType,
+ "budget_period_anchor_date" => $anchorDate,
+ "period_start" => $activePeriod['start']->format('Y-m-d'),
+ "period_end" => $activePeriod['end']->format('Y-m-d'),
+ "period_label" => $activePeriod['label'],
+ "currency_code" => $currencyCode,
+ "currency_symbol" => $currencySymbol,
+ "reference_date" => $referenceDate->format('Y-m-d'),
+ "notes" => $notes
+], JSON_UNESCAPED_UNICODE);
+
+$db->close();
+
+?>
diff --git a/api/users/set_budget.php b/api/users/set_budget.php
new file mode 100644
index 0000000..b2ac88b
--- /dev/null
+++ b/api/users/set_budget.php
@@ -0,0 +1,142 @@
+<?php
+/*
+This API Endpoint accepts POST requests only.
+It receives:
+- api_key (or apiKey): the API key of the user.
+- monthly_budget or budget (optional): monthly budget to store in user.budget.
+- period_budget (optional): period budget to store in user.period_budget.
+- budget_period_type (optional): weekly, fortnightly, monthly.
+- budget_period_anchor_date (optional): YYYY-MM-DD.
+
+At least one budget-related field is required.
+*/
+
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/budget_period_calculations.php';
+
+header('Content-Type: application/json; charset=UTF-8');
+
+if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Invalid request method',
+ 'message' => 'Only POST requests are allowed.'
+ ]);
+ exit;
+}
+
+$rawBody = file_get_contents('php://input');
+$jsonData = json_decode($rawBody, true);
+$payload = is_array($jsonData) ? $jsonData : $_POST;
+
+$apiKey = $payload['api_key'] ?? $payload['apiKey'] ?? $_POST['api_key'] ?? $_POST['apiKey'] ?? null;
+
+if (!$apiKey) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Missing API key',
+ 'message' => 'API key is required.'
+ ]);
+ exit;
+}
+
+$sql = "SELECT id FROM user WHERE api_key = :apiKey";
+$stmt = $db->prepare($sql);
+$stmt->bindValue(':apiKey', $apiKey, SQLITE3_TEXT);
+$result = $stmt->execute();
+$user = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
+
+if (!$user) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Unauthorized',
+ 'message' => 'Invalid API key.'
+ ]);
+ exit;
+}
+
+$hasMonthlyBudget = array_key_exists('monthly_budget', $payload) || array_key_exists('budget', $payload);
+$hasPeriodBudget = array_key_exists('period_budget', $payload);
+$hasPeriodMeta = array_key_exists('budget_period_type', $payload) || array_key_exists('budget_period_anchor_date', $payload);
+
+if (!$hasMonthlyBudget && !$hasPeriodBudget && !$hasPeriodMeta) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Missing parameters',
+ 'message' => 'Provide at least one of monthly_budget/budget/period_budget/budget_period_type/budget_period_anchor_date.'
+ ]);
+ exit;
+}
+
+$sets = [];
+$binds = [];
+
+if ($hasMonthlyBudget) {
+ $monthlyBudgetRaw = $payload['monthly_budget'] ?? $payload['budget'];
+ if (!is_numeric($monthlyBudgetRaw)) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Invalid parameter',
+ 'message' => 'monthly_budget (or budget) must be numeric.'
+ ]);
+ exit;
+ }
+
+ $monthlyBudget = max(0, (float) $monthlyBudgetRaw);
+ $sets[] = 'budget = :monthlyBudget';
+ $binds[':monthlyBudget'] = ['value' => $monthlyBudget, 'type' => SQLITE3_FLOAT];
+}
+
+if ($hasPeriodBudget || $hasPeriodMeta) {
+ if ($hasPeriodBudget) {
+ $periodBudgetRaw = $payload['period_budget'];
+ if (!is_numeric($periodBudgetRaw)) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Invalid parameter',
+ 'message' => 'period_budget must be numeric.'
+ ]);
+ exit;
+ }
+
+ $periodBudget = max(0, (float) $periodBudgetRaw);
+ $sets[] = 'period_budget = :periodBudget';
+ $binds[':periodBudget'] = ['value' => $periodBudget, 'type' => SQLITE3_FLOAT];
+ }
+
+ $periodType = sanitizeBudgetPeriodType($payload['budget_period_type'] ?? 'monthly');
+ $anchorDate = sanitizeBudgetAnchorDate($payload['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());
+
+ $sets[] = 'budget_period_type = :periodType';
+ $binds[':periodType'] = ['value' => $periodType, 'type' => SQLITE3_TEXT];
+ $sets[] = 'budget_period_anchor_date = :anchorDate';
+ $binds[':anchorDate'] = ['value' => $anchorDate, 'type' => SQLITE3_TEXT];
+}
+
+$updateSql = "UPDATE user SET " . implode(', ', $sets) . " WHERE id = :userId";
+$updateStmt = $db->prepare($updateSql);
+
+foreach ($binds as $key => $bind) {
+ $updateStmt->bindValue($key, $bind['value'], $bind['type']);
+}
+
+$updateStmt->bindValue(':userId', (int) $user['id'], SQLITE3_INTEGER);
+$updateResult = $updateStmt->execute();
+
+if ($updateResult) {
+ echo json_encode([
+ 'success' => true,
+ 'title' => 'Updated',
+ 'message' => 'Budget settings updated successfully.'
+ ]);
+} else {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Database error',
+ 'message' => 'Failed to update budget settings.'
+ ]);
+}
+
+$db->close();
+
+?>
diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.php
index f4a9d2f..c7aa186 100644
--- a/endpoints/cronjobs/sendnotifications.php
+++ b/endpoints/cronjobs/sendnotifications.php
@@ -12,6 +12,7 @@ require __DIR__ . '/../../libs/PHPMailer/SMTP.php';
require __DIR__ . '/../../libs/PHPMailer/Exception.php';
require __DIR__ . '/../../includes/currency_formatter.php';
+require __DIR__ . '/../../includes/budget_period_calculations.php';
require 'settimezone.php';
@@ -26,6 +27,8 @@ if (php_sapi_name() == 'cli') {
$query = "SELECT id, username FROM user";
$stmt = $db->prepare($query);
$usersToNotify = $stmt->execute();
+$periodSummaryColumnCheck = $db->query("SELECT * FROM pragma_table_info('notification_settings') WHERE name='period_summary_at_period_start'");
+$hasPeriodSummaryColumn = $periodSummaryColumnCheck && $periodSummaryColumnCheck->fetchArray(SQLITE3_ASSOC);
function getDaysText($days)
{
@@ -50,6 +53,34 @@ function formatPrice($price, $currencyCode, $currencySymbol)
return $formattedPrice;
}
+function buildNotificationMessage($name, $perUser, $periodSummaryLine, $includePeriodSummary)
+{
+ if (empty($perUser) && !$includePeriodSummary) {
+ return "";
+ }
+
+ if (empty($perUser)) {
+ return ($name ? $name . ", " : "") . $periodSummaryLine . "\n";
+ }
+
+ if ($name) {
+ $message = $name . ", the following subscriptions are up for renewal:\n";
+ } else {
+ $message = "The following subscriptions are up for renewal:\n";
+ }
+
+ foreach ($perUser as $subscription) {
+ $dayText = getDaysText($subscription['days']);
+ $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ }
+
+ if ($includePeriodSummary) {
+ $message .= "\n" . $periodSummaryLine . "\n";
+ }
+
+ return $message;
+}
+
while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$userId = $userToNotify['id'];
if (php_sapi_name() !== 'cli') {
@@ -57,6 +88,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
}
$days = 1;
+ $periodSummaryAtPeriodStart = 0;
$emailNotificationsEnabled = false;
$gotifyNotificationsEnabled = false;
$telegramNotificationsEnabled = false;
@@ -69,13 +101,18 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$serverchanNotificationsEnabled = false;
// Get notification settings (how many days before the subscription ends should the notification be sent)
- $query = "SELECT days FROM notification_settings WHERE user_id = :userId";
+ $query = $hasPeriodSummaryColumn
+ ? "SELECT days, period_summary_at_period_start FROM notification_settings WHERE user_id = :userId"
+ : "SELECT days FROM notification_settings WHERE user_id = :userId";
$stmt = $db->prepare($query);
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$days = $row['days'];
+ if ($hasPeriodSummaryColumn) {
+ $periodSummaryAtPeriodStart = (int) ($row['period_summary_at_period_start'] ?? 0);
+ }
}
// Check if email notifications are enabled and get the settings
@@ -253,6 +290,41 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$categories[$rowCategory['id']] = $rowCategory;
}
+ $currentDate = new DateTime('now');
+
+ $query = "SELECT main_currency, period_budget, budget_period_type, budget_period_anchor_date FROM user WHERE id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $userBudgetConfig = $result->fetchArray(SQLITE3_ASSOC);
+
+ $mainCurrencyId = $userBudgetConfig['main_currency'];
+ $budgetPeriodType = sanitizeBudgetPeriodType($userBudgetConfig['budget_period_type'] ?? 'monthly');
+ $budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userBudgetConfig['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());
+ $activeBudgetPeriod = getActiveBudgetPeriod($currentDate, $budgetPeriodType, $budgetPeriodAnchorDate);
+ $isPeriodStart = $activeBudgetPeriod['start']->format('Y-m-d') === $currentDate->format('Y-m-d');
+
+ $query = "SELECT price, currency_id, next_payment, cycle, frequency, inactive, auto_renew FROM subscriptions WHERE user_id = :userId AND inactive = 0";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $periodSubscriptions = [];
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $periodSubscriptions[] = $row;
+ }
+
+ $amountNeededThisPeriod = computeAmountNeededInPeriod($periodSubscriptions, $currentDate, $activeBudgetPeriod['end'], $db, $userId);
+ $mainCurrencyCode = $currencies[$mainCurrencyId]['code'] ?? 'USD';
+ $mainCurrencySymbol = $currencies[$mainCurrencyId]['symbol'] ?? '$';
+ $periodSummaryLine = translate('amount_for_pay_period', $i18n) . ": " . formatPrice($amountNeededThisPeriod, $mainCurrencyCode, $mainCurrencySymbol);
+
+ if (!empty($userBudgetConfig['period_budget']) && $userBudgetConfig['period_budget'] > 0) {
+ $remaining = max(0, $userBudgetConfig['period_budget'] - $amountNeededThisPeriod);
+ $periodSummaryLine .= " | " . translate('remaining', $i18n) . ": " . formatPrice($remaining, $mainCurrencyCode, $mainCurrencySymbol);
+ }
+
+ $sendPeriodStartSummaryOnly = $periodSummaryAtPeriodStart === 1 && $isPeriodStart;
+
$query = "SELECT * FROM subscriptions WHERE user_id = :user_id AND notify = :notify AND inactive = :inactive ORDER BY payer_user_id ASC";
$stmt = $db->prepare($query);
$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
@@ -262,7 +334,6 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$notify = [];
$i = 0;
- $currentDate = new DateTime('now');
while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {
if ($rowSubscription['notify_days_before'] !== -1) {
$daysToCompare = $rowSubscription['notify_days_before'];
@@ -296,6 +367,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
}
}
+ if (empty($notify) && $sendPeriodStartSummaryOnly) {
+ $defaultPayerUserId = array_key_first($household);
+ if ($defaultPayerUserId !== null) {
+ $notify[$defaultPayerUserId] = [];
+ }
+ }
+
if (!empty($notify)) {
// Email notifications if enabled
@@ -305,79 +383,78 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
if (!validate_smtp_host($email['smtpAddress'], (int) $email['smtpPort'], $db)) {
echo "SSRF attempt detected for SMTP host. Email notifications not sent.<br />";
} else {
- $stmt = $db->prepare('SELECT * FROM user WHERE id = :user_id');
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $defaultUser = $result->fetchArray(SQLITE3_ASSOC);
- $defaultEmail = $defaultUser['email'];
- $defaultName = $defaultUser['username'];
- foreach ($notify as $userId => $perUser) {
- $message = "The following subscriptions are up for renewal:\n";
+ $stmt = $db->prepare('SELECT * FROM user WHERE id = :user_id');
+ $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $defaultUser = $result->fetchArray(SQLITE3_ASSOC);
+ $defaultEmail = $defaultUser['email'];
+ $defaultName = $defaultUser['username'];
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
- }
+ foreach ($notify as $userId => $perUser) {
+ $message = buildNotificationMessage("", $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
+ }
- $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");
+ $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");
- $mail = new PHPMailer(true);
- $mail->CharSet = "UTF-8";
- $mail->isSMTP();
+ $mail = new PHPMailer(true);
+ $mail->CharSet = "UTF-8";
+ $mail->isSMTP();
- $mail->Host = $email['smtpAddress'];
- $mail->SMTPAuth = $smtpAuth;
+ $mail->Host = $email['smtpAddress'];
+ $mail->SMTPAuth = $smtpAuth;
- if ($smtpAuth) {
- $mail->Username = $email['smtpUsername'];
- $mail->Password = $email['smtpPassword'];
- }
+ if ($smtpAuth) {
+ $mail->Username = $email['smtpUsername'];
+ $mail->Password = $email['smtpPassword'];
+ }
- if ($email['encryption'] != "none") {
- $mail->SMTPSecure = $email['encryption'];
- } else {
- $mail->SMTPSecure = false;
- $mail->SMTPAutoTLS = false;
- }
+ if ($email['encryption'] != "none") {
+ $mail->SMTPSecure = $email['encryption'];
+ } else {
+ $mail->SMTPSecure = false;
+ $mail->SMTPAutoTLS = false;
+ }
- $mail->Port = $email['smtpPort'];
+ $mail->Port = $email['smtpPort'];
- $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $user = $result->fetchArray(SQLITE3_ASSOC);
+ $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $user = $result->fetchArray(SQLITE3_ASSOC);
- $emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail;
- $name = !empty($user['name']) ? $user['name'] : $defaultName;
+ $emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail;
+ $name = !empty($user['name']) ? $user['name'] : $defaultName;
- $mail->setFrom($email['fromEmail'], 'Wallos App');
- $mail->addAddress($emailaddress, $name);
+ $mail->setFrom($email['fromEmail'], 'Wallos App');
+ $mail->addAddress($emailaddress, $name);
- if (!empty($email['otherEmails'])) {
- $list = explode(';', $email['otherEmails']);
+ if (!empty($email['otherEmails'])) {
+ $list = explode(';', $email['otherEmails']);
- // Avoid duplicate emails
- $list = array_unique($list);
- $list = array_filter($list, function ($value) use ($emailaddress) {
- return $value !== $emailaddress;
- });
+ // Avoid duplicate emails
+ $list = array_unique($list);
+ $list = array_filter($list, function ($value) use ($emailaddress) {
+ return $value !== $emailaddress;
+ });
- foreach ($list as $value) {
- $mail->addCC(trim($value));
- }
+ foreach ($list as $value) {
+ $mail->addCC(trim($value));
}
+ }
- $mail->Subject = 'Wallos Notification';
- $mail->Body = $message;
+ $mail->Subject = 'Wallos Notification';
+ $mail->Body = $message;
- if ($mail->send()) {
- echo "Email Notifications sent<br />";
- } else {
- echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";
- }
+ if ($mail->send()) {
+ echo "Email Notifications sent<br />";
+ } else {
+ echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";
}
}
+ }
}
// Discord notifications if enabled
@@ -395,15 +472,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$title = translate('wallos_notification', $i18n);
- if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $message = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
$postfields = [
@@ -455,15 +527,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$result = $stmt->execute();
$user = $result->fetchArray(SQLITE3_ASSOC);
- if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $message = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
$data = array(
@@ -514,14 +581,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$user = $result->fetchArray(SQLITE3_ASSOC);
if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
+ $name = $user['name'];
} else {
- $message = "The following subscriptions are up for renewal:\n";
+ $name = "";
}
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
$data = array(
@@ -566,16 +632,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$user = $result->fetchArray(SQLITE3_ASSOC);
// Build Message Content
- $messageContent = "";
- if ($user['name']) {
- $messageContent = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $messageContent = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $messageContent .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($messageContent === "") {
+ continue;
}
// Prepare PushPlus Data
@@ -632,18 +692,11 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$user = $result->fetchArray(SQLITE3_ASSOC);
// Build Message Content
- $messageContent = "";
- if ($user['name']) {
- $messageContent = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $messageContent = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $messageContent .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($messageContent === "") {
+ continue;
}
-
// Prepare Mattermost Data
$webhook_url = $mattermost['webhook_url'];
$data = array(
@@ -697,14 +750,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$user = $result->fetchArray(SQLITE3_ASSOC);
if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
+ $name = $user['name'];
} else {
- $message = "The following subscriptions are up for renewal:\n";
+ $name = "";
}
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
$ch = curl_init();
@@ -742,15 +794,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$result = $stmt->execute();
$user = $result->fetchArray(SQLITE3_ASSOC);
- if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $message = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
$headers = json_decode($ntfy["headers"], true);
@@ -873,15 +920,10 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$user = $result->fetchArray(SQLITE3_ASSOC);
$title = 'Wallos Notification';
- if ($user['name']) {
- $message = $user['name'] . ", the following subscriptions are up for renewal:\n";
- } else {
- $message = "The following subscriptions are up for renewal:\n";
- }
-
- foreach ($perUser as $subscription) {
- $dayText = getDaysText($subscription['days']);
- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";
+ $name = $user['name'] ?? "";
+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);
+ if ($message === "") {
+ continue;
}
// Build Serverchan request
diff --git a/endpoints/notifications/savenotificationsettings.php b/endpoints/notifications/savenotificationsettings.php
index b5aa025..bd0d63e 100644
--- a/endpoints/notifications/savenotificationsettings.php
+++ b/endpoints/notifications/savenotificationsettings.php
@@ -14,6 +14,14 @@ if (!isset($data["days"]) || $data['days'] == "") {
echo json_encode($response);
} else {
$days = $data["days"];
+ $periodSummaryAtPeriodStart = isset($data["period_summary_at_period_start"]) ? (int) $data["period_summary_at_period_start"] : 0;
+
+ $hasPeriodSummaryColumn = false;
+ $columnResult = $db->query("SELECT * FROM pragma_table_info('notification_settings') WHERE name='period_summary_at_period_start'");
+ if ($columnResult && $columnResult->fetchArray(SQLITE3_ASSOC)) {
+ $hasPeriodSummaryColumn = true;
+ }
+
$query = "SELECT COUNT(*) FROM notification_settings WHERE user_id = :userId";
$stmt = $db->prepare($query);
$stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
@@ -29,14 +37,28 @@ if (!isset($data["days"]) || $data['days'] == "") {
$row = $result->fetchArray();
$count = $row[0];
if ($count == 0) {
- $query = "INSERT INTO notification_settings (days, user_id)
- VALUES (:days, :userId)";
+ if ($hasPeriodSummaryColumn) {
+ $query = "INSERT INTO notification_settings (days, period_summary_at_period_start, user_id)
+ VALUES (:days, :periodSummaryAtPeriodStart, :userId)";
+ } else {
+ $query = "INSERT INTO notification_settings (days, user_id)
+ VALUES (:days, :userId)";
+ }
} else {
- $query = "UPDATE notification_settings SET days = :days WHERE user_id = :userId";
+ if ($hasPeriodSummaryColumn) {
+ $query = "UPDATE notification_settings
+ SET days = :days, period_summary_at_period_start = :periodSummaryAtPeriodStart
+ WHERE user_id = :userId";
+ } else {
+ $query = "UPDATE notification_settings SET days = :days WHERE user_id = :userId";
+ }
}
$stmt = $db->prepare($query);
$stmt->bindValue(':days', $days, SQLITE3_INTEGER);
+ if ($hasPeriodSummaryColumn) {
+ $stmt->bindValue(':periodSummaryAtPeriodStart', $periodSummaryAtPeriodStart, SQLITE3_INTEGER);
+ }
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
if ($stmt->execute()) {
@@ -53,4 +75,4 @@ if (!isset($data["days"]) || $data['days'] == "") {
echo json_encode($response);
}
}
-}
\ No newline at end of file
+}
diff --git a/endpoints/user/budget.php b/endpoints/user/budget.php
index 0ad07f9..7d98c53 100644
--- a/endpoints/user/budget.php
+++ b/endpoints/user/budget.php
@@ -3,16 +3,51 @@
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
require_once '../../includes/validate_endpoint.php';
+require_once '../../includes/budget_period_calculations.php';
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
-$budget = $data["budget"];
+$sets = [];
+$binds = [];
-$sql = "UPDATE user SET budget = :budget WHERE id = :userId";
+if (isset($data['budget']) && !isset($data['monthly_budget'])) {
+ $legacyBudget = max(0, (float) $data['budget']);
+ $sets[] = 'budget = :legacyBudget';
+ $binds[':legacyBudget'] = ['value' => $legacyBudget, 'type' => SQLITE3_FLOAT];
+}
+
+if (isset($data['monthly_budget'])) {
+ $monthlyBudget = max(0, (float) $data['monthly_budget']);
+ $sets[] = 'budget = :monthlyBudget';
+ $binds[':monthlyBudget'] = ['value' => $monthlyBudget, 'type' => SQLITE3_FLOAT];
+}
+
+if (isset($data['period_budget'])) {
+ $periodBudget = max(0, (float) $data['period_budget']);
+ $sets[] = 'period_budget = :periodBudget';
+ $binds[':periodBudget'] = ['value' => $periodBudget, 'type' => SQLITE3_FLOAT];
+
+ $periodType = sanitizeBudgetPeriodType($data['budget_period_type'] ?? 'monthly');
+ $anchorDate = sanitizeBudgetAnchorDate($data['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());
+
+ $sets[] = 'budget_period_type = :periodType';
+ $binds[':periodType'] = ['value' => $periodType, 'type' => SQLITE3_TEXT];
+ $sets[] = 'budget_period_anchor_date = :anchorDate';
+ $binds[':anchorDate'] = ['value' => $anchorDate, 'type' => SQLITE3_TEXT];
+}
+
+if (empty($sets)) {
+ echo json_encode(["success" => false, "message" => translate('error_updating_user_data', $i18n)]);
+ exit;
+}
+
+$sql = "UPDATE user SET " . implode(', ', $sets) . " WHERE id = :userId";
$stmt = $db->prepare($sql);
-$stmt->bindValue(':budget', $budget, SQLITE3_TEXT);
-$stmt->bindValue(':userId', $userId, SQLITE3_TEXT);
+foreach ($binds as $key => $bind) {
+ $stmt->bindValue($key, $bind['value'], $bind['type']);
+}
+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
if ($result) {
@@ -20,14 +55,13 @@ if ($result) {
"success" => true,
"message" => translate('user_details_saved', $i18n)
];
- echo json_encode($response);
} else {
$response = [
"success" => false,
"message" => translate('error_updating_user_data', $i18n)
];
- echo json_encode($response);
}
+echo json_encode($response);
-?>
\ No newline at end of file
+?>
diff --git a/includes/budget_period_calculations.php b/includes/budget_period_calculations.php
new file mode 100644
index 0000000..7913ace
--- /dev/null
+++ b/includes/budget_period_calculations.php
@@ -0,0 +1,305 @@
+<?php
+
+if (!function_exists('sanitizeBudgetPeriodType')) {
+ function sanitizeBudgetPeriodType($periodType)
+ {
+ $allowedTypes = ['weekly', 'fortnightly', 'monthly'];
+ return in_array($periodType, $allowedTypes, true) ? $periodType : 'monthly';
+ }
+}
+
+if (!function_exists('getDefaultBudgetAnchorDate')) {
+ function getDefaultBudgetAnchorDate()
+ {
+ return (new DateTime('now'))->format('Y-m-d');
+ }
+}
+
+if (!function_exists('sanitizeBudgetAnchorDate')) {
+ function sanitizeBudgetAnchorDate($anchorDate)
+ {
+ if (!is_string($anchorDate) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $anchorDate)) {
+ return getDefaultBudgetAnchorDate();
+ }
+
+ $parsed = DateTime::createFromFormat('Y-m-d', $anchorDate);
+ if ($parsed === false || $parsed->format('Y-m-d') !== $anchorDate) {
+ return getDefaultBudgetAnchorDate();
+ }
+
+ return $anchorDate;
+ }
+}
+
+if (!function_exists('createDateAtMidnight')) {
+ function createDateAtMidnight(DateTime $date)
+ {
+ return new DateTime($date->format('Y-m-d'));
+ }
+}
+
+if (!function_exists('getDateWithClampedDay')) {
+ function getDateWithClampedDay($year, $month, $day)
+ {
+ $base = DateTime::createFromFormat('!Y-n-j', $year . '-' . $month . '-1');
+ if ($base === false) {
+ $base = new DateTime('1970-01-01');
+ }
+
+ $lastDay = (int) $base->format('t');
+ $clampedDay = min(max(1, (int) $day), $lastDay);
+
+ return DateTime::createFromFormat('!Y-n-j', $year . '-' . $month . '-' . $clampedDay);
+ }
+}
+
+if (!function_exists('getActiveBudgetPeriod')) {
+ function getActiveBudgetPeriod(DateTime $today, $periodType, $anchorDate)
+ {
+ $periodType = sanitizeBudgetPeriodType($periodType);
+ $anchorDate = sanitizeBudgetAnchorDate($anchorDate ?: getDefaultBudgetAnchorDate());
+
+ $todayDate = createDateAtMidnight($today);
+ $anchor = DateTime::createFromFormat('!Y-m-d', $anchorDate);
+ if ($anchor === false) {
+ $anchor = new DateTime('1970-01-01');
+ }
+
+ if ($periodType === 'weekly' || $periodType === 'fortnightly') {
+ $periodLengthDays = $periodType === 'weekly' ? 7 : 14;
+ $diffDays = (int) $anchor->diff($todayDate)->format('%r%a');
+ $periodOffset = (int) floor($diffDays / $periodLengthDays);
+
+ $start = clone $anchor;
+ $start->modify(($periodOffset * $periodLengthDays) . ' day');
+
+ if ($start > $todayDate) {
+ $start->modify('-' . $periodLengthDays . ' day');
+ }
+
+ $end = clone $start;
+ $end->modify('+' . ($periodLengthDays - 1) . ' day');
+ } else {
+ $anchorDay = (int) $anchor->format('j');
+ $currentMonthStart = getDateWithClampedDay((int) $todayDate->format('Y'), (int) $todayDate->format('n'), $anchorDay);
+
+ if ($todayDate < $currentMonthStart) {
+ $currentMonthStart->modify('first day of previous month');
+ $currentMonthStart = getDateWithClampedDay((int) $currentMonthStart->format('Y'), (int) $currentMonthStart->format('n'), $anchorDay);
+ }
+
+ $start = $currentMonthStart;
+ $nextStartMonth = clone $start;
+ $nextStartMonth->modify('first day of next month');
+ $nextStart = getDateWithClampedDay((int) $nextStartMonth->format('Y'), (int) $nextStartMonth->format('n'), $anchorDay);
+ $end = clone $nextStart;
+ $end->modify('-1 day');
+ }
+
+ return [
+ 'start' => $start,
+ 'end' => $end,
+ 'label' => formatBudgetPeriodLabel($start, $end),
+ 'type' => $periodType,
+ ];
+ }
+}
+
+if (!function_exists('formatBudgetPeriodLabel')) {
+ function formatBudgetPeriodLabel(DateTime $start, DateTime $end)
+ {
+ $startLabel = $start->format('M j');
+ $endLabel = $end->format('M j');
+
+ if ($start->format('Y') !== $end->format('Y')) {
+ $startLabel .= ', ' . $start->format('Y');
+ $endLabel .= ', ' . $end->format('Y');
+ }
+
+ return $startLabel . ' - ' . $endLabel;
+ }
+}
+
+if (!function_exists('getSubscriptionIntervalSpec')) {
+ function getSubscriptionIntervalSpec($cycle, $frequency)
+ {
+ $frequency = max(1, (int) $frequency);
+ $cycle = (int) $cycle;
+
+ $unit = match ($cycle) {
+ 1 => 'D',
+ 2 => 'W',
+ 3 => 'M',
+ 4 => 'Y',
+ default => null,
+ };
+
+ return $unit !== null ? 'P' . $frequency . $unit : null;
+ }
+}
+
+if (!function_exists('shiftSubscriptionOccurrence')) {
+ function shiftSubscriptionOccurrence(DateTime $date, array $subscription, DateTime $anchorDate, $direction)
+ {
+ $frequency = max(1, (int) ($subscription['frequency'] ?? 1));
+ $cycle = (int) ($subscription['cycle'] ?? 0);
+ $direction = $direction < 0 ? -1 : 1;
+ $step = $direction * $frequency;
+
+ if ($cycle === 1) {
+ $shifted = clone $date;
+ $shifted->modify($step . ' day');
+ return createDateAtMidnight($shifted);
+ }
+
+ if ($cycle === 2) {
+ $shifted = clone $date;
+ $shifted->modify(($step * 7) . ' day');
+ return createDateAtMidnight($shifted);
+ }
+
+ if ($cycle === 3) {
+ $totalMonths = ((int) $date->format('Y') * 12) + ((int) $date->format('n') - 1) + $step;
+ $targetYear = (int) floor($totalMonths / 12);
+ $targetMonth = ($totalMonths % 12) + 1;
+ $anchorDay = (int) $anchorDate->format('j');
+
+ return getDateWithClampedDay($targetYear, $targetMonth, $anchorDay);
+ }
+
+ if ($cycle === 4) {
+ $targetYear = (int) $date->format('Y') + $step;
+ $anchorMonth = (int) $anchorDate->format('n');
+ $anchorDay = (int) $anchorDate->format('j');
+
+ return getDateWithClampedDay($targetYear, $anchorMonth, $anchorDay);
+ }
+
+ return null;
+ }
+}
+
+if (!function_exists('getSubscriptionOccurrencesInRange')) {
+ function getSubscriptionOccurrencesInRange(array $subscription, DateTime $rangeStart, DateTime $rangeEnd)
+ {
+ if (empty($subscription['next_payment'])) {
+ return [];
+ }
+
+ $nextPayment = DateTime::createFromFormat('!Y-m-d', trim($subscription['next_payment']));
+ if ($nextPayment === false) {
+ return [];
+ }
+
+ $rangeStartDate = createDateAtMidnight($rangeStart);
+ $rangeEndDate = createDateAtMidnight($rangeEnd);
+ $occurrences = [];
+
+ $autoRenew = isset($subscription['auto_renew']) ? (int) $subscription['auto_renew'] === 1 : true;
+ $intervalSpec = getSubscriptionIntervalSpec($subscription['cycle'] ?? 0, $subscription['frequency'] ?? 1);
+
+ if ($intervalSpec === null) {
+ return [];
+ }
+
+ if (!$autoRenew) {
+ return ($nextPayment >= $rangeStartDate && $nextPayment <= $rangeEndDate)
+ ? [clone $nextPayment]
+ : [];
+ }
+
+ $current = clone $nextPayment;
+ $safetyCounter = 0;
+
+ while ($current > $rangeStartDate) {
+ $current = shiftSubscriptionOccurrence($current, $subscription, $nextPayment, -1);
+ if ($current === null) {
+ return [];
+ }
+ $safetyCounter++;
+ if ($safetyCounter > 10000) {
+ return [];
+ }
+ }
+
+ while ($current < $rangeStartDate) {
+ $current = shiftSubscriptionOccurrence($current, $subscription, $nextPayment, 1);
+ if ($current === null) {
+ return [];
+ }
+ $safetyCounter++;
+ if ($safetyCounter > 10000) {
+ return [];
+ }
+ }
+
+ while ($current <= $rangeEndDate) {
+ if ($current >= $rangeStartDate) {
+ $occurrences[] = clone $current;
+ }
+
+ $nextOccurrence = shiftSubscriptionOccurrence($current, $subscription, $nextPayment, 1);
+ if ($nextOccurrence === null || $nextOccurrence <= $current) {
+ break;
+ }
+ $current = $nextOccurrence;
+ $safetyCounter++;
+ if ($safetyCounter > 10000) {
+ break;
+ }
+ }
+
+ return $occurrences;
+ }
+}
+
+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'];
+ }
+}
+
+if (!function_exists('computeAmountNeededInPeriod')) {
+ function computeAmountNeededInPeriod(array $subscriptions, DateTime $today, DateTime $periodEnd, SQLite3 $database, $userId)
+ {
+ $rangeStart = createDateAtMidnight($today);
+ $amountNeeded = 0.0;
+
+ foreach ($subscriptions as $subscription) {
+ $isActive = isset($subscription['inactive']) && (int) $subscription['inactive'] === 0;
+ if (!$isActive) {
+ continue;
+ }
+
+ $occurrences = getSubscriptionOccurrencesInRange($subscription, $rangeStart, $periodEnd);
+ if (empty($occurrences)) {
+ continue;
+ }
+
+ $price = convertPriceToMainCurrency(
+ $subscription['price'],
+ $subscription['currency_id'],
+ $database,
+ $userId
+ );
+
+ $amountNeeded += $price * count($occurrences);
+ }
+
+ return $amountNeeded;
+ }
+}
+
+?>
diff --git a/includes/i18n/ca.php b/includes/i18n/ca.php
index 8c8f95d..0e33c22 100644
--- a/includes/i18n/ca.php
+++ b/includes/i18n/ca.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "La clau API s'utilitza per accedir a l'API de Wallos. No la comparteixis amb ningú.",
// Settings page
"monthly_budget" => "Pressupost Mensual",
+ "monthly_budget_info" => "El pressupost mensual es compara amb el cost total mensual de les teves subscripcions.",
+ "period_budget" => "Pressupost del període",
+ "period_budget_info" => "El pressupost del període fa un seguiment del que cal pagar dins del període de pressupost triat.",
+ "budget_period" => "Període de pressupost",
+ "budget_anchor_date" => "Data d'ancoratge",
+ "fortnightly" => "Quinzena / Quinzenes",
+ "cost_vs_monthly_budget" => "Cost vs Pressupost Mensual",
+ "cost_vs_period_budget" => "Cost vs Pressupost del Període",
+ "send_period_summary_at_period_start" => "Envia un resum a l'inici de cada període de pagament",
+ "amount_for_pay_period" => "Import per al Període de Pagament",
+ "remaining" => "Restant",
+ "amount_needed_this_period" => "Import necessari aquest període",
+ "current_period" => "Període actual",
"budget_info" => "El pressupost mensual s'utilitza per calcular les estadístiques. Si no vols utilitzar aquesta funció, deixa'l a 0.",
"household" => "Familia",
"save_member" => "Guardar Membre",
diff --git a/includes/i18n/cs.php b/includes/i18n/cs.php
index 8acbe71..600680f 100644
--- a/includes/i18n/cs.php
+++ b/includes/i18n/cs.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Klíč API slouží k přístupu k rozhraní API. Udržujte jej v tajnosti.",
// Settings page
"monthly_budget" => "Měsíční rozpočet",
+ "monthly_budget_info" => "Měsíční rozpočet se porovnává s celkovými měsíčními náklady na předplatná.",
+ "period_budget" => "Rozpočet na období",
+ "period_budget_info" => "Rozpočet na období sleduje, kolik je třeba zaplatit ve vybraném rozpočtovém období.",
+ "budget_period" => "Rozpočtové období",
+ "budget_anchor_date" => "Počáteční datum",
+ "fortnightly" => "čtrnáct dní",
+ "cost_vs_monthly_budget" => "Náklady vs měsíční rozpočet",
+ "cost_vs_period_budget" => "Náklady vs rozpočet na období",
+ "send_period_summary_at_period_start" => "Odeslat souhrn na začátku každého platebního období",
+ "amount_for_pay_period" => "Částka za platební období",
+ "remaining" => "Zbývá",
+ "amount_needed_this_period" => "Potřebná částka v tomto období",
+ "current_period" => "Aktuální období",
"budget_info" => "Měsíční rozpočet se používá pro výpočet statistik",
"household" => "Domácnost",
"save_member" => "Uložit člena",
diff --git a/includes/i18n/da.php b/includes/i18n/da.php
index 8bdc7d2..703911a 100644
--- a/includes/i18n/da.php
+++ b/includes/i18n/da.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API-nøglen bruges til at få adgang til API'en. Hold den hemmelig.",
// Settings page
"monthly_budget" => "Månedligt budget",
+ "monthly_budget_info" => "Det månedlige budget sammenlignes med dine samlede månedlige abonnementsudgifter.",
+ "period_budget" => "Periodebudget",
+ "period_budget_info" => "Periodebudgettet holder styr på, hvad du skal betale i den valgte budgetperiode.",
+ "budget_period" => "Budgetperiode",
+ "budget_anchor_date" => "Startdato",
+ "fortnightly" => "Fjorten dage",
+ "cost_vs_monthly_budget" => "Udgift vs. månedligt budget",
+ "cost_vs_period_budget" => "Udgift vs. periodebudget",
+ "send_period_summary_at_period_start" => "Send opsummering ved starten af hver betalingsperiode",
+ "amount_for_pay_period" => "Beløb for betalingsperiode",
+ "remaining" => "Resterende",
+ "amount_needed_this_period" => "Nødvendigt beløb i denne periode",
+ "current_period" => "Nuværende periode",
"budget_info" => "Det månedlige budget bruges til at beregne statistikker",
"household" => "Husstand",
"save_member" => "Gem medlem",
diff --git a/includes/i18n/de.php b/includes/i18n/de.php
index 6b8fb63..b39f626 100644
--- a/includes/i18n/de.php
+++ b/includes/i18n/de.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Der API-Schlüssel wird für die Integration von Drittanbieter-Apps verwendet. Wenn Sie Ihren Schlüssel neu generieren, müssen Sie ihn in allen Apps aktualisieren, die ihn verwenden.",
// Settings page
"monthly_budget" => "Monatliches Budget",
+ "monthly_budget_info" => "Das monatliche Budget wird mit Ihren gesamten monatlichen Abonnementkosten verglichen.",
+ "period_budget" => "Zeitraumbudget",
+ "period_budget_info" => "Das Zeitraumbudget verfolgt, was Sie innerhalb Ihres gewählten Budgetzeitraums zahlen müssen.",
+ "budget_period" => "Budgetzeitraum",
+ "budget_anchor_date" => "Ankerdatum",
+ "fortnightly" => "Zweiwöchentlich",
+ "cost_vs_monthly_budget" => "Kosten vs. monatliches Budget",
+ "cost_vs_period_budget" => "Kosten vs. Zeitraumbudget",
+ "send_period_summary_at_period_start" => "Zusammenfassung zu Beginn jedes Zahlungszeitraums senden",
+ "amount_for_pay_period" => "Betrag für Zahlungszeitraum",
+ "remaining" => "Verbleibend",
+ "amount_needed_this_period" => "Benötigter Betrag in diesem Zeitraum",
+ "current_period" => "Aktueller Zeitraum",
"budget_info" => "Das monatliche Budget wird für die Berechnung der Statistiken verwendet.",
"household" => "Haushalt",
"save_member" => "Mitglied speichern",
diff --git a/includes/i18n/el.php b/includes/i18n/el.php
index 42af006..d00fd3f 100644
--- a/includes/i18n/el.php
+++ b/includes/i18n/el.php
@@ -177,6 +177,19 @@ $i18n = [
"api_key_info" => "Το API κλειδί χρησιμοποιείται για την επικοινωνία με το API του Wallos. Μην αποκαλύπτετε το API κλειδί σας σε κανέναν.",
// Settings page
"monthly_budget" => "Μηνιαίος προϋπολογισμός",
+ "monthly_budget_info" => "Ο μηνιαίος προϋπολογισμός συγκρίνεται με το συνολικό μηνιαίο κόστος των συνδρομών σας.",
+ "period_budget" => "Προϋπολογισμός Περιόδου",
+ "period_budget_info" => "Ο προϋπολογισμός περιόδου παρακολουθεί τι πρέπει να πληρώσετε εντός της επιλεγμένης περιόδου προϋπολογισμού.",
+ "budget_period" => "Περίοδος προϋπολογισμού",
+ "budget_anchor_date" => "Ημερομηνία αναφοράς",
+ "fortnightly" => "Δεκαπενθήμερο",
+ "cost_vs_monthly_budget" => "Κόστος έναντι Μηνιαίου Προϋπολογισμού",
+ "cost_vs_period_budget" => "Κόστος έναντι Προϋπολογισμού Περιόδου",
+ "send_period_summary_at_period_start" => "Αποστολή σύνοψης στην αρχή κάθε περιόδου πληρωμής",
+ "amount_for_pay_period" => "Ποσό για την Περίοδο Πληρωμής",
+ "remaining" => "Υπόλοιπο",
+ "amount_needed_this_period" => "Απαιτούμενο ποσό αυτή την περίοδο",
+ "current_period" => "Τρέχουσα περίοδος",
"budget_info" => "Ο μηνιαίος προϋπολογισμός χρησιμοποιείται για τον υπολογισμό των στατιστικών",
"household" => "Νοικοκυριό",
"save_member" => "Αποθήκευση μέλους",
diff --git a/includes/i18n/en.php b/includes/i18n/en.php
index a3aa411..0615392 100644
--- a/includes/i18n/en.php
+++ b/includes/i18n/en.php
@@ -202,6 +202,19 @@ $i18n = [
"api_key_info" => "The API key is used to access the API. Keep it secret.",
// Settings page
"monthly_budget" => "Monthly Budget",
+ "monthly_budget_info" => "Monthly budget compares against your total monthly subscription cost.",
+ "period_budget" => "Period Budget",
+ "period_budget_info" => "Period budget tracks what you need to pay within your chosen budget period.",
+ "budget_period" => "Budget period",
+ "budget_anchor_date" => "Anchor date",
+ "fortnightly" => "Fortnight(s)",
+ "cost_vs_monthly_budget" => "Cost vs Monthly Budget",
+ "cost_vs_period_budget" => "Cost vs Period Budget",
+ "send_period_summary_at_period_start" => "Send summary at start of each payment period",
+ "amount_for_pay_period" => "Amount for Pay Period",
+ "remaining" => "Remaining",
+ "amount_needed_this_period" => "Amount needed this period",
+ "current_period" => "Current period",
"budget_info" => "Monthly budget is used to calculate statistics",
"household" => "Household",
"save_member" => "Save Member",
diff --git a/includes/i18n/es.php b/includes/i18n/es.php
index 1ffcbb7..0547401 100644
--- a/includes/i18n/es.php
+++ b/includes/i18n/es.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "La clave API se utiliza para acceder a la API de Wallos. No compartas esta clave con nadie.",
// Settings page
"monthly_budget" => "Presupuesto Mensual",
+ "monthly_budget_info" => "El presupuesto mensual se compara con el costo total mensual de tus suscripciones.",
+ "period_budget" => "Presupuesto del Periodo",
+ "period_budget_info" => "El presupuesto del periodo hace seguimiento de lo que necesitas pagar dentro del periodo de presupuesto elegido.",
+ "budget_period" => "Periodo de presupuesto",
+ "budget_anchor_date" => "Fecha de referencia",
+ "fortnightly" => "Quincena(s)",
+ "cost_vs_monthly_budget" => "Costo vs Presupuesto Mensual",
+ "cost_vs_period_budget" => "Costo vs Presupuesto del Periodo",
+ "send_period_summary_at_period_start" => "Enviar resumen al inicio de cada periodo de pago",
+ "amount_for_pay_period" => "Monto para el Periodo de Pago",
+ "remaining" => "Restante",
+ "amount_needed_this_period" => "Monto necesario este periodo",
+ "current_period" => "Periodo actual",
"budget_info" => "El presupuesto mensual se utiliza para calcular las estadísticas. Si no deseas utilizar esta función, déjalo en 0.",
"household" => "Hogar",
"save_member" => "Guardar Miembro",
diff --git a/includes/i18n/fr.php b/includes/i18n/fr.php
index 9f82fcb..43f2ae9 100644
--- a/includes/i18n/fr.php
+++ b/includes/i18n/fr.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "La clé API est utilisée pour les applications tierces et les intégrations. Ne la partagez pas.",
// Page de paramètres
"monthly_budget" => "Budget mensuel",
+ "monthly_budget_info" => "Le budget mensuel est comparé au coût total mensuel de vos abonnements.",
+ "period_budget" => "Budget de la période",
+ "period_budget_info" => "Le budget de la période suit ce que vous devez payer pendant la période de budget choisie.",
+ "budget_period" => "Période de budget",
+ "budget_anchor_date" => "Date de référence",
+ "fortnightly" => "Quinzaine",
+ "cost_vs_monthly_budget" => "Coût vs Budget Mensuel",
+ "cost_vs_period_budget" => "Coût vs Budget de la Période",
+ "send_period_summary_at_period_start" => "Envoyer un résumé au début de chaque période de paiement",
+ "amount_for_pay_period" => "Montant pour la Période de Paiement",
+ "remaining" => "Restant",
+ "amount_needed_this_period" => "Montant nécessaire pour cette période",
+ "current_period" => "Période actuelle",
"budget_info" => "Le budget mensuel est utilisé pour calculer les statistiques. Laissez vide pour désactiver.",
"household" => "Ménage",
"save_member" => "Enregistrer le membre",
diff --git a/includes/i18n/hu.php b/includes/i18n/hu.php
index d3efd2b..7010481 100644
--- a/includes/i18n/hu.php
+++ b/includes/i18n/hu.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Az API kulcs az API eléréséhez használatos. Tartsa titokban.",
// Settings page
"monthly_budget" => "Havi költségvetés",
+ "monthly_budget_info" => "A havi költségvetést az előfizetések teljes havi költségével hasonlítja össze.",
+ "period_budget" => "Időszaki költségvetés",
+ "period_budget_info" => "Az időszaki költségvetés nyomon követi, mennyit kell fizetnie a kiválasztott költségvetési időszakban.",
+ "budget_period" => "Költségvetési időszak",
+ "budget_anchor_date" => "Kezdő dátum",
+ "fortnightly" => "Két hetente",
+ "cost_vs_monthly_budget" => "Költség vs Havi Költségvetés",
+ "cost_vs_period_budget" => "Költség vs Időszaki Költségvetés",
+ "send_period_summary_at_period_start" => "Összefoglaló küldése minden fizetési időszak elején",
+ "amount_for_pay_period" => "Összeg a fizetési időszakra",
+ "remaining" => "Fennmaradó",
+ "amount_needed_this_period" => "Szükséges összeg ebben az időszakban",
+ "current_period" => "Jelenlegi időszak",
"budget_info" => "A havi költségvetés a statisztikák kiszámításához használatos",
"household" => "Háztartás",
"save_member" => "Tag mentése",
diff --git a/includes/i18n/id.php b/includes/i18n/id.php
index 4086719..533cd35 100644
--- a/includes/i18n/id.php
+++ b/includes/i18n/id.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Kunci API digunakan untuk mengakses API. Jaga kerahasiaannya.",
// Settings page
"monthly_budget" => "Anggaran Bulanan",
+ "monthly_budget_info" => "Anggaran bulanan dibandingkan dengan total biaya bulanan berlangganan Anda.",
+ "period_budget" => "Anggaran Periode",
+ "period_budget_info" => "Anggaran periode melacak apa yang perlu Anda bayar dalam periode anggaran yang dipilih.",
+ "budget_period" => "Periode anggaran",
+ "budget_anchor_date" => "Tanggal acuan",
+ "fortnightly" => "Dua Mingguan",
+ "cost_vs_monthly_budget" => "Biaya vs Anggaran Bulanan",
+ "cost_vs_period_budget" => "Biaya vs Anggaran Periode",
+ "send_period_summary_at_period_start" => "Kirim ringkasan di awal setiap periode pembayaran",
+ "amount_for_pay_period" => "Jumlah untuk Periode Pembayaran",
+ "remaining" => "Sisa",
+ "amount_needed_this_period" => "Jumlah yang dibutuhkan periode ini",
+ "current_period" => "Periode saat ini",
"budget_info" => "Anggaran bulanan digunakan untuk menghitung statistik",
"household" => "Rumah Tangga",
"save_member" => "Simpan Anggota",
diff --git a/includes/i18n/it.php b/includes/i18n/it.php
index 87b3613..c4f8a02 100644
--- a/includes/i18n/it.php
+++ b/includes/i18n/it.php
@@ -186,6 +186,19 @@ $i18n = [
"api_key_info" => "La chiave API viene utilizzata per accedere ai dati tramite l'API di Wallos. Non condividere la tua chiave API con nessuno.",
// Settings
"monthly_budget" => "Budget mensile",
+ "monthly_budget_info" => "Il budget mensile viene confrontato con il costo totale mensile dei tuoi abbonamenti.",
+ "period_budget" => "Budget del Periodo",
+ "period_budget_info" => "Il budget del periodo monitora quanto devi pagare nel periodo di budget scelto.",
+ "budget_period" => "Periodo di budget",
+ "budget_anchor_date" => "Data di ancoraggio",
+ "fortnightly" => "Quindicina",
+ "cost_vs_monthly_budget" => "Costo vs Budget Mensile",
+ "cost_vs_period_budget" => "Costo vs Budget del Periodo",
+ "send_period_summary_at_period_start" => "Invia un riepilogo all'inizio di ogni periodo di pagamento",
+ "amount_for_pay_period" => "Importo per il Periodo di Pagamento",
+ "remaining" => "Rimanente",
+ "amount_needed_this_period" => "Importo necessario in questo periodo",
+ "current_period" => "Periodo attuale",
"budget_info" => "Il budget mensile viene utilizzato per calcolare le statistiche. Se non si desidera utilizzare questa funzionalità, impostare il budget su 0.",
"household" => 'Nucleo familiare',
"save_member" => 'Salva membro',
diff --git a/includes/i18n/ja.php b/includes/i18n/ja.php
index 95acc12..94242b5 100644
--- a/includes/i18n/ja.php
+++ b/includes/i18n/ja.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "APIキーは、WallosのAPIを使用するために必要です。APIキーを再生成すると、以前のキーは無効になります。",
// Settings page
"monthly_budget" => "月間予算",
+ "monthly_budget_info" => "月間予算は、サブスクリプションの月間合計費用と比較されます。",
+ "period_budget" => "期間予算",
+ "period_budget_info" => "期間予算は、選択した予算期間内に支払う必要がある金額を追跡します。",
+ "budget_period" => "予算期間",
+ "budget_anchor_date" => "基準日",
+ "fortnightly" => "隔週",
+ "cost_vs_monthly_budget" => "費用 対 月間予算",
+ "cost_vs_period_budget" => "費用 対 期間予算",
+ "send_period_summary_at_period_start" => "各支払い期間の開始時にまとめを送信",
+ "amount_for_pay_period" => "支払い期間の金額",
+ "remaining" => "残り",
+ "amount_needed_this_period" => "今期に必要な金額",
+ "current_period" => "現在の期間",
"budget_info" => "予算を設定すると、統計ページで予算と実際の支出を比較できます。",
"household" => "世帯",
"save_member" => "世帯員を保存",
diff --git a/includes/i18n/ko.php b/includes/i18n/ko.php
index 08c0da3..a8d08d0 100644
--- a/includes/i18n/ko.php
+++ b/includes/i18n/ko.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API 키는 외부 애플리케이션과 통신할 때 사용됩니다. API 키를 재생성하면 이전 키는 더 이상 유효하지 않습니다.",
// Settings page
"monthly_budget" => "월간 예산",
+ "monthly_budget_info" => "월간 예산은 구독의 총 월간 비용과 비교됩니다.",
+ "period_budget" => "기간 예산",
+ "period_budget_info" => "기간 예산은 선택한 예산 기간 내에 지불해야 하는 금액을 추적합니다.",
+ "budget_period" => "예산 기간",
+ "budget_anchor_date" => "기준 날짜",
+ "fortnightly" => "2주",
+ "cost_vs_monthly_budget" => "비용 대 월간 예산",
+ "cost_vs_period_budget" => "비용 대 기간 예산",
+ "send_period_summary_at_period_start" => "각 결제 기간 시작 시 요약 보내기",
+ "amount_for_pay_period" => "결제 기간 금액",
+ "remaining" => "남음",
+ "amount_needed_this_period" => "이번 기간에 필요한 금액",
+ "current_period" => "현재 기간",
"budget_info" => "예산을 설정하면 통계 페이지에서 예산과 실제 지출을 비교할 수 있습니다.",
"household" => "가구",
"save_member" => "구성원 저장",
diff --git a/includes/i18n/nl.php b/includes/i18n/nl.php
index 5208c24..1ba3811 100644
--- a/includes/i18n/nl.php
+++ b/includes/i18n/nl.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "De API-sleutel wordt gebruikt om toegang te krijgen tot de API. Houd deze geheim.",
// Instellingen pagina
"monthly_budget" => "Maandelijks budget",
+ "monthly_budget_info" => "Het maandbudget wordt vergeleken met je totale maandelijkse abonnementskosten.",
+ "period_budget" => "Periodebudget",
+ "period_budget_info" => "Het periodebudget houdt bij wat je moet betalen binnen de gekozen budgetperiode.",
+ "budget_period" => "Budgetperiode",
+ "budget_anchor_date" => "Startdatum",
+ "fortnightly" => "Tweewekelijks",
+ "cost_vs_monthly_budget" => "Kosten vs Maandbudget",
+ "cost_vs_period_budget" => "Kosten vs Periodebudget",
+ "send_period_summary_at_period_start" => "Verzend samenvatting bij start van elke betaalperiode",
+ "amount_for_pay_period" => "Bedrag voor Betaalperiode",
+ "remaining" => "Resterend",
+ "amount_needed_this_period" => "Benodigd bedrag deze periode",
+ "current_period" => "Huidige periode",
"budget_info" => "Maandelijks budget wordt gebruikt om statistieken te berekenen",
"household" => "Huishouden",
"save_member" => "Lid opslaan",
diff --git a/includes/i18n/pl.php b/includes/i18n/pl.php
index 17dedae..cb12e4b 100644
--- a/includes/i18n/pl.php
+++ b/includes/i18n/pl.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Klucz API jest używany do integracji z innymi aplikacjami. Nie udostępniaj go nikomu.",
// Settings page
"monthly_budget" => "Miesięczny budżet",
+ "monthly_budget_info" => "Budżet miesięczny jest porównywany z całkowitym miesięcznym kosztem Twoich subskrypcji.",
+ "period_budget" => "Budżet okresu",
+ "period_budget_info" => "Budżet okresu śledzi, ile musisz zapłacić w wybranym okresie budżetowym.",
+ "budget_period" => "Okres budżetowy",
+ "budget_anchor_date" => "Data odniesienia",
+ "fortnightly" => "Dwa tygodnie",
+ "cost_vs_monthly_budget" => "Koszt vs Budżet Miesięczny",
+ "cost_vs_period_budget" => "Koszt vs Budżet Okresu",
+ "send_period_summary_at_period_start" => "Wysyłaj podsumowanie na początku każdego okresu płatności",
+ "amount_for_pay_period" => "Kwota za okres płatności",
+ "remaining" => "Pozostało",
+ "amount_needed_this_period" => "Kwota potrzebna w tym okresie",
+ "current_period" => "Aktualny okres",
"budget_info" => "Jeśli ustawisz budżet, zobaczysz pasek postępu na stronie głównej.",
"household" => "Gospodarstwo domowe",
"save_member" => "Zapisz użytkownika",
diff --git a/includes/i18n/pt.php b/includes/i18n/pt.php
index 706fca1..d372c65 100644
--- a/includes/i18n/pt.php
+++ b/includes/i18n/pt.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "A sua API Key é usada para aceder à API do Wallos. Não a partilhe com ninguém.",
// Settings page
"monthly_budget" => "Orçamento Mensal",
+ "monthly_budget_info" => "O orçamento mensal é comparado com o custo total mensal das suas subscrições.",
+ "period_budget" => "Orçamento do Período",
+ "period_budget_info" => "O orçamento do período acompanha o que precisa de pagar dentro do período de orçamento escolhido.",
+ "budget_period" => "Período de orçamento",
+ "budget_anchor_date" => "Data de referência",
+ "fortnightly" => "Quinzenal",
+ "cost_vs_monthly_budget" => "Custo vs Orçamento Mensal",
+ "cost_vs_period_budget" => "Custo vs Orçamento do Período",
+ "send_period_summary_at_period_start" => "Enviar resumo no início de cada período de pagamento",
+ "amount_for_pay_period" => "Montante para o Período de Pagamento",
+ "remaining" => "Restante",
+ "amount_needed_this_period" => "Montante necessário neste período",
+ "current_period" => "Período atual",
"budget_info" => "Ao definir um orçamento pode comparar com os gastos reais na página de estatísticas.",
"household" => "Agregado",
"save_member" => "Guardar Membro",
diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.php
index 68eac03..873e130 100644
--- a/includes/i18n/pt_br.php
+++ b/includes/i18n/pt_br.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "A chave da API é usada para acessar a API do Wallos. Não compartilhe sua chave com ninguém.",
// Settings page
"monthly_budget" => "Orçamento mensal",
+ "monthly_budget_info" => "O orçamento mensal é comparado com o custo total mensal das suas assinaturas.",
+ "period_budget" => "Orçamento do Período",
+ "period_budget_info" => "O orçamento do período acompanha o que você precisa pagar dentro do período de orçamento escolhido.",
+ "budget_period" => "Período de orçamento",
+ "budget_anchor_date" => "Data de referência",
+ "fortnightly" => "Quinzenal",
+ "cost_vs_monthly_budget" => "Custo vs Orçamento Mensal",
+ "cost_vs_period_budget" => "Custo vs Orçamento do Período",
+ "send_period_summary_at_period_start" => "Enviar resumo no início de cada período de pagamento",
+ "amount_for_pay_period" => "Valor para o Período de Pagamento",
+ "remaining" => "Restante",
+ "amount_needed_this_period" => "Valor necessário neste período",
+ "current_period" => "Período atual",
"budget_info" => "O orçamento mensal é usado para calcular estatísticas",
"household" => "Membros",
"save_member" => "Salvar membro",
diff --git a/includes/i18n/ro.php b/includes/i18n/ro.php
index ee3154c..40fd6fe 100644
--- a/includes/i18n/ro.php
+++ b/includes/i18n/ro.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "Cheia API este utilizată pentru a accesa API-ul. Păstreaz-o secretă!",
// Settings page
"monthly_budget" => "Buget lunar",
+ "monthly_budget_info" => "Bugetul lunar este comparat cu costul total lunar al abonamentelor tale.",
+ "period_budget" => "Bugetul perioadei",
+ "period_budget_info" => "Bugetul perioadei urmărește ce trebuie să plătești în perioada de buget aleasă.",
+ "budget_period" => "Perioadă de buget",
+ "budget_anchor_date" => "Data de referință",
+ "fortnightly" => "Bisăptămânal",
+ "cost_vs_monthly_budget" => "Cost vs Buget Lunar",
+ "cost_vs_period_budget" => "Cost vs Bugetul Perioadei",
+ "send_period_summary_at_period_start" => "Trimite un rezumat la începutul fiecărei perioade de plată",
+ "amount_for_pay_period" => "Suma pentru Perioada de Plată",
+ "remaining" => "Rămas",
+ "amount_needed_this_period" => "Suma necesară în această perioadă",
+ "current_period" => "Perioada curentă",
"budget_info" => "Bugetul lunar este utilizat pentru calcularea statisticilor.",
"household" => "Membrii familiei",
"save_member" => "Salvează membru",
diff --git a/includes/i18n/ru.php b/includes/i18n/ru.php
index cd221af..edfd79a 100644
--- a/includes/i18n/ru.php
+++ b/includes/i18n/ru.php
@@ -175,6 +175,19 @@ $i18n = [
"disable_two_factor_authentication" => "Отключить двухфакторную аутентификацию",
"totp_code" => "Код TOTP",
"monthly_budget" => "Ежемесячный бюджет",
+ "monthly_budget_info" => "Месячный бюджет сравнивается с общей ежемесячной стоимостью ваших подписок.",
+ "period_budget" => "Бюджет периода",
+ "period_budget_info" => "Бюджет периода отслеживает, сколько нужно заплатить в выбранном бюджетном периоде.",
+ "budget_period" => "Бюджетный период",
+ "budget_anchor_date" => "Дата отсчёта",
+ "fortnightly" => "Раз в две недели",
+ "cost_vs_monthly_budget" => "Стоимость vs Месячный бюджет",
+ "cost_vs_period_budget" => "Стоимость vs Бюджет периода",
+ "send_period_summary_at_period_start" => "Отправлять сводку в начале каждого платёжного периода",
+ "amount_for_pay_period" => "Сумма за платёжный период",
+ "remaining" => "Осталось",
+ "amount_needed_this_period" => "Необходимая сумма в этом периоде",
+ "current_period" => "Текущий период",
"api_key" => "API ключ",
"regenerate" => "Сгенерировать",
"api_key_info" => "API ключ используется для доступа к вашим данным через API. Не передавайте его третьим лицам.",
diff --git a/includes/i18n/sl.php b/includes/i18n/sl.php
index f465072..05915bd 100644
--- a/includes/i18n/sl.php
+++ b/includes/i18n/sl.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API ključ se uporablja za dostop do vaših podatkov prek API-ja. Če mislite, da je vaš ključ kompromitiran, ga lahko ponovno generirate.",
// Settings page
"monthly_budget" => "Mesečni proračun",
+ "monthly_budget_info" => "Mesečni proračun se primerja s skupnimi mesečnimi stroški vaših naročnin.",
+ "period_budget" => "Proračun obdobja",
+ "period_budget_info" => "Proračun obdobja sledi, koliko morate plačati v izbranem proračunskem obdobju.",
+ "budget_period" => "Proračunsko obdobje",
+ "budget_anchor_date" => "Izhodiščni datum",
+ "fortnightly" => "Vsaka dva tedna",
+ "cost_vs_monthly_budget" => "Stroški vs Mesečni proračun",
+ "cost_vs_period_budget" => "Stroški vs Proračun obdobja",
+ "send_period_summary_at_period_start" => "Pošlji povzetek na začetku vsakega plačilnega obdobja",
+ "amount_for_pay_period" => "Znesek za plačilno obdobje",
+ "remaining" => "Preostalo",
+ "amount_needed_this_period" => "Potreben znesek v tem obdobju",
+ "current_period" => "Trenutno obdobje",
"budget_info" => "Mesečni proračun se uporablja za izračun statistike",
"household" => "Gospodinjstvo",
"save_member" => "Shrani člana",
diff --git a/includes/i18n/sr.php b/includes/i18n/sr.php
index 2ed03da..e2e7e85 100644
--- a/includes/i18n/sr.php
+++ b/includes/i18n/sr.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API кључ је потребан за коришћење API-ја за приступ вашим подацима. Не делите овај кључ са другима.",
// Страница са подешавањима
"monthly_budget" => "Месечни буџет",
+ "monthly_budget_info" => "Месечни буџет се упоређује са укупним месечним трошком ваших претплата.",
+ "period_budget" => "Буџет периода",
+ "period_budget_info" => "Буџет периода прати колико треба да платите у изабраном периоду буџета.",
+ "budget_period" => "Период буџета",
+ "budget_anchor_date" => "Референтни датум",
+ "fortnightly" => "Двонедељно",
+ "cost_vs_monthly_budget" => "Трошак vs Месечни буџет",
+ "cost_vs_period_budget" => "Трошак vs Буџет периода",
+ "send_period_summary_at_period_start" => "Пошаљи сажетак на почетку сваког периода плаћања",
+ "amount_for_pay_period" => "Износ за период плаћања",
+ "remaining" => "Преостало",
+ "amount_needed_this_period" => "Потребан износ у овом периоду",
+ "current_period" => "Тренутни период",
"budget_info" => "Унесите месечни буџет да бисте видели препоручену максималну цену претплате на почетној страници.",
"household" => "Домаћинство",
"save_member" => "Сачувај члана",
diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.php
index 51f3e59..b7b7f56 100644
--- a/includes/i18n/sr_lat.php
+++ b/includes/i18n/sr_lat.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API ključ se koristi za pristup Wallos API-ju. Ako mislite da je vaš ključ kompromitovan, možete ga regenerisati.",
// Stranica sa podešavanjima
"monthly_budget" => "Mesečni budžet",
+ "monthly_budget_info" => "Mesečni budžet se upoređuje sa ukupnim mesečnim troškom vaših pretplata.",
+ "period_budget" => "Budžet perioda",
+ "period_budget_info" => "Budžet perioda prati koliko treba da platite u izabranom periodu budžeta.",
+ "budget_period" => "Period budžeta",
+ "budget_anchor_date" => "Referentni datum",
+ "fortnightly" => "Dvonedeljno",
+ "cost_vs_monthly_budget" => "Trošak vs Mesečni budžet",
+ "cost_vs_period_budget" => "Trošak vs Budžet perioda",
+ "send_period_summary_at_period_start" => "Pošalji sažetak na početku svakog perioda plaćanja",
+ "amount_for_pay_period" => "Iznos za period plaćanja",
+ "remaining" => "Preostalo",
+ "amount_needed_this_period" => "Potreban iznos u ovom periodu",
+ "current_period" => "Trenutni period",
"budget_info" => "Ovo je vaš mesečni budžet za sve pretplate. Ovo je samo informativno i ne ograničava vas.",
"household" => "Domaćinstvo",
"save_member" => "Sačuvaj člana",
diff --git a/includes/i18n/tr.php b/includes/i18n/tr.php
index 6dc61a9..4e38a67 100644
--- a/includes/i18n/tr.php
+++ b/includes/i18n/tr.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API Anahtarı, Wallos'un API'sine erişmek için kullanılır. Bu anahtarı kimseyle paylaşmayın.",
// Settings page
"monthly_budget" => "Aylık Bütçe",
+ "monthly_budget_info" => "Aylık bütçe, toplam aylık abonelik maliyetinizle karşılaştırılır.",
+ "period_budget" => "Dönem Bütçesi",
+ "period_budget_info" => "Dönem bütçesi, seçtiğiniz bütçe döneminde ödemeniz gerekeni takip eder.",
+ "budget_period" => "Bütçe dönemi",
+ "budget_anchor_date" => "Referans tarih",
+ "fortnightly" => "İki Haftalık",
+ "cost_vs_monthly_budget" => "Maliyet vs Aylık Bütçe",
+ "cost_vs_period_budget" => "Maliyet vs Dönem Bütçesi",
+ "send_period_summary_at_period_start" => "Her ödeme döneminin başında özet gönder",
+ "amount_for_pay_period" => "Ödeme Dönemi Tutarı",
+ "remaining" => "Kalan",
+ "amount_needed_this_period" => "Bu dönemde gereken tutar",
+ "current_period" => "Geçerli dönem",
"budget_info" => "Bir bütçe belirlemek, istatistik sayfasında bütçe ve gerçek harcamaları karşılaştırmanıza olanak tanır.",
"household" => "Hane",
"save_member" => "Üyeyi Kaydet",
diff --git a/includes/i18n/uk.php b/includes/i18n/uk.php
index 419960d..87fc18c 100644
--- a/includes/i18n/uk.php
+++ b/includes/i18n/uk.php
@@ -175,6 +175,19 @@ $i18n = [
"disable_two_factor_authentication" => "Вимкнути двофакторну автентифікацію",
"totp_code" => "Код TOTP",
"monthly_budget" => "Щомісячний бюджет",
+ "monthly_budget_info" => "Місячний бюджет порівнюється із загальною щомісячною вартістю ваших підписок.",
+ "period_budget" => "Бюджет періоду",
+ "period_budget_info" => "Бюджет періоду відстежує, скільки потрібно сплатити у вибраному бюджетному періоді.",
+ "budget_period" => "Бюджетний період",
+ "budget_anchor_date" => "Дата відліку",
+ "fortnightly" => "Раз на два тижні",
+ "cost_vs_monthly_budget" => "Вартість vs Місячний бюджет",
+ "cost_vs_period_budget" => "Вартість vs Бюджет періоду",
+ "send_period_summary_at_period_start" => "Надсилати підсумок на початку кожного платіжного періоду",
+ "amount_for_pay_period" => "Сума за платіжний період",
+ "remaining" => "Залишок",
+ "amount_needed_this_period" => "Необхідна сума у цьому періоді",
+ "current_period" => "Поточний період",
"api_key" => "API ключ",
"regenerate" => "Згенерувати",
"api_key_info" => "API ключ використовується для доступу до ваших даних через API. Не передавайте його третім особам.",
diff --git a/includes/i18n/vi.php b/includes/i18n/vi.php
index 24f12d0..9ad5e81 100644
--- a/includes/i18n/vi.php
+++ b/includes/i18n/vi.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API Key được sử dụng để truy cập API. Giữ nó bí mật.",
// Settings page
"monthly_budget" => "Ngân sách hàng tháng",
+ "monthly_budget_info" => "Ngân sách hàng tháng được so sánh với tổng chi phí đăng ký hàng tháng của bạn.",
+ "period_budget" => "Ngân sách theo kỳ",
+ "period_budget_info" => "Ngân sách theo kỳ theo dõi số tiền bạn cần thanh toán trong kỳ ngân sách đã chọn.",
+ "budget_period" => "Kỳ ngân sách",
+ "budget_anchor_date" => "Ngày mốc",
+ "fortnightly" => "Hai tuần một lần",
+ "cost_vs_monthly_budget" => "Chi phí so với Ngân sách hàng tháng",
+ "cost_vs_period_budget" => "Chi phí so với Ngân sách theo kỳ",
+ "send_period_summary_at_period_start" => "Gửi tóm tắt vào đầu mỗi kỳ thanh toán",
+ "amount_for_pay_period" => "Số tiền cho Kỳ thanh toán",
+ "remaining" => "Còn lại",
+ "amount_needed_this_period" => "Số tiền cần trong kỳ này",
+ "current_period" => "Kỳ hiện tại",
"budget_info" => "Ngân sách hàng tháng được sử dụng để tính toán thống kê",
"household" => "Hộ gia đình",
"save_member" => "Lưu thành viên",
diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.php
index dea491f..12c3651 100644
--- a/includes/i18n/zh_cn.php
+++ b/includes/i18n/zh_cn.php
@@ -187,6 +187,19 @@ $i18n = [
"api_key_info" => "API 密钥用于与 Wallos API 通信。请勿将此密钥分享给任何人。",
// 设置页面
"monthly_budget" => "月度预算",
+ "monthly_budget_info" => "月度预算会与您的订阅月度总费用进行比较。",
+ "period_budget" => "周期预算",
+ "period_budget_info" => "周期预算跟踪您在所选预算周期内需要支付的金额。",
+ "budget_period" => "预算周期",
+ "budget_anchor_date" => "起始日期",
+ "fortnightly" => "每两周",
+ "cost_vs_monthly_budget" => "费用与月度预算对比",
+ "cost_vs_period_budget" => "费用与周期预算对比",
+ "send_period_summary_at_period_start" => "在每个付款周期开始时发送摘要",
+ "amount_for_pay_period" => "付款周期金额",
+ "remaining" => "剩余",
+ "amount_needed_this_period" => "本周期所需金额",
+ "current_period" => "当前周期",
"budget_info" => "设置预算后,您可以在统计页面上比较预算和实际支出。",
"household" => "家庭",
"save_member" => "保存成员",
diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.php
index 3a4bff6..e28b01f 100644
--- a/includes/i18n/zh_tw.php
+++ b/includes/i18n/zh_tw.php
@@ -179,6 +179,19 @@ $i18n = [
"api_key_info" => "API 金鑰用於存取 Wallos API,請妥善保管、勿將此金鑰分享給任何人。",
// 設定頁面
"monthly_budget" => "每月預算",
+ "monthly_budget_info" => "每月預算會與您訂閱的每月總費用進行比較。",
+ "period_budget" => "週期預算",
+ "period_budget_info" => "週期預算會追蹤您在所選預算週期內需要支付的金額。",
+ "budget_period" => "預算週期",
+ "budget_anchor_date" => "起始日期",
+ "fortnightly" => "每兩週",
+ "cost_vs_monthly_budget" => "費用與每月預算對比",
+ "cost_vs_period_budget" => "費用與週期預算對比",
+ "send_period_summary_at_period_start" => "在每個付款週期開始時傳送摘要",
+ "amount_for_pay_period" => "付款週期金額",
+ "remaining" => "剩餘",
+ "amount_needed_this_period" => "本週期所需金額",
+ "current_period" => "目前週期",
"budget_info" => "每月預算用於計算統計資訊",
"household" => "家庭成員",
"save_member" => "儲存成員",
diff --git a/includes/stats_calculations.php b/includes/stats_calculations.php
index b7d9200..0c9a2c9 100644
--- a/includes/stats_calculations.php
+++ b/includes/stats_calculations.php
@@ -1,4 +1,5 @@
<?php
+require_once __DIR__ . '/budget_period_calculations.php';
function getPricePerMonth($cycle, $frequency, $price)
{
@@ -165,6 +166,7 @@ foreach ($params as $key => $value) {
$result = $stmt->execute();
$usesMultipleCurrencies = false;
+$subscriptions = [];
if ($result) {
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
@@ -273,30 +275,76 @@ if ($result) {
}
}
-$showVsBudgetGraph = false;
-$vsBudgetDataPoints = [];
+$today = new DateTime('now');
+$budgetPeriodType = sanitizeBudgetPeriodType($userData['budget_period_type'] ?? 'monthly');
+$budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userData['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());
+$activeBudgetPeriod = getActiveBudgetPeriod($today, $budgetPeriodType, $budgetPeriodAnchorDate);
+$budgetPeriodStart = $activeBudgetPeriod['start'];
+$budgetPeriodEnd = $activeBudgetPeriod['end'];
+$budgetPeriodLabel = $activeBudgetPeriod['label'];
+
+// A monthly period whose anchor lands on the calendar month's boundaries is
+// identical to the plain monthly budget, so there's nothing distinct to show.
+$calendarMonthStart = new DateTime($today->format('Y-m-01'));
+$calendarMonthEnd = new DateTime($today->format('Y-m-t'));
+$periodDiffersFromCalendarMonth = $budgetPeriodStart->format('Y-m-d') !== $calendarMonthStart->format('Y-m-d')
+ || $budgetPeriodEnd->format('Y-m-d') !== $calendarMonthEnd->format('Y-m-d');
+
+$amountNeededThisPeriod = computeAmountNeededInPeriod($subscriptions ?? [], $today, $budgetPeriodEnd, $db, $userId);
+
+$showVsMonthlyBudgetGraph = false;
+$vsMonthlyBudgetDataPoints = [];
if (isset($userData['budget']) && $userData['budget'] > 0) {
- $budget = $userData['budget'];
- $budgetLeft = $budget - $totalCostPerMonth;
- $budgetLeft = $budgetLeft < 0 ? 0 : $budgetLeft;
- $budgetUsed = ($totalCostPerMonth / $budget) * 100;
- $budgetUsed = $budgetUsed > 100 ? 100 : $budgetUsed;
- if ($totalCostPerMonth > $budget) {
- $overBudgetAmount = $totalCostPerMonth - $budget;
+ $monthlyBudget = $userData['budget'];
+ $monthlyBudgetLeft = max(0, $monthlyBudget - $totalCostPerMonth);
+ $monthlyBudgetUsed = min(100, ($totalCostPerMonth / $monthlyBudget) * 100);
+ if ($totalCostPerMonth > $monthlyBudget) {
+ $monthlyOverBudgetAmount = $totalCostPerMonth - $monthlyBudget;
}
- $showVsBudgetGraph = true;
- $vsBudgetDataPoints = [
+ $showVsMonthlyBudgetGraph = true;
+ $vsMonthlyBudgetDataPoints = [
[
"label" => translate('budget_remaining', $i18n),
- "y" => $budgetLeft,
+ "y" => $monthlyBudgetLeft,
],
[
- "label" => translate('total_cost', $i18n),
+ "label" => translate('monthly_cost', $i18n),
"y" => $totalCostPerMonth,
],
];
+ // Backwards compatibility for pages still referencing legacy monthly budget variables.
+ $budget = $monthlyBudget;
+ $budgetLeft = $monthlyBudgetLeft;
+ $budgetUsed = $monthlyBudgetUsed;
+ $overBudgetAmount = $monthlyOverBudgetAmount ?? 0;
}
+$showVsPeriodBudgetGraph = false;
+$vsPeriodBudgetDataPoints = [];
+if ($periodDiffersFromCalendarMonth && isset($userData['period_budget']) && $userData['period_budget'] > 0) {
+ $periodBudget = $userData['period_budget'];
+ $periodBudgetLeft = max(0, $periodBudget - $amountNeededThisPeriod);
+ $periodBudgetUsed = min(100, ($amountNeededThisPeriod / $periodBudget) * 100);
+ if ($amountNeededThisPeriod > $periodBudget) {
+ $periodOverBudgetAmount = $amountNeededThisPeriod - $periodBudget;
+ }
+ $showVsPeriodBudgetGraph = true;
+ $vsPeriodBudgetDataPoints = [
+ [
+ "label" => translate('budget_remaining', $i18n),
+ "y" => $periodBudgetLeft,
+ ],
+ [
+ "label" => translate('amount_needed_this_period', $i18n),
+ "y" => $amountNeededThisPeriod,
+ ],
+ ];
+}
+
+// Backwards compatibility for pages still referencing legacy graph variables.
+$showVsBudgetGraph = $showVsMonthlyBudgetGraph;
+$vsBudgetDataPoints = $vsMonthlyBudgetDataPoints;
+
$showCantConverErrorMessage = false;
if ($usesMultipleCurrencies) {
$query = "SELECT api_key FROM fixer WHERE user_id = :userId";
diff --git a/includes/version.php b/includes/version.php
index 0834a3b..3b45054 100644
--- a/includes/version.php
+++ b/includes/version.php
@@ -1,3 +1,3 @@
<?php
-$version = "v5.2.0";
+$version = "v5.3.0";
?>
diff --git a/index.php b/index.php
index 2871bb4..cc4b8eb 100644
--- a/index.php
+++ b/index.php
@@ -256,57 +256,110 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
<?php } ?>
- <?php if (isset($amountDueThisMonth) || isset($budget) || isset($budgetUsed) || isset($budgetLeft) || isset($overBudgetAmount)) { ?>
+ <?php if (isset($totalCostPerMonth)) { ?>
<div class="budget-subscriptions">
- <h2><?= translate('your_budget', $i18n) ?></h2>
+ <h2><?= translate('monthly_budget', $i18n) ?></h2>
<div class="dashboard-subscriptions-container">
<div class="dashboard-subscriptions-list">
- <?php if (isset($amountDueThisMonth)) { ?>
- <div class="subscription-item thin">
- <p class="subscription-item-title"><?= translate("amount_due", $i18n) ?></p>
- <div class="subscription-item-info">
- <p class="subscription-item-value">
- <?= CurrencyFormatter::format($amountDueThisMonth, $currencies[$userData['main_currency']]['code']) ?>
- </p>
- </div>
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("monthly_cost", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= CurrencyFormatter::format($totalCostPerMonth, $currencies[$userData['main_currency']]['code']) ?>
+ </p>
</div>
- <?php } ?>
- <?php if (isset($budget) && $budget > 0) { ?>
+ </div>
+ <?php if (isset($monthlyBudget) && $monthlyBudget > 0) { ?>
<div class="subscription-item thin">
<p class="subscription-item-title"><?= translate("budget", $i18n) ?></p>
<div class="subscription-item-info">
<p class="subscription-item-value">
- <?= formatPrice($budget, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ <?= formatPrice($monthlyBudget, $currencies[$userData['main_currency']]['code'], $currencies) ?>
</p>
</div>
</div>
- <?php } ?>
- <?php if (isset($budgetUsed)) { ?>
+ <?php if (isset($monthlyBudgetUsed)) { ?>
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("budget_used", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= number_format($monthlyBudgetUsed, 2) ?>%
+ </p>
+ </div>
+ </div>
+ <?php } ?>
<div class="subscription-item thin">
- <p class="subscription-item-title"><?= translate("budget_used", $i18n) ?></p>
+ <p class="subscription-item-title"><?= translate("budget_remaining", $i18n) ?></p>
<div class="subscription-item-info">
<p class="subscription-item-value">
- <?= number_format($budgetUsed, 2) ?>%
+ <?= formatPrice($monthlyBudgetLeft, $currencies[$userData['main_currency']]['code'], $currencies) ?>
</p>
</div>
</div>
+ <?php if (isset($monthlyOverBudgetAmount) && $monthlyOverBudgetAmount > 0) { ?>
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("over_budget", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= formatPrice($monthlyOverBudgetAmount, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ </p>
+ </div>
+ </div>
+ <?php } ?>
<?php } ?>
- <?php if (isset($budgetLeft)) { ?>
+ </div>
+ </div>
+ </div>
+ <?php } ?>
+
+ <?php if (isset($periodBudget) && $periodBudget > 0) { ?>
+ <div class="budget-subscriptions">
+ <h2><?= translate('period_budget', $i18n) ?></h2>
+ <?php if (isset($budgetPeriodLabel)) { ?>
+ <p class="header-subtitle"><?= translate('current_period', $i18n) ?>: <?= htmlspecialchars($budgetPeriodLabel, ENT_QUOTES, 'UTF-8') ?></p>
+ <?php } ?>
+ <div class="dashboard-subscriptions-container">
+ <div class="dashboard-subscriptions-list">
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("amount_needed_this_period", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= CurrencyFormatter::format($amountNeededThisPeriod, $currencies[$userData['main_currency']]['code']) ?>
+ </p>
+ </div>
+ </div>
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("budget", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= formatPrice($periodBudget, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ </p>
+ </div>
+ </div>
+ <?php if (isset($periodBudgetUsed)) { ?>
<div class="subscription-item thin">
- <p class="subscription-item-title"><?= translate("budget_remaining", $i18n) ?></p>
+ <p class="subscription-item-title"><?= translate("budget_used", $i18n) ?></p>
<div class="subscription-item-info">
<p class="subscription-item-value">
- <?= formatPrice($budgetLeft, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ <?= number_format($periodBudgetUsed, 2) ?>%
</p>
</div>
</div>
<?php } ?>
- <?php if (isset($overBudgetAmount) && $overBudgetAmount > 0) { ?>
+ <div class="subscription-item thin">
+ <p class="subscription-item-title"><?= translate("budget_remaining", $i18n) ?></p>
+ <div class="subscription-item-info">
+ <p class="subscription-item-value">
+ <?= formatPrice($periodBudgetLeft, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ </p>
+ </div>
+ </div>
+ <?php if (isset($periodOverBudgetAmount) && $periodOverBudgetAmount > 0) { ?>
<div class="subscription-item thin">
<p class="subscription-item-title"><?= translate("over_budget", $i18n) ?></p>
<div class="subscription-item-info">
<p class="subscription-item-value">
- <?= formatPrice($overBudgetAmount, $currencies[$userData['main_currency']]['code'], $currencies) ?>
+ <?= formatPrice($periodOverBudgetAmount, $currencies[$userData['main_currency']]['code'], $currencies) ?>
</p>
</div>
</div>
diff --git a/migrations/000053.php b/migrations/000053.php
new file mode 100644
index 0000000..d577721
--- /dev/null
+++ b/migrations/000053.php
@@ -0,0 +1,39 @@
+<?php
+
+// This migration adds support for payment-period budgeting.
+// It adds a "period_summary_at_period_start" column to the "notification_settings" table.
+// It also adds "budget_period_type", "budget_period_anchor_date" and "period_budget" columns to the "user" table.
+
+$columnQuery = $db->query("SELECT * FROM pragma_table_info('notification_settings') WHERE name='period_summary_at_period_start'");
+if ($columnQuery->fetchArray(SQLITE3_ASSOC) === false) {
+ $db->exec('ALTER TABLE notification_settings ADD COLUMN period_summary_at_period_start INTEGER DEFAULT 0');
+}
+
+$db->exec('UPDATE notification_settings
+ SET period_summary_at_period_start = 0
+ WHERE period_summary_at_period_start IS NULL');
+
+$defaultAnchorDate = (new DateTime('now'))->format('Y-m-d');
+
+$periodTypeColumn = $db->query("SELECT * FROM pragma_table_info('user') WHERE name='budget_period_type'");
+if ($periodTypeColumn->fetchArray(SQLITE3_ASSOC) === false) {
+ $db->exec('ALTER TABLE user ADD COLUMN budget_period_type TEXT DEFAULT "monthly"');
+}
+
+$anchorDateColumn = $db->query("SELECT * FROM pragma_table_info('user') WHERE name='budget_period_anchor_date'");
+if ($anchorDateColumn->fetchArray(SQLITE3_ASSOC) === false) {
+ $db->exec('ALTER TABLE user ADD COLUMN budget_period_anchor_date TEXT DEFAULT "' . $defaultAnchorDate . '"');
+}
+
+$periodBudgetColumn = $db->query("SELECT * FROM pragma_table_info('user') WHERE name='period_budget'");
+if ($periodBudgetColumn->fetchArray(SQLITE3_ASSOC) === false) {
+ $db->exec('ALTER TABLE user ADD COLUMN period_budget REAL DEFAULT 0');
+}
+
+$db->exec("UPDATE user SET budget_period_type = 'monthly' WHERE budget_period_type IS NULL OR budget_period_type = ''");
+$db->exec("UPDATE user SET budget_period_anchor_date = '" . $defaultAnchorDate . "' WHERE budget_period_anchor_date IS NULL OR budget_period_anchor_date = '' OR budget_period_anchor_date = '1970-01-01'");
+
+// Seed period_budget from existing budget for existing users
+$db->exec("UPDATE user SET period_budget = budget WHERE (period_budget IS NULL OR period_budget = 0) AND budget > 0");
+
+?>
diff --git a/scripts/i18n/ca.js b/scripts/i18n/ca.js
index 446e952..a73bfe5 100644
--- a/scripts/i18n/ca.js
+++ b/scripts/i18n/ca.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Error al recarregar la subscripció:",
- error_fetching_image_results: "Error al obtenir resultats d'imatges:",
- subscription_deleted: "Subscripció eliminada",
- error_deleting_subscription: "Error al eliminar la subscripció",
- failed_to_load_subscription: "Error al carregar la subscripció",
- edit_subscription: "Editar Subscripció",
- add_subscription: "Afegir Subscripció",
- confirm_delete_subscription: "¿Segur que vols eliminar aquesta subscripció?",
- // Settings
- network_response_error: "Error en la resposta de la xarxa",
- failed_add_member: "Error al afegir membre",
- member: "Membre",
- email: "Correu electrònic",
- firstname: "Nom",
- lastname: "Cognom",
- save_member: "Desar membre",
- delete_member: "Eliminar membre",
- failed_remove_member: "Error al eliminar membre",
- failed_save_member: "Error al desar membre",
- failed_add_category: "Error al afegir categoria",
- category: "Categoria",
- save_category: "Desar categoria",
- delete_category: "Eliminar categoria",
- failed_remove_category: "Error al eliminar categoria",
- currency: "Divisa",
- currency_code: "Còdi de moneda",
- save_currency: "Desar divisa",
- delete_currency: "Eliminar divisa",
- failed_remove_currency: "Error al eliminar divisa",
- failed_save_currency: "Error al desar divisa",
- cant_disable_payment_in_use: "No es pot desactivar un mètode de pagament en ús",
- failed_save_payment_method: "Error al desar el mètode de pagament",
- unknown_error: "Error desconegut, si us plau prova-ho de nou.",
- error_saving_notification_data: "Error al desar les dades de notificació",
- error_sending_notification: "Error al enviar la notificació",
- delete_account_confirmation: "Segur que vols eliminar el teu compte?",
- this_will_delete_all_data: "S'eliminaran totes les teves dades i no es podran recuperar. Continuar?",
- success: "Èxit",
- copied_to_clipboard: "Copiat al porta-retalls",
- // Calendar
- price: "Preu",
- category: "Categoria",
- paid_by: "Pagat per",
- payment_method: "Mètode de pagment",
- notes: "Notes",
- export: "Exportar",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Error al recarregar la subscripció:",
+ error_fetching_image_results: "Error al obtenir resultats d'imatges:",
+ subscription_deleted: "Subscripció eliminada",
+ error_deleting_subscription: "Error al eliminar la subscripció",
+ failed_to_load_subscription: "Error al carregar la subscripció",
+ edit_subscription: "Editar Subscripció",
+ add_subscription: "Afegir Subscripció",
+ confirm_delete_subscription: "¿Segur que vols eliminar aquesta subscripció?",
+ // Settings
+ network_response_error: "Error en la resposta de la xarxa",
+ failed_add_member: "Error al afegir membre",
+ member: "Membre",
+ email: "Correu electrònic",
+ firstname: "Nom",
+ lastname: "Cognom",
+ save_member: "Desar membre",
+ delete_member: "Eliminar membre",
+ failed_remove_member: "Error al eliminar membre",
+ failed_save_member: "Error al desar membre",
+ failed_add_category: "Error al afegir categoria",
+ category: "Categoria",
+ save_category: "Desar categoria",
+ delete_category: "Eliminar categoria",
+ failed_remove_category: "Error al eliminar categoria",
+ currency: "Divisa",
+ currency_code: "Còdi de moneda",
+ save_currency: "Desar divisa",
+ delete_currency: "Eliminar divisa",
+ failed_remove_currency: "Error al eliminar divisa",
+ failed_save_currency: "Error al desar divisa",
+ cant_disable_payment_in_use: "No es pot desactivar un mètode de pagament en ús",
+ failed_save_payment_method: "Error al desar el mètode de pagament",
+ unknown_error: "Error desconegut, si us plau prova-ho de nou.",
+ error_saving_notification_data: "Error al desar les dades de notificació",
+ error_sending_notification: "Error al enviar la notificació",
+ delete_account_confirmation: "Segur que vols eliminar el teu compte?",
+ this_will_delete_all_data: "S'eliminaran totes les teves dades i no es podran recuperar. Continuar?",
+ success: "Èxit",
+ copied_to_clipboard: "Copiat al porta-retalls",
+ // Calendar
+ price: "Preu",
+ category: "Categoria",
+ paid_by: "Pagat per",
+ payment_method: "Mètode de pagment",
+ notes: "Notes",
+ export: "Exportar",
+ invalid_budget: "El pressupost ha de ser un número no negatiu",
+ invalid_budget_period: "Període de pressupost seleccionat no vàlid",
+ invalid_budget_anchor_date: "La data d'ancoratge ha de ser una data vàlida",
no_results_found: "No s'han trobat resultats",
-}
+}
diff --git a/scripts/i18n/cs.js b/scripts/i18n/cs.js
index 4670454..1555916 100644
--- a/scripts/i18n/cs.js
+++ b/scripts/i18n/cs.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Platební metoda",
notes: "Poznámky",
export: "Exportovat",
+ invalid_budget: "Rozpočet musí být nezáporné číslo",
+ invalid_budget_period: "Vybrané rozpočtové období je neplatné",
+ invalid_budget_anchor_date: "Počáteční datum musí být platné datum",
no_results_found: "Nebyly nalezeny žádné výsledky",
}
diff --git a/scripts/i18n/da.js b/scripts/i18n/da.js
index 36608e3..23985d9 100644
--- a/scripts/i18n/da.js
+++ b/scripts/i18n/da.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Betalingsmetode",
notes: "Noter",
export: "Eksportér",
+ invalid_budget: "Budgettet skal være et ikke-negativt tal",
+ invalid_budget_period: "Ugyldig budgetperiode valgt",
+ invalid_budget_anchor_date: "Startdatoen skal være en gyldig dato",
no_results_found: "Ingen resultater fundet",
}
diff --git a/scripts/i18n/de.js b/scripts/i18n/de.js
index f59ca94..42c5e11 100644
--- a/scripts/i18n/de.js
+++ b/scripts/i18n/de.js
@@ -1,52 +1,55 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Fehler beim Aktualisieren des Abonnements:",
- error_fetching_image_results: "Fehler beim Laden der Bilder:",
- subscription_deleted: "Abonnement gelöscht",
- error_deleting_subscription: "Fehler beim Löschen des Abonnements",
- failed_to_load_subscription: "Fehler beim Laden des Abonnements",
- edit_subscription: "Abonnement bearbeiten",
- add_subscription: "Abonnement hinzufügen",
- confirm_delete_subscription: "Sind Sie sicher, dass Sie dieses Abonnement löschen möchten?",
- // Settings
- network_response_error: "Netzwerkfehler",
- failed_add_member: "Hinzufügen von Mitglied fehlgeschlagen",
- member: "Mitglied",
- email: "E-Mail",
- firstname: "Vorname",
- lastname: "Nachname",
- save_member: "Mitglied speichern",
- delete_member: "Mitglied löschen",
- failed_remove_member: "Mitglied konnte nicht gelöscht werden",
- failed_save_member: "Mitglied konnte nicht gespeichert werden",
- failed_add_category: "Kategorie konnte nicht hinzugefügt werden",
- category: "Kategorie",
- save_category: "Kategorie speichern",
- delete_category: "Kategorie löschen",
- failed_remove_category: "Kategorie konnte nicht gelöscht werden",
- currency: "Währung",
- currency_code: "Währungscode",
- save_currency: "Währung speichern",
- delete_currency: "Währung löschen",
- failed_remove_currency: "Währung konnte nicht gelöscht werden",
- failed_save_currency: "Währung konnte nicht gespeichert werden",
- cant_disable_payment_in_use:
- "Genutzte Währungen können nicht deaktiviert werden",
- failed_save_payment_method: "Zahlungsmethode konnte nicht gespeichert werden",
- unknown_error: "Unbekannter Fehler, bitte erneut versuchen.",
- error_saving_notification_data:
- "Fehler beim Speichern der Benachrichtigungsangaben",
- error_sending_notification: "Fehler beim Senden der Benachrichtigung",
- delete_account_confirmation: "Möchten Sie Ihr Konto wirklich löschen?",
- this_will_delete_all_data: "Dadurch werden alle Daten gelöscht und können nicht wiederhergestellt werden. Fortfahren?",
- success: "Erfolg",
- copied_to_clipboard: "In die Zwischenablage kopiert",
- // Calendar
- price: "Preis",
- category: "Kategorie",
- paid_by: "Bezahlt von",
- payment_method: "Zahlungsmethode",
- notes: "Notizen",
- export: "Exportieren",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Fehler beim Aktualisieren des Abonnements:",
+ error_fetching_image_results: "Fehler beim Laden der Bilder:",
+ subscription_deleted: "Abonnement gelöscht",
+ error_deleting_subscription: "Fehler beim Löschen des Abonnements",
+ failed_to_load_subscription: "Fehler beim Laden des Abonnements",
+ edit_subscription: "Abonnement bearbeiten",
+ add_subscription: "Abonnement hinzufügen",
+ confirm_delete_subscription: "Sind Sie sicher, dass Sie dieses Abonnement löschen möchten?",
+ // Settings
+ network_response_error: "Netzwerkfehler",
+ failed_add_member: "Hinzufügen von Mitglied fehlgeschlagen",
+ member: "Mitglied",
+ email: "E-Mail",
+ firstname: "Vorname",
+ lastname: "Nachname",
+ save_member: "Mitglied speichern",
+ delete_member: "Mitglied löschen",
+ failed_remove_member: "Mitglied konnte nicht gelöscht werden",
+ failed_save_member: "Mitglied konnte nicht gespeichert werden",
+ failed_add_category: "Kategorie konnte nicht hinzugefügt werden",
+ category: "Kategorie",
+ save_category: "Kategorie speichern",
+ delete_category: "Kategorie löschen",
+ failed_remove_category: "Kategorie konnte nicht gelöscht werden",
+ currency: "Währung",
+ currency_code: "Währungscode",
+ save_currency: "Währung speichern",
+ delete_currency: "Währung löschen",
+ failed_remove_currency: "Währung konnte nicht gelöscht werden",
+ failed_save_currency: "Währung konnte nicht gespeichert werden",
+ cant_disable_payment_in_use:
+ "Genutzte Währungen können nicht deaktiviert werden",
+ failed_save_payment_method: "Zahlungsmethode konnte nicht gespeichert werden",
+ unknown_error: "Unbekannter Fehler, bitte erneut versuchen.",
+ error_saving_notification_data:
+ "Fehler beim Speichern der Benachrichtigungsangaben",
+ error_sending_notification: "Fehler beim Senden der Benachrichtigung",
+ delete_account_confirmation: "Möchten Sie Ihr Konto wirklich löschen?",
+ this_will_delete_all_data: "Dadurch werden alle Daten gelöscht und können nicht wiederhergestellt werden. Fortfahren?",
+ success: "Erfolg",
+ copied_to_clipboard: "In die Zwischenablage kopiert",
+ // Calendar
+ price: "Preis",
+ category: "Kategorie",
+ paid_by: "Bezahlt von",
+ payment_method: "Zahlungsmethode",
+ notes: "Notizen",
+ export: "Exportieren",
+ invalid_budget: "Das Budget muss eine nicht negative Zahl sein",
+ invalid_budget_period: "Ungültiger Budgetzeitraum ausgewählt",
+ invalid_budget_anchor_date: "Das Ankerdatum muss ein gültiges Datum sein",
no_results_found: "Keine Ergebnisse gefunden",
-}
+}
diff --git a/scripts/i18n/el.js b/scripts/i18n/el.js
index 3efe453..9c6f9fa 100644
--- a/scripts/i18n/el.js
+++ b/scripts/i18n/el.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Σφάλμα επαναφόρτωσης συνδρομής:",
- error_fetching_image_results: "Σφάλμα λήψης αποτελεσμάτων εικόνας:",
- subscription_deleted: "Η συνδρομή διαγράφηκε",
- error_deleting_subscription: "Σφάλμα διαγραφής συνδρομής",
- failed_to_load_subscription: "Απέτυχε η φόρτωση της συνδρομής",
- edit_subscription: "Επεξεργασία συνδρομής",
- add_subscription: "Προσθήκη συνδρομής",
- confirm_delete_subscription: "Είστε σίγουρος ότι θέλετε να διαγράψετε αυτή τη συνδρομή;",
- // Settings
- network_response_error: "Η ανταπόκριση του δικτύου δεν ήταν εντάξει",
- failed_add_member: "Αποτυχία προσθήκης μέλους",
- member: "Μέλος",
- email: "Email",
- firstname: "Ονομα",
- lastname: "Επώνυμο",
- save_member: "Αποθήκευση μέλους",
- delete_member: "Διαγραφή μέλους",
- failed_remove_member: "Αποτυχία διαγραφής μέλους",
- failed_save_member: "Αποτυχία αποθήκευσης μέλους",
- failed_add_category: "Αποτυχία προσθήκης μέλους",
- category: "Κατηγορία",
- save_category: "Αποθήκευση κατηγορίας",
- delete_category: "Διαγραφή κατηγορίας",
- failed_remove_category: "Αποτυχία διαγραφής κατηγορίας",
- currency: "Νόμισμα",
- currency_code: "Κωδικός νομίσματος",
- save_currency: "Αποθήκευση νομίσματος",
- delete_currency: "Διαγραφή νομίσματος",
- failed_remove_currency: "Αποτυχία διαγραφής νομίσματος",
- failed_save_currency: "Αποτυχία αποθήκευσης νομίσματος",
- cant_disable_payment_in_use: "Δεν ειναι εφικτή η απενεργοποίηση της πληρωμή που βρίσκεται σε χρήση",
- failed_save_payment_method: "Failed to save payment method",
- unknown_error: "Άγνωστο σφάλμα, προσπάθησε ξανά.",
- error_saving_notification_data: "Σφάλμα αποθήκευσης δεδομένων ειδοποίησης",
- error_sending_notification: "Σφάλμα αποστολής ειδοποίησης",
- delete_account_confirmation: "Είστε σίγουρος ότι θέλετε να διαγράψετε το λογαριασμό σας;",
- this_will_delete_all_data: "Αυτό θα διαγράψει όλα τα δεδομένα σας και δεν μπορεί να ανακτηθεί. Να συνεχίσω;",
- success: "Επιτυχία",
- copied_to_clipboard: "Αντιγράφηκε στο πρόχειρο",
- // Calendar
- price: "Τιμή",
- category: "Κατηγορία",
- paid_by: "Πληρώθηκε από",
- payment_method: "Μέθοδος πληρωμής",
- notes: "Σημειώσεις",
- export: "Εξαγωγή",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Σφάλμα επαναφόρτωσης συνδρομής:",
+ error_fetching_image_results: "Σφάλμα λήψης αποτελεσμάτων εικόνας:",
+ subscription_deleted: "Η συνδρομή διαγράφηκε",
+ error_deleting_subscription: "Σφάλμα διαγραφής συνδρομής",
+ failed_to_load_subscription: "Απέτυχε η φόρτωση της συνδρομής",
+ edit_subscription: "Επεξεργασία συνδρομής",
+ add_subscription: "Προσθήκη συνδρομής",
+ confirm_delete_subscription: "Είστε σίγουρος ότι θέλετε να διαγράψετε αυτή τη συνδρομή;",
+ // Settings
+ network_response_error: "Η ανταπόκριση του δικτύου δεν ήταν εντάξει",
+ failed_add_member: "Αποτυχία προσθήκης μέλους",
+ member: "Μέλος",
+ email: "Email",
+ firstname: "Ονομα",
+ lastname: "Επώνυμο",
+ save_member: "Αποθήκευση μέλους",
+ delete_member: "Διαγραφή μέλους",
+ failed_remove_member: "Αποτυχία διαγραφής μέλους",
+ failed_save_member: "Αποτυχία αποθήκευσης μέλους",
+ failed_add_category: "Αποτυχία προσθήκης μέλους",
+ category: "Κατηγορία",
+ save_category: "Αποθήκευση κατηγορίας",
+ delete_category: "Διαγραφή κατηγορίας",
+ failed_remove_category: "Αποτυχία διαγραφής κατηγορίας",
+ currency: "Νόμισμα",
+ currency_code: "Κωδικός νομίσματος",
+ save_currency: "Αποθήκευση νομίσματος",
+ delete_currency: "Διαγραφή νομίσματος",
+ failed_remove_currency: "Αποτυχία διαγραφής νομίσματος",
+ failed_save_currency: "Αποτυχία αποθήκευσης νομίσματος",
+ cant_disable_payment_in_use: "Δεν ειναι εφικτή η απενεργοποίηση της πληρωμή που βρίσκεται σε χρήση",
+ failed_save_payment_method: "Failed to save payment method",
+ unknown_error: "Άγνωστο σφάλμα, προσπάθησε ξανά.",
+ error_saving_notification_data: "Σφάλμα αποθήκευσης δεδομένων ειδοποίησης",
+ error_sending_notification: "Σφάλμα αποστολής ειδοποίησης",
+ delete_account_confirmation: "Είστε σίγουρος ότι θέλετε να διαγράψετε το λογαριασμό σας;",
+ this_will_delete_all_data: "Αυτό θα διαγράψει όλα τα δεδομένα σας και δεν μπορεί να ανακτηθεί. Να συνεχίσω;",
+ success: "Επιτυχία",
+ copied_to_clipboard: "Αντιγράφηκε στο πρόχειρο",
+ // Calendar
+ price: "Τιμή",
+ category: "Κατηγορία",
+ paid_by: "Πληρώθηκε από",
+ payment_method: "Μέθοδος πληρωμής",
+ notes: "Σημειώσεις",
+ export: "Εξαγωγή",
+ invalid_budget: "Ο προϋπολογισμός πρέπει να είναι μη αρνητικός αριθμός",
+ invalid_budget_period: "Επιλέχθηκε μη έγκυρη περίοδος προϋπολογισμού",
+ invalid_budget_anchor_date: "Η ημερομηνία αναφοράς πρέπει να είναι έγκυρη ημερομηνία",
no_results_found: "Δεν βρέθηκαν αποτελέσματα",
-}
+}
diff --git a/scripts/i18n/en.js b/scripts/i18n/en.js
index 97fea47..5272a73 100644
--- a/scripts/i18n/en.js
+++ b/scripts/i18n/en.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Payment method",
notes: "Notes",
export: "Export",
- no_results_found: "No results found",
+ no_results_found: "No results found",
+ invalid_budget: "Budget must be a non-negative number",
+ invalid_budget_period: "Invalid budget period selected",
+ invalid_budget_anchor_date: "Anchor date must be a valid date",
}
diff --git a/scripts/i18n/es.js b/scripts/i18n/es.js
index c45ac19..e1923b7 100644
--- a/scripts/i18n/es.js
+++ b/scripts/i18n/es.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Error al recargar la suscripción:",
- error_fetching_image_results: "Error al obtener resultados de imágenes:",
- subscription_deleted: "Suscripción eliminada",
- error_deleting_subscription: "Error al eliminar la suscripción",
- failed_to_load_subscription: "Error al cargar la suscripción",
- edit_subscription: "Editar suscripción",
- add_subscription: "Añadir suscripción",
- confirm_delete_subscription: "¿Estás seguro de que quieres eliminar esta suscripción?",
- // Settings
- network_response_error: "Error en la respuesta de la red",
- failed_add_member: "Error al añadir miembro",
- member: "Miembro",
- email: "Correo electrónico",
- firstname: "Nombre de pila",
- lastname: "Apellido",
- save_member: "Guardar miembro",
- delete_member: "Eliminar miembro",
- failed_remove_member: "Error al eliminar miembro",
- failed_save_member: "Error al guardar miembro",
- failed_add_category: "Error al añadir categoría",
- category: "Categoría",
- save_category: "Guardar categoría",
- delete_category: "Eliminar categoría",
- failed_remove_category: "Error al eliminar categoría",
- currency: "Moneda",
- currency_code: "Código de moneda",
- save_currency: "Guardar moneda",
- delete_currency: "Eliminar moneda",
- failed_remove_currency: "Error al eliminar moneda",
- failed_save_currency: "Error al guardar moneda",
- cant_disable_payment_in_use: "No se puede desactivar el método de pago en uso",
- failed_save_payment_method: "Error al guardar el método de pago",
- unknown_error: "Error desconocido, por favor inténtalo de nuevo.",
- error_saving_notification_data: "Error al guardar los datos de notificación",
- error_sending_notification: "Error al enviar la notificación",
- delete_account_confirmation: "¿Estás seguro de que quieres eliminar tu cuenta?",
- this_will_delete_all_data: "Esto eliminará todos tus datos y no se podrán recuperar. ¿Continuar?",
- success: "Éxito",
- copied_to_clipboard: "Copiado al portapapeles",
- // Calendar
- price: "Precio",
- category: "Categoría",
- paid_by: "Pagado por",
- payment_method: "Método de pago",
- notes: "Notas",
- export: "Exportar",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Error al recargar la suscripción:",
+ error_fetching_image_results: "Error al obtener resultados de imágenes:",
+ subscription_deleted: "Suscripción eliminada",
+ error_deleting_subscription: "Error al eliminar la suscripción",
+ failed_to_load_subscription: "Error al cargar la suscripción",
+ edit_subscription: "Editar suscripción",
+ add_subscription: "Añadir suscripción",
+ confirm_delete_subscription: "¿Estás seguro de que quieres eliminar esta suscripción?",
+ // Settings
+ network_response_error: "Error en la respuesta de la red",
+ failed_add_member: "Error al añadir miembro",
+ member: "Miembro",
+ email: "Correo electrónico",
+ firstname: "Nombre de pila",
+ lastname: "Apellido",
+ save_member: "Guardar miembro",
+ delete_member: "Eliminar miembro",
+ failed_remove_member: "Error al eliminar miembro",
+ failed_save_member: "Error al guardar miembro",
+ failed_add_category: "Error al añadir categoría",
+ category: "Categoría",
+ save_category: "Guardar categoría",
+ delete_category: "Eliminar categoría",
+ failed_remove_category: "Error al eliminar categoría",
+ currency: "Moneda",
+ currency_code: "Código de moneda",
+ save_currency: "Guardar moneda",
+ delete_currency: "Eliminar moneda",
+ failed_remove_currency: "Error al eliminar moneda",
+ failed_save_currency: "Error al guardar moneda",
+ cant_disable_payment_in_use: "No se puede desactivar el método de pago en uso",
+ failed_save_payment_method: "Error al guardar el método de pago",
+ unknown_error: "Error desconocido, por favor inténtalo de nuevo.",
+ error_saving_notification_data: "Error al guardar los datos de notificación",
+ error_sending_notification: "Error al enviar la notificación",
+ delete_account_confirmation: "¿Estás seguro de que quieres eliminar tu cuenta?",
+ this_will_delete_all_data: "Esto eliminará todos tus datos y no se podrán recuperar. ¿Continuar?",
+ success: "Éxito",
+ copied_to_clipboard: "Copiado al portapapeles",
+ // Calendar
+ price: "Precio",
+ category: "Categoría",
+ paid_by: "Pagado por",
+ payment_method: "Método de pago",
+ notes: "Notas",
+ export: "Exportar",
+ invalid_budget: "El presupuesto debe ser un número no negativo",
+ invalid_budget_period: "Periodo de presupuesto seleccionado no válido",
+ invalid_budget_anchor_date: "La fecha de referencia debe ser una fecha válida",
no_results_found: "No se encontraron resultados",
-}
+}
diff --git a/scripts/i18n/fr.js b/scripts/i18n/fr.js
index b9812c6..811a0f4 100644
--- a/scripts/i18n/fr.js
+++ b/scripts/i18n/fr.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Méthode de paiement",
notes: "Notes",
export: "Exporter",
+ invalid_budget: "Le budget doit être un nombre non négatif",
+ invalid_budget_period: "Période de budget sélectionnée invalide",
+ invalid_budget_anchor_date: "La date de référence doit être une date valide",
no_results_found: "Aucun résultat trouvé",
};
diff --git a/scripts/i18n/hu.js b/scripts/i18n/hu.js
index 49f7ce1..780e51f 100644
--- a/scripts/i18n/hu.js
+++ b/scripts/i18n/hu.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Fizetési mód",
notes: "Jegyzetek",
export: "Exportálás",
+ invalid_budget: "A költségvetésnek nem negatív számnak kell lennie",
+ invalid_budget_period: "Érvénytelen költségvetési időszak lett kiválasztva",
+ invalid_budget_anchor_date: "A kezdő dátumnak érvényes dátumnak kell lennie",
no_results_found: "Nincs találat",
}
diff --git a/scripts/i18n/id.js b/scripts/i18n/id.js
index 96ff2b2..2f8d876 100644
--- a/scripts/i18n/id.js
+++ b/scripts/i18n/id.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Metode pembayaran",
notes: "Catatan",
export: "Ekspor",
+ invalid_budget: "Anggaran harus berupa angka non-negatif",
+ invalid_budget_period: "Periode anggaran yang dipilih tidak valid",
+ invalid_budget_anchor_date: "Tanggal acuan harus berupa tanggal yang valid",
no_results_found: "Tidak ada hasil ditemukan",
}
diff --git a/scripts/i18n/it.js b/scripts/i18n/it.js
index cfc3a52..c6c61f0 100644
--- a/scripts/i18n/it.js
+++ b/scripts/i18n/it.js
@@ -1,51 +1,54 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Errore nel ricaricare l'abbonamento:",
- error_fetching_image_results: "Errore nel recupero delle immagini:",
- subscription_deleted: "Abbonamento eliminato",
- error_deleting_subscription: "Errore nell'eliminare l'abbonamento",
- failed_to_load_subscription: "Caricamento dell'abbonamento non riuscito",
- edit_subscription: "Modifica abbonamento",
- add_subscription: "Aggiungi abbonamento",
- confirm_delete_subscription: "Sei sicuro di voler eliminare questo abbonamento?",
-
- // Settings
- network_response_error: "Si è verificato un errore nella risposta del server",
- failed_add_member: "Impossibile aggiungere il membro",
- member: "Membro",
- email: "Email",
- firstname: "Nome di battesimo",
- lastname: "Cognome",
- save_member: "Salva membro",
- delete_member: "Elimina membro",
- failed_remove_member: "Impossibile rimuovere il membro",
- failed_save_member: "Impossibile salvare il membro",
- failed_add_category: "Impossibile aggiungere la categoria",
- category: "Categoria",
- save_category: "Salva categoria",
- delete_category: "Elimina categoria",
- failed_remove_category: "Impossibile rimuovere la categoria",
- currency: "Valuta",
- currency_code: "Codice valuta",
- save_currency: "Salva valuta",
- delete_currency: "Elimina valuta",
- failed_remove_currency: "Impossibile rimuovere la valuta",
- failed_save_currency: "Impossibile salvare la valuta",
- cant_disable_payment_in_use: "Impossibile disabilitare il pagamento in uso",
- failed_save_payment_method: "Impossibile salvare il metodo di pagamento",
- unknown_error: "Errore sconosciuto, si prega di riprovare.",
- error_saving_notification_data: "Errore nel salvataggio delle impostazioni di notifica",
- error_sending_notification: "Errore nell'invio della notifica",
- delete_account_confirmation: "Sei sicuro di voler eliminare il tuo account?",
- this_will_delete_all_data: "Questo eliminerà tutti i tuoi dati e non potrà essere annullato. Continuare?",
- success: "Successo",
- copied_to_clipboard: "Copiato negli appunti",
- // Calendar
- price: "Prezzo",
- category: "Categoria",
- paid_by: "Pagato da",
- payment_method: "Metodo di pagamento",
- notes: "Note",
- export: "Esporta",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Errore nel ricaricare l'abbonamento:",
+ error_fetching_image_results: "Errore nel recupero delle immagini:",
+ subscription_deleted: "Abbonamento eliminato",
+ error_deleting_subscription: "Errore nell'eliminare l'abbonamento",
+ failed_to_load_subscription: "Caricamento dell'abbonamento non riuscito",
+ edit_subscription: "Modifica abbonamento",
+ add_subscription: "Aggiungi abbonamento",
+ confirm_delete_subscription: "Sei sicuro di voler eliminare questo abbonamento?",
+
+ // Settings
+ network_response_error: "Si è verificato un errore nella risposta del server",
+ failed_add_member: "Impossibile aggiungere il membro",
+ member: "Membro",
+ email: "Email",
+ firstname: "Nome di battesimo",
+ lastname: "Cognome",
+ save_member: "Salva membro",
+ delete_member: "Elimina membro",
+ failed_remove_member: "Impossibile rimuovere il membro",
+ failed_save_member: "Impossibile salvare il membro",
+ failed_add_category: "Impossibile aggiungere la categoria",
+ category: "Categoria",
+ save_category: "Salva categoria",
+ delete_category: "Elimina categoria",
+ failed_remove_category: "Impossibile rimuovere la categoria",
+ currency: "Valuta",
+ currency_code: "Codice valuta",
+ save_currency: "Salva valuta",
+ delete_currency: "Elimina valuta",
+ failed_remove_currency: "Impossibile rimuovere la valuta",
+ failed_save_currency: "Impossibile salvare la valuta",
+ cant_disable_payment_in_use: "Impossibile disabilitare il pagamento in uso",
+ failed_save_payment_method: "Impossibile salvare il metodo di pagamento",
+ unknown_error: "Errore sconosciuto, si prega di riprovare.",
+ error_saving_notification_data: "Errore nel salvataggio delle impostazioni di notifica",
+ error_sending_notification: "Errore nell'invio della notifica",
+ delete_account_confirmation: "Sei sicuro di voler eliminare il tuo account?",
+ this_will_delete_all_data: "Questo eliminerà tutti i tuoi dati e non potrà essere annullato. Continuare?",
+ success: "Successo",
+ copied_to_clipboard: "Copiato negli appunti",
+ // Calendar
+ price: "Prezzo",
+ category: "Categoria",
+ paid_by: "Pagato da",
+ payment_method: "Metodo di pagamento",
+ notes: "Note",
+ export: "Esporta",
+ invalid_budget: "Il budget deve essere un numero non negativo",
+ invalid_budget_period: "Periodo di budget selezionato non valido",
+ invalid_budget_anchor_date: "La data di ancoraggio deve essere una data valida",
no_results_found: "Nessun risultato trovato",
-}
+}
diff --git a/scripts/i18n/ja.js b/scripts/i18n/ja.js
index 49954c7..e9febbf 100644
--- a/scripts/i18n/ja.js
+++ b/scripts/i18n/ja.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "定期購入の再読み込みエラー:",
- error_fetching_image_results: "画像取得結果エラー:",
- subscription_deleted: "定期購入の削除",
- error_deleting_subscription: "定期購入の削除エラー",
- failed_to_load_subscription: "定期購入の読み込みに失敗しました",
- edit_subscription: "定期購入の編集",
- add_subscription: "定期購入の追加",
- confirm_delete_subscription: "この定期購入を削除してもよろしいですか?",
- // Settings
- network_response_error: "ネットワークの応答異常",
- failed_add_member: "世帯員の追加に失敗",
- member: "世帯員",
- email: "メール",
- firstname: "ファーストネーム",
- lastname: "苗字",
- save_member: "世帯員の保存",
- delete_member: "世帯員の削除",
- failed_remove_member: "世帯員の削除に失敗",
- failed_save_member: "世帯員の削除に失敗",
- failed_add_category: "カテゴリの追加に失敗",
- category: "カテゴリ",
- save_category: "カテゴリの保存",
- delete_category: "カテゴリの削除",
- failed_remove_category: "カテゴリの削除に失敗",
- currency: "通貨",
- currency_code: "通貨コード",
- save_currency: "通貨の保存",
- delete_currency: "通貨の削除",
- failed_remove_currency: "通貨の削除に失敗",
- failed_save_currency: "通貨の保存に失敗",
- cant_disable_payment_in_use: "使用中の支払いは無効にできません",
- failed_save_payment_method: "支払い方法の保存に失敗",
- unknown_error: "不明なエラー。もう一度試してください。",
- error_saving_notification_data: "通知データの保存エラー",
- error_sending_notification: "通知の送信エラー",
- delete_account_confirmation: "アカウントを削除してもよろしいですか?",
- this_will_delete_all_data: "これによりすべてのデータが削除され、元に戻すことはできません。続行しますか?",
- success: "成功",
- copied_to_clipboard: "クリップボードにコピーされました",
- // Calendar
- price: "価格",
- category: "カテゴリ",
- paid_by: "支払い者",
- payment_method: "支払い方法",
- notes: "メモ",
- export: "エクスポート",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "定期購入の再読み込みエラー:",
+ error_fetching_image_results: "画像取得結果エラー:",
+ subscription_deleted: "定期購入の削除",
+ error_deleting_subscription: "定期購入の削除エラー",
+ failed_to_load_subscription: "定期購入の読み込みに失敗しました",
+ edit_subscription: "定期購入の編集",
+ add_subscription: "定期購入の追加",
+ confirm_delete_subscription: "この定期購入を削除してもよろしいですか?",
+ // Settings
+ network_response_error: "ネットワークの応答異常",
+ failed_add_member: "世帯員の追加に失敗",
+ member: "世帯員",
+ email: "メール",
+ firstname: "ファーストネーム",
+ lastname: "苗字",
+ save_member: "世帯員の保存",
+ delete_member: "世帯員の削除",
+ failed_remove_member: "世帯員の削除に失敗",
+ failed_save_member: "世帯員の削除に失敗",
+ failed_add_category: "カテゴリの追加に失敗",
+ category: "カテゴリ",
+ save_category: "カテゴリの保存",
+ delete_category: "カテゴリの削除",
+ failed_remove_category: "カテゴリの削除に失敗",
+ currency: "通貨",
+ currency_code: "通貨コード",
+ save_currency: "通貨の保存",
+ delete_currency: "通貨の削除",
+ failed_remove_currency: "通貨の削除に失敗",
+ failed_save_currency: "通貨の保存に失敗",
+ cant_disable_payment_in_use: "使用中の支払いは無効にできません",
+ failed_save_payment_method: "支払い方法の保存に失敗",
+ unknown_error: "不明なエラー。もう一度試してください。",
+ error_saving_notification_data: "通知データの保存エラー",
+ error_sending_notification: "通知の送信エラー",
+ delete_account_confirmation: "アカウントを削除してもよろしいですか?",
+ this_will_delete_all_data: "これによりすべてのデータが削除され、元に戻すことはできません。続行しますか?",
+ success: "成功",
+ copied_to_clipboard: "クリップボードにコピーされました",
+ // Calendar
+ price: "価格",
+ category: "カテゴリ",
+ paid_by: "支払い者",
+ payment_method: "支払い方法",
+ notes: "メモ",
+ export: "エクスポート",
+ invalid_budget: "予算は0以上の数値である必要があります",
+ invalid_budget_period: "選択した予算期間が無効です",
+ invalid_budget_anchor_date: "基準日は有効な日付である必要があります",
no_results_found: "結果が見つかりません",
-}
+}
diff --git a/scripts/i18n/ko.js b/scripts/i18n/ko.js
index 0a77d6a..fb9d6bf 100644
--- a/scripts/i18n/ko.js
+++ b/scripts/i18n/ko.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "결제 수단",
notes: "메모",
export: "내보내기",
+ invalid_budget: "예산은 0 이상의 숫자여야 합니다",
+ invalid_budget_period: "선택한 예산 기간이 유효하지 않습니다",
+ invalid_budget_anchor_date: "기준 날짜는 유효한 날짜여야 합니다",
no_results_found: "결과를 찾을 수 없습니다",
};
diff --git a/scripts/i18n/nl.js b/scripts/i18n/nl.js
index 6c89279..1aee156 100644
--- a/scripts/i18n/nl.js
+++ b/scripts/i18n/nl.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Betaalmethode",
notes: "Notities",
export: "Exporteren",
+ invalid_budget: "Budget moet een niet-negatief getal zijn",
+ invalid_budget_period: "Ongeldige budgetperiode geselecteerd",
+ invalid_budget_anchor_date: "Startdatum moet een geldige datum zijn",
no_results_found: "Geen resultaten gevonden",
}
diff --git a/scripts/i18n/pl.js b/scripts/i18n/pl.js
index e78f398..2486c7b 100644
--- a/scripts/i18n/pl.js
+++ b/scripts/i18n/pl.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Błąd przeładowania subskrypcji:",
- error_fetching_image_results: "Błąd pobierania wyników obrazu:",
- subscription_deleted: "Subskrypcja usunięta",
- error_deleting_subscription: "Błąd usunięcia subskrypcji",
- failed_to_load_subscription: "Nie udało się załadować subskrypcji",
- edit_subscription: "Edytuj subskrypcję",
- add_subscription: "Dodaj subskrypcję",
- confirm_delete_subscription: "Czy na pewno chcesz usunąć tę subskrypcję?",
- // Settings
- network_response_error: "Odpowiedź sieciowa nie była prawidłowa",
- failed_add_member: "Nie udało się dodać użytkownika",
- member: "Użytkownik",
- email: "E-mail",
- firstname: "Imię",
- lastname: "Nazwisko",
- save_member: "Zapisz użytkownika",
- delete_member: "Usuń użytkownika",
- failed_remove_member: "Nie udało się usunąć użytkownika",
- failed_save_member: "Nie udało się zapisać użytkownika",
- failed_add_category: "Nie udało się dodać kategorii",
- category: "Kategoria",
- save_category: "Zapisz kategorię",
- delete_category: "Usuń kategorię",
- failed_remove_category: "Nie udało się usunąć kategorii",
- currency: "Waluta",
- currency_code: "Kod waluty",
- save_currency: "Zapisz walutę",
- delete_currency: "Usuń walutę",
- failed_remove_currency: "Nie udało się usunąć waluty",
- failed_save_currency: "Nie udało się zapisać waluty",
- cant_disable_payment_in_use: "Nie można wyłączyć płatności w użyciu",
- failed_save_payment_method: "Nie udało się zapisać metody płatności",
- unknown_error: "Nieznany błąd, spróbuj ponownie.",
- error_saving_notification_data: "Błąd zapisywania danych powiadomienia",
- error_sending_notification: "Błąd wysyłania powiadomienia",
- delete_account_confirmation: "Czy na pewno chcesz usunąć swoje konto?",
- this_will_delete_all_data: "Spowoduje to usunięcie wszystkich danych i nie będzie można tego cofnąć. Kontynuować?",
- success: "Sukces",
- copied_to_clipboard: "Skopiowano do schowka",
- // Calendar
- price: "Cena",
- category: "Kategoria",
- paid_by: "Zapłacone przez",
- payment_method: "Metoda płatności",
- notes: "Notatki",
- export: "Eksport",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Błąd przeładowania subskrypcji:",
+ error_fetching_image_results: "Błąd pobierania wyników obrazu:",
+ subscription_deleted: "Subskrypcja usunięta",
+ error_deleting_subscription: "Błąd usunięcia subskrypcji",
+ failed_to_load_subscription: "Nie udało się załadować subskrypcji",
+ edit_subscription: "Edytuj subskrypcję",
+ add_subscription: "Dodaj subskrypcję",
+ confirm_delete_subscription: "Czy na pewno chcesz usunąć tę subskrypcję?",
+ // Settings
+ network_response_error: "Odpowiedź sieciowa nie była prawidłowa",
+ failed_add_member: "Nie udało się dodać użytkownika",
+ member: "Użytkownik",
+ email: "E-mail",
+ firstname: "Imię",
+ lastname: "Nazwisko",
+ save_member: "Zapisz użytkownika",
+ delete_member: "Usuń użytkownika",
+ failed_remove_member: "Nie udało się usunąć użytkownika",
+ failed_save_member: "Nie udało się zapisać użytkownika",
+ failed_add_category: "Nie udało się dodać kategorii",
+ category: "Kategoria",
+ save_category: "Zapisz kategorię",
+ delete_category: "Usuń kategorię",
+ failed_remove_category: "Nie udało się usunąć kategorii",
+ currency: "Waluta",
+ currency_code: "Kod waluty",
+ save_currency: "Zapisz walutę",
+ delete_currency: "Usuń walutę",
+ failed_remove_currency: "Nie udało się usunąć waluty",
+ failed_save_currency: "Nie udało się zapisać waluty",
+ cant_disable_payment_in_use: "Nie można wyłączyć płatności w użyciu",
+ failed_save_payment_method: "Nie udało się zapisać metody płatności",
+ unknown_error: "Nieznany błąd, spróbuj ponownie.",
+ error_saving_notification_data: "Błąd zapisywania danych powiadomienia",
+ error_sending_notification: "Błąd wysyłania powiadomienia",
+ delete_account_confirmation: "Czy na pewno chcesz usunąć swoje konto?",
+ this_will_delete_all_data: "Spowoduje to usunięcie wszystkich danych i nie będzie można tego cofnąć. Kontynuować?",
+ success: "Sukces",
+ copied_to_clipboard: "Skopiowano do schowka",
+ // Calendar
+ price: "Cena",
+ category: "Kategoria",
+ paid_by: "Zapłacone przez",
+ payment_method: "Metoda płatności",
+ notes: "Notatki",
+ export: "Eksport",
+ invalid_budget: "Budżet musi być liczbą nieujemną",
+ invalid_budget_period: "Wybrano nieprawidłowy okres budżetowy",
+ invalid_budget_anchor_date: "Data odniesienia musi być prawidłową datą",
no_results_found: "Nie znaleziono wyników",
-}
+}
diff --git a/scripts/i18n/pt.js b/scripts/i18n/pt.js
index 6d4dca5..d448570 100644
--- a/scripts/i18n/pt.js
+++ b/scripts/i18n/pt.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: 'Erro ao carregar a subscrição:',
- error_fetching_image_results: 'Erro ao obter imagens:',
- subscription_deleted: 'Subscrição eliminada',
- error_deleting_subscription: 'Erro ao eliminar a subscrição',
- failed_to_load_subscription: 'Falha ao carregar a subscrição',
- edit_subscription: 'Editar subscrição',
- add_subscription: 'Adicionar subscrição',
- confirm_delete_subscription: 'Tem a certeza de que deseja eliminar esta subscrição?',
- // Settings
- network_response_error: 'Erro de resposta de rede',
- failed_add_member: 'Falha ao adicionar membro',
- member: 'Membro',
- email: 'Email',
- firstname: 'Nome próprio',
- lastname: 'Último nome',
- save_member: 'Guardar membro',
- delete_member: 'Remover membro',
- failed_remove_member: 'Erro ao remover membro',
- failed_save_member: 'Erro ao guardar membro',
- failed_add_category: 'Erro ao adicionar categoria',
- category: 'Categoria',
- save_category: 'Guardar categoria',
- delete_category: 'Remover categoria',
- failed_remove_category: 'Erro ao remover categoria',
- currency: 'Moeda',
- currency_code: 'Código de moeda',
- save_currency: 'Guardar moeda',
- delete_currency: 'Remover moeda',
- failed_remove_currency: 'Erro ao remover moeda',
- failed_save_currency: 'Erro ao guardar moeda',
- cant_disable_payment_in_use: 'Não é possível desativar pagamento em uso',
- failed_save_payment_method: 'Erro ao guardar método de pagamento',
- unknown_error: 'Erro desconhecido, por favor, tente novamente.',
- error_saving_notification_data: 'Erro ao guardar dados de notificação',
- error_sending_notification: 'Erro ao enviar notificação',
- delete_account_confirmation: "Tem a certeza de que deseja eliminar a sua conta?",
- this_will_delete_all_data: "Isto irá eliminar todos os seus dados e não poderão ser recuperados. Continuar?",
- success: "Sucesso",
- copied_to_clipboard: "Copiado para a área de transferência",
- // Calendar
- price: "Preço",
- category: "Categoria",
- paid_by: "Pago por",
- payment_method: "Método de pagamento",
- notes: "Notas",
- export: "Exportar",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: 'Erro ao carregar a subscrição:',
+ error_fetching_image_results: 'Erro ao obter imagens:',
+ subscription_deleted: 'Subscrição eliminada',
+ error_deleting_subscription: 'Erro ao eliminar a subscrição',
+ failed_to_load_subscription: 'Falha ao carregar a subscrição',
+ edit_subscription: 'Editar subscrição',
+ add_subscription: 'Adicionar subscrição',
+ confirm_delete_subscription: 'Tem a certeza de que deseja eliminar esta subscrição?',
+ // Settings
+ network_response_error: 'Erro de resposta de rede',
+ failed_add_member: 'Falha ao adicionar membro',
+ member: 'Membro',
+ email: 'Email',
+ firstname: 'Nome próprio',
+ lastname: 'Último nome',
+ save_member: 'Guardar membro',
+ delete_member: 'Remover membro',
+ failed_remove_member: 'Erro ao remover membro',
+ failed_save_member: 'Erro ao guardar membro',
+ failed_add_category: 'Erro ao adicionar categoria',
+ category: 'Categoria',
+ save_category: 'Guardar categoria',
+ delete_category: 'Remover categoria',
+ failed_remove_category: 'Erro ao remover categoria',
+ currency: 'Moeda',
+ currency_code: 'Código de moeda',
+ save_currency: 'Guardar moeda',
+ delete_currency: 'Remover moeda',
+ failed_remove_currency: 'Erro ao remover moeda',
+ failed_save_currency: 'Erro ao guardar moeda',
+ cant_disable_payment_in_use: 'Não é possível desativar pagamento em uso',
+ failed_save_payment_method: 'Erro ao guardar método de pagamento',
+ unknown_error: 'Erro desconhecido, por favor, tente novamente.',
+ error_saving_notification_data: 'Erro ao guardar dados de notificação',
+ error_sending_notification: 'Erro ao enviar notificação',
+ delete_account_confirmation: "Tem a certeza de que deseja eliminar a sua conta?",
+ this_will_delete_all_data: "Isto irá eliminar todos os seus dados e não poderão ser recuperados. Continuar?",
+ success: "Sucesso",
+ copied_to_clipboard: "Copiado para a área de transferência",
+ // Calendar
+ price: "Preço",
+ category: "Categoria",
+ paid_by: "Pago por",
+ payment_method: "Método de pagamento",
+ notes: "Notas",
+ export: "Exportar",
+ invalid_budget: "O orçamento deve ser um número não negativo",
+ invalid_budget_period: "Período de orçamento selecionado inválido",
+ invalid_budget_anchor_date: "A data de referência deve ser uma data válida",
no_results_found: "Nenhum resultado encontrado",
-};
+};
diff --git a/scripts/i18n/pt_br.js b/scripts/i18n/pt_br.js
index 2bfe3ef..b3eae1e 100644
--- a/scripts/i18n/pt_br.js
+++ b/scripts/i18n/pt_br.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Método de pagamento",
notes: "Notas",
export: "Exportar",
+ invalid_budget: "O orçamento deve ser um número não negativo",
+ invalid_budget_period: "Período de orçamento selecionado inválido",
+ invalid_budget_anchor_date: "A data de referência deve ser uma data válida",
no_results_found: "Nenhum resultado encontrado",
}
diff --git a/scripts/i18n/ro.js b/scripts/i18n/ro.js
index e871cbf..722d8ae 100644
--- a/scripts/i18n/ro.js
+++ b/scripts/i18n/ro.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: ",Metoda de plată",
notes: "Notițe",
export: "Export",
+ invalid_budget: "Bugetul trebuie să fie un număr nenegativ",
+ invalid_budget_period: "Perioadă de buget selectată nevalidă",
+ invalid_budget_anchor_date: "Data de referință trebuie să fie o dată validă",
no_results_found: "Nu s-au găsit rezultate",
}
diff --git a/scripts/i18n/ru.js b/scripts/i18n/ru.js
index 0ebde64..27c3d28 100644
--- a/scripts/i18n/ru.js
+++ b/scripts/i18n/ru.js
@@ -1,50 +1,53 @@
-let i18n = {
- // Dashboard
- error_reloading_subscription: "Ошибка перезагрузки подписки:",
- error_fetching_image_results: "Ошибка при получении результатов изображения:",
- subscription_deleted: "Подписка удалена",
- error_deleting_subscription: "Ошибка удаления подписки",
- failed_to_load_subscription: "Не удалось загрузить подписку",
- edit_subscription: "Изменить подписку",
- add_subscription: "Добавить подписку",
- confirm_delete_subscription: "Вы уверены, что хотите удалить эту подписку?",
- // Settings
- network_response_error: "Отсутствует сетевое соединение",
- failed_add_member: "Не удалось добавить пользователя",
- member: "Пользователь",
- email: "Электронная почта",
- firstname: "Имя",
- lastname: "Фамилия",
- save_member: "Сохранить пользователя",
- delete_member: "Удалить пользователя",
- failed_remove_member: "Не удалось удалить пользователя",
- failed_save_member: "Не удалось сохранить пользователя",
- failed_add_category: "Не удалось добавить категорию",
- category: "Категория",
- save_category: "Сохранить категорию",
- delete_category: "Удалить категорию",
- failed_remove_category: "Не удалось удалить категорию",
- currency: "Валюта",
- currency_code: "Код валюты",
- save_currency: "Сохранить валюту",
- delete_currency: "Удалить валюту",
- failed_remove_currency: "Не удалось удалить валюту.",
- failed_save_currency: "Не удалось сохранить валюту.",
- cant_disable_payment_in_use: "Невозможно отключить используемый платеж",
- failed_save_payment_method: "Не удалось сохранить способ оплаты.",
- unknown_error: "Неизвестная ошибка. Повторите попытку.",
- error_saving_notification_data: "Ошибка сохранения данных уведомления.",
- error_sending_notification: "Ошибка отправки уведомления",
- delete_account_confirmation: "Вы уверены, что хотите удалить свою учетную запись?",
- this_will_delete_all_data: "Это удалит все ваши данные и не может быть отменено. Продолжить?",
- success: "Успешно",
- copied_to_clipboard: "Скопировано в буфер обмена",
- // Calendar
- price: "Цена",
- category: "Категория",
- paid_by: "Оплачено",
- payment_method: "Способ оплаты",
- notes: "Примечания",
- export: "Экспорт",
+let i18n = {
+ // Dashboard
+ error_reloading_subscription: "Ошибка перезагрузки подписки:",
+ error_fetching_image_results: "Ошибка при получении результатов изображения:",
+ subscription_deleted: "Подписка удалена",
+ error_deleting_subscription: "Ошибка удаления подписки",
+ failed_to_load_subscription: "Не удалось загрузить подписку",
+ edit_subscription: "Изменить подписку",
+ add_subscription: "Добавить подписку",
+ confirm_delete_subscription: "Вы уверены, что хотите удалить эту подписку?",
+ // Settings
+ network_response_error: "Отсутствует сетевое соединение",
+ failed_add_member: "Не удалось добавить пользователя",
+ member: "Пользователь",
+ email: "Электронная почта",
+ firstname: "Имя",
+ lastname: "Фамилия",
+ save_member: "Сохранить пользователя",
+ delete_member: "Удалить пользователя",
+ failed_remove_member: "Не удалось удалить пользователя",
+ failed_save_member: "Не удалось сохранить пользователя",
+ failed_add_category: "Не удалось добавить категорию",
+ category: "Категория",
+ save_category: "Сохранить категорию",
+ delete_category: "Удалить категорию",
+ failed_remove_category: "Не удалось удалить категорию",
+ currency: "Валюта",
+ currency_code: "Код валюты",
+ save_currency: "Сохранить валюту",
+ delete_currency: "Удалить валюту",
+ failed_remove_currency: "Не удалось удалить валюту.",
+ failed_save_currency: "Не удалось сохранить валюту.",
+ cant_disable_payment_in_use: "Невозможно отключить используемый платеж",
+ failed_save_payment_method: "Не удалось сохранить способ оплаты.",
+ unknown_error: "Неизвестная ошибка. Повторите попытку.",
+ error_saving_notification_data: "Ошибка сохранения данных уведомления.",
+ error_sending_notification: "Ошибка отправки уведомления",
+ delete_account_confirmation: "Вы уверены, что хотите удалить свою учетную запись?",
+ this_will_delete_all_data: "Это удалит все ваши данные и не может быть отменено. Продолжить?",
+ success: "Успешно",
+ copied_to_clipboard: "Скопировано в буфер обмена",
+ // Calendar
+ price: "Цена",
+ category: "Категория",
+ paid_by: "Оплачено",
+ payment_method: "Способ оплаты",
+ notes: "Примечания",
+ export: "Экспорт",
+ invalid_budget: "Бюджет должен быть неотрицательным числом",
+ invalid_budget_period: "Выбран недопустимый бюджетный период",
+ invalid_budget_anchor_date: "Дата отсчёта должна быть действительной датой",
no_results_found: "Ничего не найдено",
-}
+}
diff --git a/scripts/i18n/sl.js b/scripts/i18n/sl.js
index b340479..9e3512b 100644
--- a/scripts/i18n/sl.js
+++ b/scripts/i18n/sl.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Način plačila",
notes: "Opombe",
export: "Izvozi",
+ invalid_budget: "Proračun mora biti nenegativno število",
+ invalid_budget_period: "Izbrano neveljavno proračunsko obdobje",
+ invalid_budget_anchor_date: "Izhodiščni datum mora biti veljaven datum",
no_results_found: "Ni najdenih rezultatov",
}
diff --git a/scripts/i18n/sr.js b/scripts/i18n/sr.js
index 4b276dd..f501904 100644
--- a/scripts/i18n/sr.js
+++ b/scripts/i18n/sr.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Метод плаћања",
notes: "Белешке",
export: "Извоз",
+ invalid_budget: "Буџет мора бити не-негативан број",
+ invalid_budget_period: "Изабран је неважећи период буџета",
+ invalid_budget_anchor_date: "Референтни датум мора бити важећи датум",
no_results_found: "Нема резултата",
}
diff --git a/scripts/i18n/sr_lat.js b/scripts/i18n/sr_lat.js
index 19f228f..5e266aa 100644
--- a/scripts/i18n/sr_lat.js
+++ b/scripts/i18n/sr_lat.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Način plaćanja",
notes: "Beleške",
export: "Izvezi",
+ invalid_budget: "Budžet mora biti ne-negativan broj",
+ invalid_budget_period: "Izabran je nevažeći period budžeta",
+ invalid_budget_anchor_date: "Referentni datum mora biti važeći datum",
no_results_found: "Nema rezultata",
}
diff --git a/scripts/i18n/tr.js b/scripts/i18n/tr.js
index 0ecba7b..8dcbf02 100644
--- a/scripts/i18n/tr.js
+++ b/scripts/i18n/tr.js
@@ -46,6 +46,9 @@ let i18n = {
payment_method: "Payment method",
notes: "Notes",
export: "Export",
+ invalid_budget: "Bütçe negatif olmayan bir sayı olmalıdır",
+ invalid_budget_period: "Geçersiz bütçe dönemi seçildi",
+ invalid_budget_anchor_date: "Referans tarih geçerli bir tarih olmalıdır",
no_results_found: "Sonuç bulunamadı",
}
diff --git a/scripts/i18n/uk.js b/scripts/i18n/uk.js
index e3ca81c..c4887c6 100644
--- a/scripts/i18n/uk.js
+++ b/scripts/i18n/uk.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Спосіб оплати",
notes: "Примітки",
export: "Експорт",
+ invalid_budget: "Бюджет має бути невід'ємним числом",
+ invalid_budget_period: "Вибрано недійсний бюджетний період",
+ invalid_budget_anchor_date: "Дата відліку має бути дійсною датою",
no_results_found: "Нічого не знайдено",
}
diff --git a/scripts/i18n/vi.js b/scripts/i18n/vi.js
index 740cf5e..84ab3ad 100644
--- a/scripts/i18n/vi.js
+++ b/scripts/i18n/vi.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "Phương thức thanh toán",
notes: "Ghi chú",
export: "Xuất",
+ invalid_budget: "Ngân sách phải là số không âm",
+ invalid_budget_period: "Kỳ ngân sách đã chọn không hợp lệ",
+ invalid_budget_anchor_date: "Ngày mốc phải là ngày hợp lệ",
no_results_found: "Không tìm thấy kết quả",
}
diff --git a/scripts/i18n/zh_cn.js b/scripts/i18n/zh_cn.js
index 39822ab..715f1c0 100644
--- a/scripts/i18n/zh_cn.js
+++ b/scripts/i18n/zh_cn.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "支付方式",
notes: "备注",
export: "导出",
+ invalid_budget: "预算必须为非负数",
+ invalid_budget_period: "所选预算周期无效",
+ invalid_budget_anchor_date: "起始日期必须是有效日期",
no_results_found: "未找到结果",
};
diff --git a/scripts/i18n/zh_tw.js b/scripts/i18n/zh_tw.js
index 25b2468..94c6e30 100644
--- a/scripts/i18n/zh_tw.js
+++ b/scripts/i18n/zh_tw.js
@@ -46,5 +46,8 @@ let i18n = {
payment_method: "支付方式",
notes: "備註",
export: "匯出",
+ invalid_budget: "預算必須為非負數",
+ invalid_budget_period: "所選預算週期無效",
+ invalid_budget_anchor_date: "起始日期必須是有效日期",
no_results_found: "找不到結果",
};
diff --git a/scripts/notifications.js b/scripts/notifications.js
index 03387fb..f197ef2 100644
--- a/scripts/notifications.js
+++ b/scripts/notifications.js
@@ -48,9 +48,13 @@ function saveNotifications() {
const button = document.getElementById("saveNotifications");
button.disabled = true;
const days = document.querySelector('#days').value;
+ const periodSummaryAtPeriodStart = document.getElementById("period_summary_at_period_start").checked ? 1 : 0;
const url = 'endpoints/notifications/savenotificationsettings.php';
- const data = { days: days };
+ const data = {
+ days: days,
+ period_summary_at_period_start: periodSummaryAtPeriodStart,
+ };
makeFetchCall(url, data, button);
}
diff --git a/scripts/settings.js b/scripts/settings.js
index aa85380..06e28f3 100644
--- a/scripts/settings.js
+++ b/scripts/settings.js
@@ -1,11 +1,17 @@
const saveIconContent = '<i class="fa-solid fa-check"></i>';
const deleteIconContent = '<i class="fa-solid fa-trash-can"></i>';
-function saveBudget() {
- const button = document.getElementById("saveBudget");
+function saveMonthlyBudget() {
+ const button = document.getElementById("saveMonthlyBudget");
button.disabled = true;
- const budget = document.getElementById("budget").value;
+ const budget = Number(document.getElementById("monthly_budget").value || 0);
+
+ if (Number.isNaN(budget) || budget < 0) {
+ showErrorMessage(translate("invalid_budget"));
+ button.disabled = false;
+ return;
+ }
fetch('endpoints/user/budget.php', {
method: 'POST',
@@ -13,7 +19,72 @@ function saveBudget() {
'Content-Type': 'application/json',
'X-CSRF-Token': window.csrfToken,
},
- body: JSON.stringify({budget: budget}),
+ body: JSON.stringify({ monthly_budget: budget }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ showSuccessMessage(data.message);
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate('unknown_error'));
+ })
+ .finally(() => {
+ button.disabled = false;
+ });
+}
+
+function savePeriodBudget() {
+ const button = document.getElementById("savePeriodBudget");
+ button.disabled = true;
+
+ const budget = Number(document.getElementById("period_budget").value || 0);
+ const budgetPeriodType = document.getElementById("budget_period_type").value;
+ const budgetPeriodAnchorDateInput = document.getElementById("budget_period_anchor_date");
+ let budgetPeriodAnchorDate = budgetPeriodAnchorDateInput.value;
+ const validPeriodTypes = ["weekly", "fortnightly", "monthly"];
+
+ if (!budgetPeriodAnchorDate || budgetPeriodAnchorDate === "1970-01-01") {
+ const today = new Date();
+ const month = `${today.getMonth() + 1}`.padStart(2, "0");
+ const day = `${today.getDate()}`.padStart(2, "0");
+ budgetPeriodAnchorDate = `${today.getFullYear()}-${month}-${day}`;
+ budgetPeriodAnchorDateInput.value = budgetPeriodAnchorDate;
+ }
+
+ if (Number.isNaN(budget) || budget < 0) {
+ showErrorMessage(translate("invalid_budget"));
+ button.disabled = false;
+ return;
+ }
+
+ if (!validPeriodTypes.includes(budgetPeriodType)) {
+ showErrorMessage(translate("invalid_budget_period"));
+ button.disabled = false;
+ return;
+ }
+
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(budgetPeriodAnchorDate)) {
+ showErrorMessage(translate("invalid_budget_anchor_date"));
+ button.disabled = false;
+ return;
+ }
+
+ fetch('endpoints/user/budget.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: JSON.stringify({
+ period_budget: budget,
+ budget_period_type: budgetPeriodType,
+ budget_period_anchor_date: budgetPeriodAnchorDate,
+ }),
})
.then(response => response.json())
.then(data => {
diff --git a/settings.php b/settings.php
index 753493f..d740bf2 100644
--- a/settings.php
+++ b/settings.php
@@ -11,6 +11,11 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$currencies[$currencyId] = $row;
}
$userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
+$budgetPeriodType = $userData['budget_period_type'] ?? 'monthly';
+$budgetPeriodAnchorDate = $userData['budget_period_anchor_date'] ?? date('Y-m-d');
+if ($budgetPeriodAnchorDate === '1970-01-01' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $budgetPeriodAnchorDate)) {
+ $budgetPeriodAnchorDate = date('Y-m-d');
+}
?>
@@ -19,6 +24,57 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
.logo-preview:after {
content: '<?= translate('upload_logo', $i18n) ?>';
}
+
+ .period-budget-controls {
+ align-items: flex-end;
+ flex-wrap: wrap;
+ gap: 12px 15px;
+ }
+
+ .period-budget-controls .period-budget-field {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 180px;
+ min-width: 160px;
+ gap: 8px;
+ }
+
+ .period-budget-controls .period-budget-field label {
+ margin-bottom: 0;
+ line-height: 1.2;
+ }
+
+ .period-budget-controls .period-budget-save {
+ flex: 0 0 auto;
+ }
+
+ .period-budget-controls #budget_period_anchor_date {
+ display: block;
+ height: 50px;
+ min-height: 50px;
+ }
+
+ @media (min-width: 421px) and (max-width: 768px) {
+ .period-budget-controls .period-budget-field {
+ flex: 1 1 calc(50% - 8px);
+ min-width: 0;
+ }
+
+ .period-budget-controls .period-budget-save {
+ width: 100%;
+ }
+ }
+
+ @media (max-width: 420px) {
+ .period-budget-controls .period-budget-field {
+ flex: 1 1 100%;
+ min-width: 0;
+ }
+
+ .period-budget-controls .period-budget-save {
+ width: 100%;
+ }
+ }
</style>
<section class="contain settings">
@@ -28,14 +84,48 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
</header>
<div class="account-budget">
<div class="form-group-inline">
- <label for="budget"><?= $userData['currency_symbol'] ?></label>
- <input type="number" id="budget" name="budget" autocomplete="off" value="<?= $userData['budget'] ?>"
+ <label for="monthly_budget"><?= $userData['currency_symbol'] ?></label>
+ <input type="number" id="monthly_budget" name="monthly_budget" autocomplete="off" value="<?= $userData['budget'] ?>"
placeholder="Budget">
- <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveBudget" onClick="saveBudget()" />
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveMonthlyBudget" onClick="saveMonthlyBudget()" />
</div>
<div class="settings-notes">
<p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('budget_info', $i18n) ?>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('monthly_budget_info', $i18n) ?>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('period_budget', $i18n) ?></h2>
+ </header>
+ <div class="account-budget">
+ <div class="form-group-inline">
+ <label for="period_budget"><?= $userData['currency_symbol'] ?></label>
+ <input type="number" id="period_budget" name="period_budget" autocomplete="off" value="<?= $userData['period_budget'] ?? 0 ?>"
+ placeholder="Budget">
+ </div>
+ <div class="form-group-inline period-budget-controls">
+ <div class="period-budget-field">
+ <label for="budget_period_type"><?= translate('budget_period', $i18n) ?></label>
+ <select id="budget_period_type" name="budget_period_type">
+ <option value="weekly" <?= $budgetPeriodType === 'weekly' ? 'selected' : '' ?>><?= translate('weekly', $i18n) ?></option>
+ <option value="fortnightly" <?= $budgetPeriodType === 'fortnightly' ? 'selected' : '' ?>><?= translate('fortnightly', $i18n) ?></option>
+ <option value="monthly" <?= $budgetPeriodType === 'monthly' ? 'selected' : '' ?>><?= translate('monthly', $i18n) ?></option>
+ </select>
+ </div>
+ <div class="period-budget-field">
+ <label for="budget_period_anchor_date"><?= translate('budget_anchor_date', $i18n) ?></label>
+ <input type="date" id="budget_period_anchor_date" name="budget_period_anchor_date"
+ value="<?= htmlspecialchars($budgetPeriodAnchorDate, ENT_QUOTES, 'UTF-8') ?>">
+ </div>
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="savePeriodBudget" class="period-budget-save" onClick="savePeriodBudget()" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('period_budget_info', $i18n) ?>
</p>
</div>
</div>
@@ -128,6 +218,9 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
if ($rowCount == 0) {
$notifications['days'] = 1;
+ $notifications['period_summary_at_period_start'] = 0;
+ } else if (!isset($notifications['period_summary_at_period_start'])) {
+ $notifications['period_summary_at_period_start'] = 0;
}
// Email notifications
@@ -396,6 +489,13 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
<input type="submit" class="thin" value="<?= translate('save', $i18n) ?>" id="saveNotifications"
onClick="saveNotifications()" />
</div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="period_summary_at_period_start" name="period_summary_at_period_start"
+ <?= !empty($notifications['period_summary_at_period_start']) ? "checked" : "" ?>>
+ <label for="period_summary_at_period_start">
+ <?= translate('send_period_summary_at_period_start', $i18n) ?>
+ </label>
+ </div>
</section>
<section class="account-notifications-section">
<header class="account-notification-section-header" onclick="openNotificationsSettings('email')">
diff --git a/stats.php b/stats.php
index 8b5fe02..d43682e 100644
--- a/stats.php
+++ b/stats.php
@@ -180,11 +180,16 @@ require_once 'includes/stats_extra_calculations.php';
usort($paymentMethodDataPoints, fn($a, $b) => $b['y'] <=> $a['y']);
$showPaymentMethodsGraph = count($paymentMethodDataPoints) > 1;
- $showAnyGraph = $showCategoryCostGraph || $showMemberCostGraph || $showPaymentMethodsGraph || $showTotalMonthlyCostGraph || $showVsBudgetGraph
+ $showMonthlyStats = !isset($_GET['budget']) || $_GET['budget'] === 'monthly';
+ $showPeriodStats = !isset($_GET['budget']) || $_GET['budget'] === 'period';
+
+ $showAnyGraph = $showCategoryCostGraph || $showMemberCostGraph || $showPaymentMethodsGraph || $showTotalMonthlyCostGraph
+ || ($showMonthlyStats && $showVsMonthlyBudgetGraph) || ($showPeriodStats && $showVsPeriodBudgetGraph)
|| $showProjectionGraph || $showLifetimeGraph || $showCycleGraph || $showCurrencyGraph || $showHistogramGraph || $showYearlyNewGraph;
$showTrendsSection = $showTotalMonthlyCostGraph || $showProjectionGraph || $monthOverMonthDelta !== null;
- $showBudgetSection = isset($budgetUsed) || isset($budgetLeft) || isset($overBudgetAmount) || $showVsBudgetGraph;
+ $showBudgetSection = ($showMonthlyStats && (isset($monthlyBudgetUsed) || isset($monthlyBudgetLeft) || isset($monthlyOverBudgetAmount) || $showVsMonthlyBudgetGraph))
+ || ($showPeriodStats && (isset($periodBudgetUsed) || isset($periodBudgetLeft) || isset($periodOverBudgetAmount) || $showVsPeriodBudgetGraph));
$showSplitSection = $showMemberCostGraph || $showCategoryCostGraph || $showPaymentMethodsGraph || $showCycleGraph || $showCurrencyGraph || $showHistogramGraph;
$showHistorySection = $totalLifetimeSpend > 0 || $oldestSubscription !== null || $averageSubscriptionAge !== null || $showLifetimeGraph || $showYearlyNewGraph;
?>
@@ -364,42 +369,80 @@ require_once 'includes/stats_extra_calculations.php';
<h2><?= translate('budget', $i18n) ?></h2>
<div class="statistics">
<?php
- if (isset($budgetUsed)) {
+ if ($showMonthlyStats && isset($monthlyBudgetUsed)) {
?>
<div class="statistic">
- <span><?= number_format($budgetUsed, 2) ?>%</span>
- <div class="title"><?= translate('percentage_budget_used', $i18n) ?></div>
+ <span><?= number_format($monthlyBudgetUsed, 2) ?>%</span>
+ <div class="title"><?= translate('monthly_budget', $i18n) ?> - <?= translate('percentage_budget_used', $i18n) ?></div>
</div>
- <?php
- }
- if (isset($budgetLeft)) {
- ?>
<div class="statistic">
- <span><?= CurrencyFormatter::format($budgetLeft, $code) ?></span>
- <div class="title"><?= translate('budget_remaining', $i18n) ?></div>
+ <span><?= CurrencyFormatter::format($monthlyBudgetLeft, $code) ?></span>
+ <div class="title"><?= translate('monthly_budget', $i18n) ?> - <?= translate('budget_remaining', $i18n) ?></div>
</div>
<?php
+ if (isset($monthlyOverBudgetAmount)) {
+ ?>
+ <div class="statistic">
+ <span><?= CurrencyFormatter::format($monthlyOverBudgetAmount, $code) ?></span>
+ <div class="title"><?= translate('monthly_budget', $i18n) ?> - <?= translate('amount_over_budget', $i18n) ?></div>
+ </div>
+ <?php
+ }
}
- if (isset($overBudgetAmount)) {
+
+ if ($showPeriodStats && isset($periodBudgetUsed)) {
+ $periodRangeLabel = htmlspecialchars($budgetPeriodLabel, ENT_QUOTES, 'UTF-8');
?>
<div class="statistic">
- <span><?= CurrencyFormatter::format($overBudgetAmount, $code) ?></span>
- <div class="title"><?= translate('amount_over_budget', $i18n) ?></div>
+ <span><?= CurrencyFormatter::format($amountNeededThisPeriod, $code) ?></span>
+ <div class="title"><?= translate('amount_needed_this_period', $i18n) ?></div>
+ <div class="period-range"><?= $periodRangeLabel ?></div>
+ </div>
+ <div class="statistic">
+ <span><?= number_format($periodBudgetUsed, 2) ?>%</span>
+ <div class="title"><?= translate('period_budget', $i18n) ?> - <?= translate('percentage_budget_used', $i18n) ?></div>
+ <div class="period-range"><?= $periodRangeLabel ?></div>
+ </div>
+ <div class="statistic">
+ <span><?= CurrencyFormatter::format($periodBudgetLeft, $code) ?></span>
+ <div class="title"><?= translate('period_budget', $i18n) ?> - <?= translate('budget_remaining', $i18n) ?></div>
+ <div class="period-range"><?= $periodRangeLabel ?></div>
</div>
<?php
+ if (isset($periodOverBudgetAmount)) {
+ ?>
+ <div class="statistic">
+ <span><?= CurrencyFormatter::format($periodOverBudgetAmount, $code) ?></span>
+ <div class="title"><?= translate('period_budget', $i18n) ?> - <?= translate('amount_over_budget', $i18n) ?></div>
+ <div class="period-range"><?= $periodRangeLabel ?></div>
+ </div>
+ <?php
+ }
}
?>
</div>
<?php
- if ($showVsBudgetGraph) {
+ if (($showMonthlyStats && $showVsMonthlyBudgetGraph) || ($showPeriodStats && $showVsPeriodBudgetGraph)) {
?>
<div class="graphs">
- <section class="graph">
- <header>
- <?= translate('cost_vs_budget', $i18n) ?> (<?= CurrencyFormatter::format($budget, $code) ?>)
- </header>
- <div id="budgetVsCostChart" style="width: 100%;"></div>
- </section>
+ <?php if ($showMonthlyStats && $showVsMonthlyBudgetGraph) { ?>
+ <section class="graph">
+ <header>
+ <?= translate('cost_vs_monthly_budget', $i18n) ?> (<?= CurrencyFormatter::format($monthlyBudget, $code) ?>)
+ <div class="sub-header">(<?= translate('monthly_cost', $i18n) ?>)</div>
+ </header>
+ <div id="monthlyBudgetVsCostChart" style="width: 100%;"></div>
+ </section>
+ <?php } ?>
+ <?php if ($showPeriodStats && $showVsPeriodBudgetGraph) { ?>
+ <section class="graph">
+ <header>
+ <?= translate('cost_vs_period_budget', $i18n) ?> (<?= CurrencyFormatter::format($periodBudget, $code) ?>)
+ <div class="sub-header">(<?= translate('amount_needed_this_period', $i18n) ?>)</div>
+ </header>
+ <div id="periodBudgetVsCostChart" style="width: 100%;"></div>
+ </section>
+ <?php } ?>
</div>
<?php
}
@@ -612,7 +655,12 @@ if ($showAnyGraph) {
loadGraph("categorySplitChart", <?php echo json_encode($categoryDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showCategoryCostGraph ? 1 : 0 ?>);
loadGraph("memberSplitChart", <?php echo json_encode($memberDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showMemberCostGraph ? 1 : 0 ?>);
loadGraph("paymentMethidSplitChart", <?php echo json_encode($paymentMethodDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showPaymentMethodsGraph ? 1 : 0 ?>);
- loadGraph("budgetVsCostChart", <?php echo json_encode($vsBudgetDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showVsBudgetGraph ? 1 : 0 ?>);
+ <?php if ($showMonthlyStats && $showVsMonthlyBudgetGraph) { ?>
+ loadGraph("monthlyBudgetVsCostChart", <?php echo json_encode($vsMonthlyBudgetDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", 1);
+ <?php } ?>
+ <?php if ($showPeriodStats && $showVsPeriodBudgetGraph) { ?>
+ loadGraph("periodBudgetVsCostChart", <?php echo json_encode($vsPeriodBudgetDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", 1);
+ <?php } ?>
loadGraph("cycleSplitChart", <?php echo json_encode($cycleDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showCycleGraph ? 1 : 0 ?>);
loadGraph("currencySplitChart", <?php echo json_encode($currencyDataPoints, JSON_NUMERIC_CHECK); ?>, "<?= $code ?>", <?= $showCurrencyGraph ? 1 : 0 ?>);
loadBarGraph("priceHistogramChart", <?php echo json_encode($histogramDataPoints, JSON_NUMERIC_CHECK); ?>, "", <?= $showHistogramGraph ? 1 : 0 ?>, null);
diff --git a/styles/styles.css b/styles/styles.css
index f28153b..7b611a3 100644
--- a/styles/styles.css
+++ b/styles/styles.css
@@ -2321,6 +2321,14 @@ button.dark-theme-button i {
text-align: center;
}
+.statistic>.period-range {
+ margin-top: 5px;
+ font-size: 13px;
+ color: var(--text-color);
+ opacity: 0.6;
+ text-align: center;
+}
+
.statistic>.subtitle {
font-size: 25px;
color: var(--accent-color);