Skip to content

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

feat: export subscription as ics from the calendar view (#404)

Miguel Ribeirof1360f7d468e
diff --git a/endpoints/subscription/exportcalendar.php b/endpoints/subscription/exportcalendar.php
new file mode 100644
index 0000000..be16b91
--- /dev/null
+++ b/endpoints/subscription/exportcalendar.php
@@ -0,0 +1,85 @@
+<?php
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/getdbkeys.php';
+
+if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('session_expired', $i18n)
+ ]));
+}
+
+if ($_SERVER["REQUEST_METHOD"] === "POST") {
+ $postData = file_get_contents("php://input");
+ $data = json_decode($postData, true);
+
+ $id = $data['id'];
+
+ $stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');
+ $stmt->bindParam(':id', $id, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER); // Assuming $_SESSION['userId'] holds the logged-in user's ID
+ $result = $stmt->execute();
+
+ if ($result === false) {
+ die(json_encode([
+ 'success' => false,
+ 'message' => "Subscription not found"
+ ]));
+ }
+
+ $subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array
+
+ if ($subscription) {
+ $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name'];
+ $subscription['category'] = $categories[$subscription['category_id']]['name'];
+ $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];
+ $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];
+ $subscription['trigger'] = $subscription['notify_days_before'] ? $subscription['notify_days_before'] : 1;
+
+ // Create ICS from subscription information
+ $uid = uniqid();
+ $summary = "Wallos: " . $subscription['name'];
+ $description = "Price: {$subscription['currency']}{$subscription['price']}\nCategory: {$subscription['category']}\nPayment Method: {$subscription['payment_method']}\nPayer: {$subscription['payer_user']}\n\nNotes: {$subscription['notes']}";
+
+ $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd\THis\Z');
+ $dtend = (new DateTime($subscription['next_payment']))->modify('+1 hour')->format('Ymd\THis\Z');
+ $location = isset($subscription['url']) ? $subscription['url'] : '';
+ $alarm_trigger = '-' . $subscription['trigger'] . 'D';
+
+ $icsContent = <<<ICS
+ BEGIN:VCALENDAR
+ VERSION:2.0
+ PRODID:-//Your Organization//Your Application//EN
+ CALSCALE:GREGORIAN
+ METHOD:PUBLISH
+ BEGIN:VEVENT
+ UID:$uid
+ SUMMARY:$summary
+ DESCRIPTION:$description
+ DTSTART:$dtstart
+ DTEND:$dtend
+ LOCATION:$location
+ STATUS:CONFIRMED
+ TRANSP:OPAQUE
+ BEGIN:VALARM
+ ACTION:DISPLAY
+ DESCRIPTION:Reminder
+ TRIGGER:$alarm_trigger
+ END:VALARM
+ END:VEVENT
+ END:VCALENDAR
+ ICS;
+
+ echo json_encode([
+ 'success' => true,
+ 'ics' => $icsContent,
+ 'name' => $subscription['name']
+ ]);
+ } else {
+ echo json_encode([
+ 'success' => false,
+ 'message' => "Subscription not found"
+ ]);
+ }
+}
+?>
\ No newline at end of file
diff --git a/includes/version.php b/includes/version.php
index 58ffe9b..775fc0c 100644
--- a/includes/version.php
+++ b/includes/version.php
@@ -1,3 +1,3 @@
<?php
- $version = "v2.6.1";
+ $version = "v2.7.0";
?>
diff --git a/scripts/calendar.js b/scripts/calendar.js
index cd30c55..44b5d61 100644
--- a/scripts/calendar.js
+++ b/scripts/calendar.js
@@ -60,6 +60,9 @@ function openSubscriptionModal(subscriptionId) {
${subscription.payment_method ? `<p><strong>${translate('payment_method')}:</strong> ${subscription.payment_method}</p>` : ''}
${subscription.notes ? `<p><strong>${translate('notes')}:</strong> ${subscription.notes}</p>` : ''}
</div>
+ </div>
+ <div class="modal-footer">
+ <button class="button tiny" onclick="exportCalendar(${subscription.id})">${translate('export')}</button>
</div>`;
modalContent.innerHTML = html;
modal.classList.add('is-open');
@@ -68,4 +71,31 @@ function openSubscriptionModal(subscriptionId) {
}
})
.catch(error => console.error('Error:', error));
+}
+
+function exportCalendar(subscriptionId) {
+ fetch('endpoints/subscription/exportcalendar.php', {
+ method: 'POST',
+ body: JSON.stringify({id: subscriptionId}),
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success && data.ics) {
+ const blob = new Blob([data.ics], {type: 'text/calendar'});
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ // Use the subscription name for the file name, replacing any characters that are invalid in file names
+ a.download = `${data.name.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.ics`;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ } else {
+ console.error('Failed to download the calendar file.');
+ }
+ })
+ .catch(error => console.error('Error:', error));
}
\ No newline at end of file