9 Commits

Author SHA1 Message Date
579cbd1bc9 feat: add multi-currency support to cospend payments
Some checks failed
CI / update (push) Failing after 5s
- Add ExchangeRate model for currency conversion tracking
- Implement currency utility functions for formatting and conversion
- Add exchange rates API endpoint with caching and fallback rates
- Update Payment and RecurringPayment models to support multiple currencies
- Enhanced payment forms with currency selection and conversion display
- Update split method selector with better currency handling
- Add currency-aware payment display and balance calculations
- Support for EUR, USD, GBP, and CHF with automatic exchange rate fetching

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-14 19:54:31 +02:00
c8e542eec8 fix: implement persistent MongoDB connections and resolve race conditions
- Replace connect/disconnect pattern with persistent connection pool
- Add explicit database initialization on server startup
- Remove all dbDisconnect() calls from API endpoints to prevent race conditions
- Fix MongoNotConnectedError when scheduler runs concurrently with API requests
- Add connection pooling with proper MongoDB driver options
- Add safety check for recipes array in favorites utility

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-14 19:53:55 +02:00
08d7d8541b cospend: graph only shows hovered month expenses
Some checks failed
CI / update (push) Failing after 5s
2025-09-12 23:37:39 +02:00
26abad6b54 fix: use event.fetch instead of global fetch for server-side requests
Some checks failed
CI / update (push) Failing after 5s
Updated both hooks.server.ts and bible-quote API to properly use event.fetch
for relative URLs in server-side code, following SvelteKit best practices.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-12 23:17:18 +02:00
53b739144a error page: prettier + random bible verse
Some checks failed
CI / update (push) Failing after 4s
2025-09-12 23:11:57 +02:00
7ffb9c0b86 bible api: use SvelteKit static file handling instead of fs
Some checks failed
CI / update (push) Failing after 5s
Replace filesystem access with fetch request to leverage SvelteKit's
built-in static file serving for the allioli.tsv bible data.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-12 22:54:25 +02:00
a22471a943 error page: prettier + random bible verse
Some checks failed
CI / update (push) Failing after 5s
2025-09-12 22:49:32 +02:00
4b2250ab03 cospend: require group membership for access 2025-09-12 22:27:21 +02:00
effed784b7 Enhance cospend monthly expenses chart with improved UX
- Add monthly total labels above each bar showing cumulative expense amounts
- Improve chart styling: white labels, larger fonts, clean flat tooltip design
- Hide Y-axis ticks and grid lines for cleaner appearance
- Capitalize category names in legend and tooltips
- Show only hovered category in tooltip instead of all categories
- Trim empty months from start of data for users with limited history
- Create responsive layout: balance and chart side-by-side on wide screens
- Increase max width to 1400px for dashboard while keeping recent activity at 800px
- Filter out settlements from monthly expenses view

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-12 22:21:22 +02:00
46 changed files with 33221 additions and 247 deletions

View File

@@ -1,4 +1,4 @@
import type { Handle } from "@sveltejs/kit"
import type { Handle, HandleServerError } from "@sveltejs/kit"
import { redirect } from "@sveltejs/kit"
import { error } from "@sveltejs/kit"
import { SvelteKitAuth } from "@auth/sveltekit"
@@ -7,24 +7,59 @@ import { AUTHENTIK_ID, AUTHENTIK_SECRET, AUTHENTIK_ISSUER } from "$env/static/pr
import { sequence } from "@sveltejs/kit/hooks"
import * as auth from "./auth"
import { initializeScheduler } from "./lib/server/scheduler"
import { dbConnect } from "./utils/db"
import fs from 'fs'
import path from 'path'
// Initialize the recurring payment scheduler
// Initialize database connection on server startup
console.log('🚀 Server starting - initializing database connection...');
await dbConnect().then(() => {
console.log('✅ Database connected successfully');
// Initialize the recurring payment scheduler after DB is ready
initializeScheduler();
console.log('✅ Recurring payment scheduler initialized');
}).catch((error) => {
console.error('❌ Failed to connect to database on startup:', error);
// Don't crash the server - API routes will attempt reconnection
});
async function authorization({ event, resolve }) {
// Protect any routes under /authenticated
if (event.url.pathname.startsWith('/rezepte/edit') || event.url.pathname.startsWith('/rezepte/add')) {
const session = await event.locals.auth();
// Protect rezepte routes
if (event.url.pathname.startsWith('/rezepte/edit') || event.url.pathname.startsWith('/rezepte/add')) {
if (!session) {
// Preserve the original URL the user was trying to access
const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search);
redirect(303, `/login?callbackUrl=${callbackUrl}`);
}
else if (!session.user.groups.includes('rezepte_users')) {
// strip last dir from url
// TODO: give indication of why access failed
const new_url = event.url.pathname.split('/').slice(0, -1).join('/');
redirect(303, new_url);
error(403, {
message: 'Zugriff verweigert',
details: 'Du hast keine Berechtigung für diesen Bereich. Falls du glaubst, dass dies ein Fehler ist, wende dich bitte an Alexander.'
});
}
}
// Protect cospend routes and API endpoints
if (event.url.pathname.startsWith('/cospend') || event.url.pathname.startsWith('/api/cospend')) {
if (!session) {
// For API routes, return 401 instead of redirecting
if (event.url.pathname.startsWith('/api/cospend')) {
error(401, {
message: 'Anmeldung erforderlich',
details: 'Du musst angemeldet sein, um auf diesen Bereich zugreifen zu können.'
});
}
// For page routes, redirect to login
const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search);
redirect(303, `/login?callbackUrl=${callbackUrl}`);
}
else if (!session.user.groups.includes('cospend')) {
error(403, {
message: 'Zugriff verweigert',
details: 'Du hast keine Berechtigung für diesen Bereich. Falls du glaubst, dass dies ein Fehler ist, wende dich bitte an Alexander.'
});
}
}
@@ -32,6 +67,32 @@ async function authorization({ event, resolve }) {
return resolve(event);
}
// Bible verse functionality for error pages
async function getRandomVerse(fetch: typeof globalThis.fetch): Promise<any> {
try {
const response = await fetch('/api/bible-quote');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (err) {
console.error('Error getting random verse:', err);
return null;
}
}
export const handleError: HandleServerError = async ({ error, event, status, message }) => {
console.error('Error occurred:', { error, status, message, url: event.url.pathname });
// Add Bible verse to error context
const bibleQuote = await getRandomVerse(event.fetch);
return {
message: message,
bibleQuote
};
};
export const handle: Handle = sequence(
auth.handle,
authorization

View File

@@ -53,9 +53,10 @@
const ctx = canvas.getContext('2d');
// Process datasets with colors
// Process datasets with colors and capitalize labels
const processedDatasets = data.datasets.map((dataset, index) => ({
...dataset,
label: dataset.label.charAt(0).toUpperCase() + dataset.label.slice(1),
backgroundColor: getCategoryColor(dataset.label, index),
borderColor: getCategoryColor(dataset.label, index),
borderWidth: 1
@@ -70,16 +71,26 @@
options: {
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {
top: 40
}
},
scales: {
x: {
stacked: true,
grid: {
display: false
},
border: {
display: false
},
ticks: {
color: 'var(--nord3)',
color: '#ffffff',
font: {
family: 'Inter, system-ui, sans-serif'
family: 'Inter, system-ui, sans-serif',
size: 14,
weight: 'bold'
}
}
},
@@ -87,58 +98,74 @@
stacked: true,
beginAtZero: true,
grid: {
color: 'var(--nord4)',
borderDash: [2, 2]
display: false
},
border: {
display: false
},
ticks: {
color: 'var(--nord3)',
color: 'transparent',
font: {
family: 'Inter, system-ui, sans-serif'
},
callback: function(value) {
return 'CHF ' + value.toFixed(0);
size: 0
}
}
}
},
plugins: {
datalabels: {
display: false
},
legend: {
position: 'bottom',
labels: {
padding: 20,
usePointStyle: true,
color: 'var(--nord1)',
color: '#ffffff',
font: {
family: 'Inter, system-ui, sans-serif',
size: 12
size: 14,
weight: 'bold'
}
}
},
title: {
display: !!title,
text: title,
color: 'var(--nord0)',
color: '#ffffff',
font: {
family: 'Inter, system-ui, sans-serif',
size: 16,
size: 18,
weight: 'bold'
},
padding: 20
},
tooltip: {
backgroundColor: 'var(--nord1)',
titleColor: 'var(--nord6)',
bodyColor: 'var(--nord6)',
borderColor: 'var(--nord3)',
borderWidth: 1,
cornerRadius: 8,
backgroundColor: '#2e3440',
titleColor: '#ffffff',
bodyColor: '#ffffff',
borderWidth: 0,
cornerRadius: 12,
padding: 12,
displayColors: true,
titleAlign: 'center',
bodyAlign: 'center',
titleFont: {
family: 'Inter, system-ui, sans-serif'
family: 'Inter, system-ui, sans-serif',
size: 13,
weight: 'bold'
},
bodyFont: {
family: 'Inter, system-ui, sans-serif'
family: 'Inter, system-ui, sans-serif',
size: 14,
weight: '500'
},
titleMarginBottom: 8,
usePointStyle: true,
boxPadding: 6,
callbacks: {
title: function(context) {
return '';
},
label: function(context) {
return context.dataset.label + ': CHF ' + context.parsed.y.toFixed(2);
}
@@ -146,10 +173,53 @@
}
},
interaction: {
intersect: false,
mode: 'index'
intersect: true,
mode: 'point'
}
},
plugins: [{
id: 'monthlyTotals',
afterDatasetsDraw: function(chart) {
const ctx = chart.ctx;
const chartArea = chart.chartArea;
ctx.save();
ctx.font = 'bold 14px Inter, system-ui, sans-serif';
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
// Calculate and display monthly totals
chart.data.labels.forEach((label, index) => {
let total = 0;
chart.data.datasets.forEach(dataset => {
total += dataset.data[index] || 0;
});
if (total > 0) {
// Get the x position for this month from any dataset
const meta = chart.getDatasetMeta(0);
if (meta && meta.data[index]) {
const x = meta.data[index].x;
// Find the highest point for this month across all datasets
let maxY = chartArea.bottom;
for (let datasetIndex = 0; datasetIndex < chart.data.datasets.length; datasetIndex++) {
const datasetMeta = chart.getDatasetMeta(datasetIndex);
if (datasetMeta && datasetMeta.data[index]) {
maxY = Math.min(maxY, datasetMeta.data[index].y);
}
}
// Display the total above the bar
ctx.fillText(`CHF ${total.toFixed(0)}`, x, maxY - 10);
}
}
});
ctx.restore();
}
}]
});
}

View File

@@ -9,6 +9,7 @@
export let personalAmounts = {};
export let currentUser = '';
export let predefinedMode = false;
export let currency = 'CHF';
let personalTotalError = false;
@@ -173,8 +174,8 @@
{/each}
{#if amount}
<div class="remainder-info" class:error={personalTotalError}>
<span>Total Personal: CHF {Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0).toFixed(2)}</span>
<span>Remainder to Split: CHF {Math.max(0, parseFloat(amount) - Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0)).toFixed(2)}</span>
<span>Total Personal: {currency} {Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0).toFixed(2)}</span>
<span>Remainder to Split: {currency} {Math.max(0, parseFloat(amount) - Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0)).toFixed(2)}</span>
{#if personalTotalError}
<div class="error-message">⚠️ Personal amounts exceed total payment amount!</div>
{/if}
@@ -194,11 +195,11 @@
</div>
<span class="amount" class:positive={splitAmounts[user] < 0} class:negative={splitAmounts[user] > 0}>
{#if splitAmounts[user] > 0}
owes CHF {splitAmounts[user].toFixed(2)}
owes {currency} {splitAmounts[user].toFixed(2)}
{:else if splitAmounts[user] < 0}
is owed CHF {Math.abs(splitAmounts[user]).toFixed(2)}
is owed {currency} {Math.abs(splitAmounts[user]).toFixed(2)}
{:else}
owes CHF {splitAmounts[user].toFixed(2)}
owes {currency} {splitAmounts[user].toFixed(2)}
{/if}
</span>
</div>

View File

@@ -24,6 +24,12 @@ export async function getUserFavorites(fetch: any, locals: any): Promise<string[
}
export function addFavoriteStatusToRecipes(recipes: any[], userFavorites: string[]): any[] {
// Safety check: ensure recipes is an array
if (!Array.isArray(recipes)) {
console.error('addFavoriteStatusToRecipes: recipes is not an array:', recipes);
return [];
}
return recipes.map(recipe => ({
...recipe,
isFavorite: userFavorites.some(favId => favId.toString() === recipe._id.toString())

94
src/lib/utils/currency.ts Normal file
View File

@@ -0,0 +1,94 @@
import { ExchangeRate } from '../../models/ExchangeRate';
import { dbConnect, dbDisconnect } from '../../utils/db';
/**
* Convert amount from foreign currency to CHF using direct database/API access
*/
export async function convertToCHF(
amount: number,
fromCurrency: string,
date: string,
fetch?: typeof globalThis.fetch
): Promise<{
convertedAmount: number;
exchangeRate: number;
}> {
if (fromCurrency.toUpperCase() === 'CHF') {
return {
convertedAmount: amount,
exchangeRate: 1
};
}
const rate = await getExchangeRate(fromCurrency.toUpperCase(), date);
return {
convertedAmount: amount * rate,
exchangeRate: rate
};
}
/**
* Get exchange rate from database cache or fetch from API
*/
async function getExchangeRate(fromCurrency: string, date: string): Promise<number> {
const dateStr = date.split('T')[0]; // Extract YYYY-MM-DD
await dbConnect();
try {
// Try cache first
const cachedRate = await ExchangeRate.findOne({
fromCurrency,
toCurrency: 'CHF',
date: dateStr
});
if (cachedRate) {
return cachedRate.rate;
}
// Fetch from API
const rate = await fetchFromFrankfurterAPI(fromCurrency, dateStr);
// Cache the result
await ExchangeRate.create({
fromCurrency,
toCurrency: 'CHF',
rate,
date: dateStr
});
return rate;
} finally {
await dbDisconnect();
}
}
/**
* Fetch exchange rate from Frankfurter API
*/
async function fetchFromFrankfurterAPI(fromCurrency: string, date: string): Promise<number> {
const url = `https://api.frankfurter.app/${date}?from=${fromCurrency}&to=CHF`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Frankfurter API request failed: ${response.status}`);
}
const data = await response.json();
if (!data.rates || !data.rates.CHF) {
throw new Error(`No exchange rate found for ${fromCurrency} to CHF on ${date}`);
}
return data.rates.CHF;
}
/**
* Validate currency code (3-letter ISO code)
*/
export function isValidCurrencyCode(currency: string): boolean {
return /^[A-Z]{3}$/.test(currency.toUpperCase());
}

View File

@@ -0,0 +1,47 @@
import mongoose from 'mongoose';
export interface IExchangeRate {
_id?: string;
fromCurrency: string; // e.g., "USD"
toCurrency: string; // Always "CHF" for our use case
rate: number;
date: string; // Date in YYYY-MM-DD format
createdAt?: Date;
updatedAt?: Date;
}
const ExchangeRateSchema = new mongoose.Schema(
{
fromCurrency: {
type: String,
required: true,
uppercase: true,
trim: true
},
toCurrency: {
type: String,
required: true,
uppercase: true,
trim: true,
default: 'CHF'
},
rate: {
type: Number,
required: true,
min: 0
},
date: {
type: String,
required: true,
match: /^\d{4}-\d{2}-\d{2}$/
}
},
{
timestamps: true
}
);
// Create compound index for efficient lookups
ExchangeRateSchema.index({ fromCurrency: 1, toCurrency: 1, date: 1 }, { unique: true });
export const ExchangeRate = mongoose.model<IExchangeRate>("ExchangeRate", ExchangeRateSchema);

View File

@@ -4,8 +4,10 @@ export interface IPayment {
_id?: string;
title: string;
description?: string;
amount: number;
currency: string;
amount: number; // Always in CHF (converted if necessary)
currency: string; // Currency code (CHF if no conversion, foreign currency if converted)
originalAmount?: number; // Amount in foreign currency (only if currency != CHF)
exchangeRate?: number; // Exchange rate used for conversion (only if currency != CHF)
paidBy: string; // username/nickname of the person who paid
date: Date;
image?: string; // path to uploaded image
@@ -36,7 +38,17 @@ const PaymentSchema = new mongoose.Schema(
type: String,
required: true,
default: 'CHF',
enum: ['CHF'] // For now only CHF as requested
uppercase: true
},
originalAmount: {
type: Number,
required: false,
min: 0
},
exchangeRate: {
type: Number,
required: false,
min: 0
},
paidBy: {
type: String,

View File

@@ -4,16 +4,16 @@ export interface IRecurringPayment {
_id?: string;
title: string;
description?: string;
amount: number;
currency: string;
amount: number; // Amount in the original currency
currency: string; // Original currency code
paidBy: string; // username/nickname of the person who paid
category: 'groceries' | 'shopping' | 'travel' | 'restaurant' | 'utilities' | 'fun' | 'settlement';
splitMethod: 'equal' | 'full' | 'proportional' | 'personal_equal';
splits: Array<{
username: string;
amount?: number;
amount?: number; // Amount in original currency
proportion?: number;
personalAmount?: number;
personalAmount?: number; // Amount in original currency
}>;
frequency: 'daily' | 'weekly' | 'monthly' | 'custom';
cronExpression?: string; // For custom frequencies using cron syntax
@@ -47,7 +47,7 @@ const RecurringPaymentSchema = new mongoose.Schema(
type: String,
required: true,
default: 'CHF',
enum: ['CHF']
uppercase: true
},
paidBy: {
type: String,

393
src/routes/+error.svelte Normal file
View File

@@ -0,0 +1,393 @@
<script>
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import Header from '$lib/components/Header.svelte';
$: status = $page.status;
$: error = $page.error;
// Get session data if available (may not be available in error context)
$: session = $page.data?.session;
$: user = session?.user;
// Get Bible quote from SSR via handleError hook
$: bibleQuote = $page.error?.bibleQuote;
function getErrorTitle(status) {
switch (status) {
case 401:
return 'Anmeldung erforderlich';
case 403:
return 'Zugriff verweigert';
case 404:
return 'Seite nicht gefunden';
case 500:
return 'Serverfehler';
default:
return 'Fehler';
}
}
function getErrorDescription(status) {
switch (status) {
case 401:
return 'Du musst angemeldet sein, um auf diese Seite zugreifen zu können.';
case 403:
return 'Du hast keine Berechtigung für diesen Bereich.';
case 404:
return 'Die angeforderte Seite konnte nicht gefunden werden.';
case 500:
return 'Es ist ein unerwarteter Fehler aufgetreten. Bitte versuche es später erneut.';
default:
return 'Es ist ein unerwarteter Fehler aufgetreten.';
}
}
function getErrorIcon(status) {
switch (status) {
case 401:
return '🔐';
case 403:
return '🚫';
case 404:
return '🔍';
case 500:
return '⚠️';
default:
return '❌';
}
}
function goHome() {
goto('/');
}
function goBack() {
if (window.history.length > 1) {
window.history.back();
} else {
goto('/');
}
}
function login() {
goto('/login');
}
</script>
<svelte:head>
<title>{getErrorTitle(status)} - Alexander's Website</title>
</svelte:head>
<Header>
<ul class="site_header" slot="links">
</ul>
<main class="error-page">
<div class="error-container">
<div class="error-icon">
{getErrorIcon(status)}
</div>
<h1 class="error-title">
{getErrorTitle(status)}
</h1>
<div class="error-code">
Fehler {status}
</div>
<p class="error-description">
{getErrorDescription(status)}
</p>
{#if error?.details}
<div class="error-details">
{error.details}
</div>
{/if}
<div class="error-actions">
{#if status === 401}
<button class="btn btn-primary" on:click={login}>
Anmelden
</button>
<button class="btn btn-secondary" on:click={goHome}>
Zur Startseite
</button>
{:else if status === 403}
<button class="btn btn-primary" on:click={goHome}>
Zur Startseite
</button>
<button class="btn btn-secondary" on:click={goBack}>
Zurück
</button>
{:else if status === 404}
<button class="btn btn-primary" on:click={goHome}>
Zur Startseite
</button>
<button class="btn btn-secondary" on:click={goBack}>
Zurück
</button>
{:else if status === 500}
<button class="btn btn-primary" on:click={goHome}>
Zur Startseite
</button>
<button class="btn btn-secondary" on:click={goBack}>
Erneut versuchen
</button>
{:else}
<button class="btn btn-primary" on:click={goHome}>
Zur Startseite
</button>
<button class="btn btn-secondary" on:click={goBack}>
Zurück
</button>
{/if}
</div>
<!-- Bible Quote Section -->
{#if bibleQuote}
<div class="bible-quote">
<div class="quote-text">
{bibleQuote.text}"
</div>
<div class="quote-reference">
{bibleQuote.reference}
</div>
</div>
{/if}
</div>
</main>
</Header>
<style>
.error-page {
min-height: calc(100vh - 6rem);
display: flex;
align-items: center;
justify-content: center;
background: #fbf9f3;
padding: 2rem;
}
@media (prefers-color-scheme: dark) {
.error-page {
background: var(--background-dark);
}
}
.error-container {
background: var(--nord5);
border-radius: 1rem;
padding: 3rem;
max-width: 600px;
width: 100%;
text-align: center;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
border: 1px solid var(--nord4);
}
@media (prefers-color-scheme: dark) {
.error-container {
background: var(--nord1);
border-color: var(--nord2);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
}
.error-icon {
font-size: 4rem;
margin-bottom: 1.5rem;
opacity: 0.8;
}
.error-title {
font-size: 2.5rem;
color: var(--nord0);
margin-bottom: 0.5rem;
font-weight: 700;
}
@media (prefers-color-scheme: dark) {
.error-title {
color: var(--nord6);
}
}
.error-code {
font-size: 1.2rem;
color: var(--nord3);
font-weight: 600;
margin-bottom: 1.5rem;
opacity: 0.8;
}
@media (prefers-color-scheme: dark) {
.error-code {
color: var(--nord4);
}
}
.error-description {
font-size: 1.1rem;
color: var(--nord2);
margin-bottom: 1rem;
line-height: 1.6;
}
@media (prefers-color-scheme: dark) {
.error-description {
color: var(--nord5);
}
}
.error-details {
background: var(--nord4);
border-radius: 0.5rem;
padding: 1rem;
margin: 1.5rem 0;
font-size: 0.9rem;
color: var(--nord0);
border-left: 4px solid var(--blue);
}
@media (prefers-color-scheme: dark) {
.error-details {
background: var(--nord2);
color: var(--nord6);
}
}
.error-actions {
display: flex;
gap: 1rem;
justify-content: center;
margin: 2rem 0;
flex-wrap: wrap;
}
.btn {
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
font-weight: 600;
text-decoration: none;
border: none;
cursor: pointer;
transition: all 0.2s ease;
font-size: 1rem;
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.btn-primary {
background: linear-gradient(135deg, var(--blue), var(--lightblue));
color: white;
}
.btn-primary:hover {
background: linear-gradient(135deg, var(--lightblue), var(--blue));
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(94, 129, 172, 0.3);
}
.btn-secondary {
background: var(--nord4);
color: var(--nord0);
border: 1px solid var(--nord3);
}
.btn-secondary:hover {
background: var(--nord3);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
@media (prefers-color-scheme: dark) {
.btn-secondary {
background: var(--nord2);
color: var(--nord6);
border-color: var(--nord3);
}
.btn-secondary:hover {
background: var(--nord3);
}
}
.bible-quote {
margin: 2.5rem 0;
padding: 2rem;
background: linear-gradient(135deg, var(--nord5), var(--nord4));
border-radius: 0.75rem;
border-left: 4px solid var(--blue);
font-style: italic;
}
@media (prefers-color-scheme: dark) {
.bible-quote {
background: linear-gradient(135deg, var(--nord2), var(--nord3));
}
}
.quote-text {
font-size: 1.1rem;
line-height: 1.6;
color: var(--nord0);
margin-bottom: 1rem;
text-align: left;
}
@media (prefers-color-scheme: dark) {
.quote-text {
color: var(--nord6);
}
}
.quote-reference {
font-size: 0.9rem;
color: var(--nord2);
font-weight: 600;
text-align: right;
font-style: normal;
}
@media (prefers-color-scheme: dark) {
.quote-reference {
color: var(--nord4);
}
}
@media (max-width: 600px) {
.error-container {
padding: 2rem;
margin: 1rem;
}
.error-title {
font-size: 2rem;
}
.error-actions {
flex-direction: column;
align-items: center;
}
.btn {
width: 100%;
max-width: 250px;
}
.bible-quote {
padding: 1.5rem;
}
.quote-text {
font-size: 1rem;
}
}
</style>

View File

@@ -0,0 +1,73 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
interface BibleVerse {
bookName: string;
abbreviation: string;
chapter: number;
verse: number;
verseNumber: number;
text: string;
}
// Cache for parsed verses to avoid reading file repeatedly
let cachedVerses: BibleVerse[] | null = null;
async function loadVerses(fetch: typeof globalThis.fetch): Promise<BibleVerse[]> {
if (cachedVerses) {
return cachedVerses;
}
try {
const response = await fetch('/allioli.tsv');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const content = await response.text();
const lines = content.trim().split('\n');
cachedVerses = lines.map(line => {
const [bookName, abbreviation, chapter, verse, verseNumber, text] = line.split('\t');
return {
bookName,
abbreviation,
chapter: parseInt(chapter),
verse: parseInt(verse),
verseNumber: parseInt(verseNumber),
text
};
});
return cachedVerses;
} catch (err) {
console.error('Error loading Bible verses:', err);
throw new Error('Failed to load Bible verses');
}
}
function getRandomVerse(verses: BibleVerse[]): BibleVerse {
const randomIndex = Math.floor(Math.random() * verses.length);
return verses[randomIndex];
}
function formatVerse(verse: BibleVerse): string {
return `${verse.bookName} ${verse.chapter}:${verse.verseNumber}`;
}
export const GET: RequestHandler = async ({ fetch }) => {
try {
const verses = await loadVerses(fetch);
const randomVerse = getRandomVerse(verses);
return json({
text: randomVerse.text,
reference: formatVerse(randomVerse),
book: randomVerse.bookName,
chapter: randomVerse.chapter,
verse: randomVerse.verseNumber
});
} catch (err) {
console.error('Error fetching random Bible verse:', err);
return error(500, 'Failed to fetch Bible verse');
}
};

View File

@@ -1,7 +1,7 @@
import type { RequestHandler } from '@sveltejs/kit';
import { PaymentSplit } from '../../../../models/PaymentSplit';
import { Payment } from '../../../../models/Payment'; // Need to import Payment for populate to work
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { error, json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ locals, url }) => {
@@ -94,7 +94,5 @@ export const GET: RequestHandler = async ({ locals, url }) => {
} catch (e) {
console.error('Error calculating balance:', e);
throw error(500, 'Failed to calculate balance');
} finally {
await dbDisconnect();
}
};

View File

@@ -1,7 +1,7 @@
import type { RequestHandler } from '@sveltejs/kit';
import { PaymentSplit } from '../../../../models/PaymentSplit';
import { Payment } from '../../../../models/Payment';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { error, json } from '@sveltejs/kit';
interface DebtSummary {
@@ -105,6 +105,6 @@ export const GET: RequestHandler = async ({ locals }) => {
console.error('Error calculating debt breakdown:', e);
throw error(500, 'Failed to calculate debt breakdown');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -0,0 +1,115 @@
import type { RequestHandler } from '@sveltejs/kit';
import { ExchangeRate } from '../../../../models/ExchangeRate';
import { dbConnect } from '../../../../utils/db';
import { error, json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ locals, url }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const fromCurrency = url.searchParams.get('from')?.toUpperCase();
const date = url.searchParams.get('date');
const action = url.searchParams.get('action') || 'rate';
if (action === 'currencies') {
return await getSupportedCurrencies();
}
if (!fromCurrency || !date) {
throw error(400, 'Missing required parameters: from and date');
}
if (!isValidCurrencyCode(fromCurrency)) {
throw error(400, 'Invalid currency code');
}
try {
const rate = await getExchangeRate(fromCurrency, date);
return json({ rate, fromCurrency, toCurrency: 'CHF', date });
} catch (e) {
console.error('Error getting exchange rate:', e);
throw error(500, 'Failed to get exchange rate');
}
};
async function getExchangeRate(fromCurrency: string, date: string): Promise<number> {
if (fromCurrency === 'CHF') {
return 1;
}
const dateStr = date.split('T')[0]; // Extract YYYY-MM-DD
await dbConnect();
try {
// Try cache first
const cachedRate = await ExchangeRate.findOne({
fromCurrency,
toCurrency: 'CHF',
date: dateStr
});
if (cachedRate) {
return cachedRate.rate;
}
// Fetch from API
const rate = await fetchFromFrankfurterAPI(fromCurrency, dateStr);
// Cache the result
await ExchangeRate.create({
fromCurrency,
toCurrency: 'CHF',
rate,
date: dateStr
});
return rate;
} finally {
// Connection will be reused
}
}
async function fetchFromFrankfurterAPI(fromCurrency: string, date: string): Promise<number> {
const url = `https://api.frankfurter.app/${date}?from=${fromCurrency}&to=CHF`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Frankfurter API request failed: ${response.status}`);
}
const data = await response.json();
if (!data.rates || !data.rates.CHF) {
throw new Error(`No exchange rate found for ${fromCurrency} to CHF on ${date}`);
}
return data.rates.CHF;
}
async function getSupportedCurrencies() {
try {
const response = await fetch('https://api.frankfurter.app/currencies');
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const data = await response.json();
const currencies = Object.keys(data);
return json({ currencies });
} catch (e) {
console.error('Error fetching supported currencies:', e);
// Return common currencies as fallback
const fallbackCurrencies = ['EUR', 'USD', 'GBP', 'JPY', 'CAD', 'AUD', 'SEK', 'NOK', 'DKK'];
return json({ currencies: fallbackCurrencies });
}
}
function isValidCurrencyCode(currency: string): boolean {
return /^[A-Z]{3}$/.test(currency);
}

View File

@@ -106,9 +106,23 @@ export const GET: RequestHandler = async ({ url, locals }) => {
});
// Convert to arrays for Chart.js
const months = Array.from(monthsMap.keys()).sort();
const allMonths = Array.from(monthsMap.keys()).sort();
const categoryList = Array.from(categories).sort();
// Find the first month with any data and trim empty months from the start
let firstMonthWithData = 0;
for (let i = 0; i < allMonths.length; i++) {
const monthData = monthsMap.get(allMonths[i]);
const hasData = Object.values(monthData).some(value => value > 0);
if (hasData) {
firstMonthWithData = i;
break;
}
}
// Trim the months array to start from the first month with data
const months = allMonths.slice(firstMonthWithData);
const datasets = categoryList.map((category: string) => ({
label: category,
data: months.map(month => monthsMap.get(month)[category] || 0)

View File

@@ -1,7 +1,8 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Payment } from '../../../../models/Payment';
import { PaymentSplit } from '../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { convertToCHF, isValidCurrencyCode } from '../../../../lib/utils/currency';
import { error, json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ locals, url }) => {
@@ -27,7 +28,7 @@ export const GET: RequestHandler = async ({ locals, url }) => {
} catch (e) {
throw error(500, 'Failed to fetch payments');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -38,7 +39,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
}
const data = await request.json();
const { title, description, amount, paidBy, date, image, category, splitMethod, splits } = data;
const { title, description, amount, currency, paidBy, date, image, category, splitMethod, splits } = data;
if (!title || !amount || !paidBy || !splitMethod || !splits) {
throw error(400, 'Missing required fields');
@@ -56,6 +57,12 @@ export const POST: RequestHandler = async ({ request, locals }) => {
throw error(400, 'Invalid category');
}
// Validate currency if provided
const inputCurrency = currency?.toUpperCase() || 'CHF';
if (currency && !isValidCurrencyCode(inputCurrency)) {
throw error(400, 'Invalid currency code');
}
// Validate personal + equal split method
if (splitMethod === 'personal_equal' && splits) {
const totalPersonal = splits.reduce((sum: number, split: any) => {
@@ -67,30 +74,66 @@ export const POST: RequestHandler = async ({ request, locals }) => {
}
}
const paymentDate = date ? new Date(date) : new Date();
let finalAmount = amount;
let originalAmount: number | undefined;
let exchangeRate: number | undefined;
// Convert currency if not CHF
if (inputCurrency !== 'CHF') {
try {
const conversion = await convertToCHF(amount, inputCurrency, paymentDate.toISOString());
finalAmount = conversion.convertedAmount;
originalAmount = amount;
exchangeRate = conversion.exchangeRate;
} catch (e) {
console.error('Currency conversion error:', e);
throw error(400, `Failed to convert ${inputCurrency} to CHF: ${e.message}`);
}
}
await dbConnect();
try {
const payment = await Payment.create({
title,
description,
amount,
currency: 'CHF',
amount: finalAmount,
currency: inputCurrency,
originalAmount,
exchangeRate,
paidBy,
date: date ? new Date(date) : new Date(),
date: paymentDate,
image,
category: category || 'groceries',
splitMethod,
createdBy: auth.user.nickname
});
const splitPromises = splits.map((split: any) => {
return PaymentSplit.create({
// Convert split amounts to CHF if needed
const convertedSplits = splits.map((split: any) => {
let convertedAmount = split.amount;
let convertedPersonalAmount = split.personalAmount;
// Convert amounts if we have a foreign currency
if (inputCurrency !== 'CHF' && exchangeRate) {
convertedAmount = split.amount * exchangeRate;
if (split.personalAmount) {
convertedPersonalAmount = split.personalAmount * exchangeRate;
}
}
return {
paymentId: payment._id,
username: split.username,
amount: split.amount,
amount: convertedAmount,
proportion: split.proportion,
personalAmount: split.personalAmount
personalAmount: convertedPersonalAmount
};
});
const splitPromises = convertedSplits.map((split) => {
return PaymentSplit.create(split);
});
await Promise.all(splitPromises);
@@ -104,6 +147,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
console.error('Error creating payment:', e);
throw error(500, 'Failed to create payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -1,7 +1,7 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Payment } from '../../../../../models/Payment';
import { PaymentSplit } from '../../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ params, locals }) => {
@@ -26,7 +26,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
if (e.status === 404) throw e;
throw error(500, 'Failed to fetch payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -88,7 +88,7 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {
if (e.status) throw e;
throw error(500, 'Failed to update payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -121,6 +121,6 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
if (e.status) throw e;
throw error(500, 'Failed to delete payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -1,6 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../models/RecurringPayment';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate, validateCronExpression } from '../../../../lib/utils/recurring';
@@ -33,7 +33,7 @@ export const GET: RequestHandler = async ({ locals, url }) => {
console.error('Error fetching recurring payments:', e);
throw error(500, 'Failed to fetch recurring payments');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -134,6 +134,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
console.error('Error creating recurring payment:', e);
throw error(500, 'Failed to create recurring payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -1,6 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate, validateCronExpression } from '../../../../../lib/utils/recurring';
import mongoose from 'mongoose';
@@ -30,7 +30,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
console.error('Error fetching recurring payment:', e);
throw error(500, 'Failed to fetch recurring payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -149,7 +149,7 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {
}
throw error(500, 'Failed to update recurring payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};
@@ -179,6 +179,6 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
console.error('Error deleting recurring payment:', e);
throw error(500, 'Failed to delete recurring payment');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -2,7 +2,7 @@ import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { Payment } from '../../../../../models/Payment';
import { PaymentSplit } from '../../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
@@ -119,6 +119,6 @@ export const POST: RequestHandler = async ({ request }) => {
console.error('[Cron] Error executing recurring payments:', e);
throw error(500, 'Failed to execute recurring payments');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -2,9 +2,10 @@ import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { Payment } from '../../../../../models/Payment';
import { PaymentSplit } from '../../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
import { convertToCHF } from '../../../../../lib/utils/currency';
export const POST: RequestHandler = async ({ locals }) => {
const auth = await locals.auth();
@@ -32,12 +33,35 @@ export const POST: RequestHandler = async ({ locals }) => {
for (const recurringPayment of duePayments) {
try {
// Handle currency conversion for execution date
let finalAmount = recurringPayment.amount;
let originalAmount: number | undefined;
let exchangeRate: number | undefined;
if (recurringPayment.currency !== 'CHF') {
try {
const conversion = await convertToCHF(
recurringPayment.amount,
recurringPayment.currency,
now.toISOString()
);
finalAmount = conversion.convertedAmount;
originalAmount = recurringPayment.amount;
exchangeRate = conversion.exchangeRate;
} catch (conversionError) {
console.error(`Currency conversion failed for recurring payment ${recurringPayment._id}:`, conversionError);
// Continue with original amount if conversion fails
}
}
// Create the payment
const payment = await Payment.create({
title: recurringPayment.title,
description: recurringPayment.description,
amount: recurringPayment.amount,
amount: finalAmount,
currency: recurringPayment.currency,
originalAmount,
exchangeRate,
paidBy: recurringPayment.paidBy,
date: now,
category: recurringPayment.category,
@@ -45,15 +69,31 @@ export const POST: RequestHandler = async ({ locals }) => {
createdBy: recurringPayment.createdBy
});
// Create payment splits
const splitPromises = recurringPayment.splits.map((split) => {
return PaymentSplit.create({
// Convert split amounts to CHF if needed
const convertedSplits = recurringPayment.splits.map((split) => {
let convertedAmount = split.amount || 0;
let convertedPersonalAmount = split.personalAmount;
// Convert amounts if we have a foreign currency and exchange rate
if (recurringPayment.currency !== 'CHF' && exchangeRate && split.amount) {
convertedAmount = split.amount * exchangeRate;
if (split.personalAmount) {
convertedPersonalAmount = split.personalAmount * exchangeRate;
}
}
return {
paymentId: payment._id,
username: split.username,
amount: split.amount,
amount: convertedAmount,
proportion: split.proportion,
personalAmount: split.personalAmount
personalAmount: convertedPersonalAmount
};
});
// Create payment splits
const splitPromises = convertedSplits.map((split) => {
return PaymentSplit.create(split);
});
await Promise.all(splitPromises);
@@ -99,6 +139,6 @@ export const POST: RequestHandler = async ({ locals }) => {
console.error('Error executing recurring payments:', e);
throw error(500, 'Failed to execute recurring payments');
} finally {
await dbDisconnect();
// Connection will be reused
}
};

View File

@@ -1,6 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { error } from '@sveltejs/kit';
// header: use for bearer token for now
// recipe json in body
@@ -22,7 +22,6 @@ export const POST: RequestHandler = async ({request, cookies, locals}) => {
} catch(e){
throw error(400, e)
}
await dbDisconnect();
return new Response(JSON.stringify({msg: "Added recipe successfully"}),{
status: 200,
});

View File

@@ -1,6 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import type {RecipeModelType} from '../../../../types/types';
import { error } from '@sveltejs/kit';
// header: use for bearer token for now
@@ -14,7 +14,6 @@ export const POST: RequestHandler = async ({request, locals}) => {
const short_name = message.old_short_name
await dbConnect();
await Recipe.findOneAndDelete({short_name: short_name});
await dbDisconnect();
return new Response(JSON.stringify({msg: "Deleted recipe successfully"}),{
status: 200,
});

View File

@@ -1,6 +1,6 @@
import type { RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import type {RecipeModelType} from '../../../../types/types';
import { error } from '@sveltejs/kit';
// header: use for bearer token for now
@@ -15,7 +15,6 @@ export const POST: RequestHandler = async ({request, locals}) => {
else{
await dbConnect();
await Recipe.findOneAndUpdate({short_name: message.old_short_name }, recipe_json);
await dbDisconnect();
return new Response(JSON.stringify({msg: "Edited recipe successfully"}),{
status: 200,
});

View File

@@ -1,7 +1,7 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { UserFavorites } from '../../../../models/UserFavorites';
import { Recipe } from '../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
import { error } from '@sveltejs/kit';
import mongoose from 'mongoose';
@@ -19,13 +19,11 @@ export const GET: RequestHandler = async ({ locals }) => {
username: session.user.nickname
}).lean();
await dbDisconnect();
return json({
favorites: userFavorites?.favorites || []
});
} catch (e) {
await dbDisconnect();
throw error(500, 'Failed to fetch favorites');
}
};
@@ -49,7 +47,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
// Validate that the recipe exists and get its ObjectId
const recipe = await Recipe.findOne({ short_name: recipeId });
if (!recipe) {
await dbDisconnect();
throw error(404, 'Recipe not found');
}
@@ -59,11 +56,9 @@ export const POST: RequestHandler = async ({ request, locals }) => {
{ upsert: true, new: true }
);
await dbDisconnect();
return json({ success: true });
} catch (e) {
await dbDisconnect();
if (e instanceof Error && e.message.includes('404')) {
throw e;
}
@@ -90,7 +85,6 @@ export const DELETE: RequestHandler = async ({ request, locals }) => {
// Find the recipe's ObjectId
const recipe = await Recipe.findOne({ short_name: recipeId });
if (!recipe) {
await dbDisconnect();
throw error(404, 'Recipe not found');
}
@@ -99,11 +93,9 @@ export const DELETE: RequestHandler = async ({ request, locals }) => {
{ $pull: { favorites: recipe._id } }
);
await dbDisconnect();
return json({ success: true });
} catch (e) {
await dbDisconnect();
if (e instanceof Error && e.message.includes('404')) {
throw e;
}

View File

@@ -1,7 +1,7 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { UserFavorites } from '../../../../../../models/UserFavorites';
import { Recipe } from '../../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
import { dbConnect } from '../../../../../../utils/db';
import { error } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ locals, params }) => {
@@ -17,7 +17,6 @@ export const GET: RequestHandler = async ({ locals, params }) => {
// Find the recipe by short_name to get its ObjectId
const recipe = await Recipe.findOne({ short_name: params.shortName });
if (!recipe) {
await dbDisconnect();
throw error(404, 'Recipe not found');
}
@@ -27,13 +26,11 @@ export const GET: RequestHandler = async ({ locals, params }) => {
favorites: recipe._id
}).lean();
await dbDisconnect();
return json({
isFavorite: !!userFavorites
});
} catch (e) {
await dbDisconnect();
if (e instanceof Error && e.message.includes('404')) {
throw e;
}

View File

@@ -1,7 +1,7 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { UserFavorites } from '../../../../../models/UserFavorites';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import type { RecipeModelType } from '../../../../../types/types';
import { error } from '@sveltejs/kit';
@@ -20,7 +20,6 @@ export const GET: RequestHandler = async ({ locals }) => {
}).lean();
if (!userFavorites?.favorites?.length) {
await dbDisconnect();
return json([]);
}
@@ -28,13 +27,11 @@ export const GET: RequestHandler = async ({ locals }) => {
_id: { $in: userFavorites.favorites }
}).lean() as RecipeModelType[];
await dbDisconnect();
recipes = JSON.parse(JSON.stringify(recipes));
return json(recipes);
} catch (e) {
await dbDisconnect();
throw error(500, 'Failed to fetch favorite recipes');
}
};

View File

@@ -1,13 +1,12 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import type {RecipeModelType} from '../../../../../types/types';
import { error } from '@sveltejs/kit';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let recipe = (await Recipe.findOne({ short_name: params.name}).lean()) as RecipeModelType[];
await dbDisconnect();
recipe = JSON.parse(JSON.stringify(recipe));
if(recipe == null){

View File

@@ -1,12 +1,11 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import type { BriefRecipeType } from '../../../../../types/types';
import { Recipe } from '../../../../../models/Recipe'
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { rand_array } from '$lib/js/randomize';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let found_brief = rand_array(await Recipe.find({}, 'name short_name tags category icon description season dateModified').lean()) as BriefRecipeType[];
await dbDisconnect();
return json(JSON.parse(JSON.stringify(found_brief)));
};

View File

@@ -1,12 +1,11 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../types/types';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let categories = (await Recipe.distinct('category').lean());
await dbDisconnect();
categories= JSON.parse(JSON.stringify(categories));
return json(categories);

View File

@@ -1,13 +1,12 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
import { dbConnect } from '../../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../../types/types';
import { rand_array } from '$lib/js/randomize';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let recipes = rand_array(await Recipe.find({category: params.category}, 'name short_name images tags category icon description season dateModified').lean()) as BriefRecipeType[];
await dbDisconnect();
recipes = JSON.parse(JSON.stringify(recipes));
return json(recipes);

View File

@@ -1,12 +1,11 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../types/types';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let icons = (await Recipe.distinct('icon').lean());
await dbDisconnect();
icons = JSON.parse(JSON.stringify(icons));
return json(icons);

View File

@@ -1,13 +1,12 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
import { dbConnect } from '../../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../../types/types';
import { rand_array } from '$lib/js/randomize';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let recipes = rand_array(await Recipe.find({icon: params.icon}, 'name short_name images tags category icon description season dateModified').lean()) as BriefRecipeType[];
await dbDisconnect();
recipes = JSON.parse(JSON.stringify(recipes));
return json(recipes);

View File

@@ -1,13 +1,12 @@
import type {rand_array} from '$lib/js/randomize';
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../../models/Recipe'
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
import { dbConnect } from '../../../../../../utils/db';
import { rand_array } from '$lib/js/randomize';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let found_in_season = rand_array(await Recipe.find({season: params.month, icon: {$ne: "🍽️"}}, 'name short_name images tags category icon description season dateModified').lean());
await dbDisconnect();
found_in_season = JSON.parse(JSON.stringify(found_in_season));
return json(found_in_season);
};

View File

@@ -1,12 +1,11 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../types/types';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let categories = (await Recipe.distinct('tags').lean());
await dbDisconnect();
categories= JSON.parse(JSON.stringify(categories));
return json(categories);

View File

@@ -1,13 +1,12 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
import { dbConnect } from '../../../../../../utils/db';
import type {BriefRecipeType} from '../../../../../../types/types';
import { rand_array } from '$lib/js/randomize';
export const GET: RequestHandler = async ({params}) => {
await dbConnect();
let recipes = rand_array(await Recipe.find({tags: params.tag}, 'name short_name images tags category icon description season dateModified').lean()) as BriefRecipeType[];
await dbDisconnect();
recipes = JSON.parse(JSON.stringify(recipes));
return json(recipes);

View File

@@ -1,6 +1,6 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import { Recipe } from '../../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { dbConnect } from '../../../../../utils/db';
import { generateRecipeJsonLd } from '$lib/js/recipeJsonLd';
import type { RecipeModelType } from '../../../../../types/types';
import { error } from '@sveltejs/kit';
@@ -8,7 +8,6 @@ import { error } from '@sveltejs/kit';
export const GET: RequestHandler = async ({ params, setHeaders }) => {
await dbConnect();
let recipe = (await Recipe.findOne({ short_name: params.name }).lean()) as RecipeModelType;
await dbDisconnect();
recipe = JSON.parse(JSON.stringify(recipe));
if (recipe == null) {

View File

@@ -1,7 +1,7 @@
import { json, type RequestHandler } from '@sveltejs/kit';
import type { BriefRecipeType } from '../../../../types/types';
import { Recipe } from '../../../../models/Recipe';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { dbConnect } from '../../../../utils/db';
export const GET: RequestHandler = async ({ url, locals }) => {
await dbConnect();
@@ -64,11 +64,9 @@ export const GET: RequestHandler = async ({ url, locals }) => {
});
}
await dbDisconnect();
return json(JSON.parse(JSON.stringify(recipes)));
} catch (error) {
await dbDisconnect();
return json({ error: 'Search failed' }, { status: 500 });
}
};

View File

@@ -153,6 +153,9 @@
<main class="cospend-main">
<h1>Cospend</h1>
<!-- Responsive layout for balance and chart -->
<div class="dashboard-layout">
<div class="balance-section">
<EnhancedBalance bind:this={enhancedBalanceComponent} initialBalance={data.balance} initialDebtData={data.debtData} />
<div class="actions">
@@ -162,6 +165,7 @@
</div>
<DebtBreakdown bind:this={debtBreakdownComponent} />
</div>
<!-- Monthly Expenses Chart -->
<div class="chart-section">
@@ -181,6 +185,7 @@
</div>
{/if}
</div>
</div>
{#if loading}
<div class="loading">Loading recent activity...</div>
@@ -274,7 +279,6 @@
<style>
.cospend-main {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
@@ -355,6 +359,9 @@
border-radius: 0.75rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border: 1px solid var(--nord4);
max-width: 800px;
margin-left: auto;
margin-right: auto;
}
.recent-activity h2 {
@@ -705,8 +712,33 @@
}
}
.chart-section {
.dashboard-layout {
display: flex;
flex-direction: column;
gap: 2rem;
margin-bottom: 2rem;
max-width: 1400px;
margin-left: auto;
margin-right: auto;
}
@media (min-width: 1200px) {
.dashboard-layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 3rem;
align-items: start;
}
.balance-section {
display: flex;
flex-direction: column;
gap: 2rem;
}
}
.chart-section {
min-height: 400px;
}
.chart-section .loading {

View File

@@ -80,13 +80,21 @@
}
}
function formatCurrency(amount) {
function formatCurrency(amount, currency = 'CHF') {
return new Intl.NumberFormat('de-CH', {
style: 'currency',
currency: 'CHF'
currency: currency
}).format(amount);
}
function formatAmountWithCurrency(payment) {
if (payment.currency === 'CHF' || !payment.originalAmount) {
return formatCurrency(payment.amount);
}
return `${formatCurrency(payment.originalAmount, payment.currency)}${formatCurrency(payment.amount)}`;
}
function formatDate(dateString) {
return new Date(dateString).toLocaleDateString('de-CH');
}
@@ -158,7 +166,7 @@
</div>
</div>
<div class="settlement-amount">
<span class="amount settlement-amount-text">{formatCurrency(payment.amount)}</span>
<span class="amount settlement-amount-text">{formatAmountWithCurrency(payment)}</span>
<span class="date">{formatDate(payment.date)}</span>
</div>
{:else}
@@ -172,7 +180,7 @@
<div class="payment-meta">
<span class="category-name">{getCategoryName(payment.category || 'groceries')}</span>
<span class="date">{formatDate(payment.date)}</span>
<span class="amount">{formatCurrency(payment.amount)}</span>
<span class="amount">{formatAmountWithCurrency(payment)}</span>
</div>
</div>
</div>

View File

@@ -28,6 +28,7 @@ export const actions: Actions = {
const title = formData.get('title')?.toString().trim();
const description = formData.get('description')?.toString().trim() || '';
const amount = parseFloat(formData.get('amount')?.toString() || '0');
const currency = formData.get('currency')?.toString()?.toUpperCase() || 'CHF';
const paidBy = formData.get('paidBy')?.toString().trim();
const date = formData.get('date')?.toString();
const category = formData.get('category')?.toString() || 'groceries';
@@ -155,6 +156,7 @@ export const actions: Actions = {
title,
description,
amount,
currency,
paidBy,
date: date || new Date().toISOString().split('T')[0],
category,
@@ -186,6 +188,7 @@ export const actions: Actions = {
title,
description,
amount,
currency,
paidBy,
category,
splitMethod,

View File

@@ -18,6 +18,7 @@
title: form?.values?.title || '',
description: form?.values?.description || '',
amount: form?.values?.amount || '',
currency: form?.values?.currency || 'CHF',
paidBy: form?.values?.paidBy || data.currentUser || '',
date: form?.values?.date || new Date().toISOString().split('T')[0],
category: form?.values?.category || 'groceries',
@@ -46,6 +47,13 @@
let jsEnhanced = false;
let cronError = false;
let nextExecutionPreview = '';
let supportedCurrencies = ['CHF'];
let loadingCurrencies = false;
let currentExchangeRate = null;
let convertedAmount = null;
let loadingExchangeRate = false;
let exchangeRateError = null;
let exchangeRateTimeout;
// Initialize users from server data for no-JS support
let users = predefinedMode ? [...data.predefinedUsers] : (data.currentUser ? [data.currentUser] : []);
@@ -89,7 +97,7 @@
}
})();
onMount(() => {
onMount(async () => {
jsEnhanced = true;
document.body.classList.add('js-loaded');
@@ -110,8 +118,65 @@
addSplitForUser(data.currentUser);
}
}
// Load supported currencies
await loadSupportedCurrencies();
});
async function loadSupportedCurrencies() {
try {
loadingCurrencies = true;
const response = await fetch('/api/cospend/exchange-rates?action=currencies');
if (response.ok) {
const data = await response.json();
supportedCurrencies = ['CHF', ...data.currencies.filter(c => c !== 'CHF')];
}
} catch (e) {
console.warn('Could not load supported currencies:', e);
// Keep default CHF
} finally {
loadingCurrencies = false;
}
}
async function fetchExchangeRate() {
if (formData.currency === 'CHF' || !formData.currency || !formData.date) {
currentExchangeRate = null;
convertedAmount = null;
exchangeRateError = null;
return;
}
if (!formData.amount || parseFloat(formData.amount) <= 0) {
convertedAmount = null;
return;
}
try {
loadingExchangeRate = true;
exchangeRateError = null;
const url = `/api/cospend/exchange-rates?from=${formData.currency}&date=${formData.date}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch exchange rate');
}
const data = await response.json();
currentExchangeRate = data.rate;
convertedAmount = parseFloat(formData.amount) * data.rate;
} catch (e) {
console.warn('Could not fetch exchange rate:', e);
exchangeRateError = e.message;
currentExchangeRate = null;
convertedAmount = null;
} finally {
loadingExchangeRate = false;
}
}
function handleImageSelected(event) {
imageFile = event.detail;
}
@@ -190,6 +255,7 @@
const payload = {
...formData,
amount: parseFloat(formData.amount),
currency: formData.currency,
image: imagePath,
splits
};
@@ -257,6 +323,13 @@
$: if (recurringData.frequency || recurringData.cronExpression || recurringData.startDate || formData.isRecurring) {
updateNextExecutionPreview();
}
// Fetch exchange rate when currency, amount, or date changes
$: if (jsEnhanced && formData.currency && formData.currency !== 'CHF' && formData.date && formData.amount) {
// Add a small delay to avoid excessive API calls while user is typing
clearTimeout(exchangeRateTimeout);
exchangeRateTimeout = setTimeout(fetchExchangeRate, 300);
}
</script>
<svelte:head>
@@ -307,7 +380,8 @@
<div class="form-row">
<div class="form-group">
<label for="amount">Amount (CHF) *</label>
<label for="amount">Amount *</label>
<div class="amount-currency">
<input
type="number"
id="amount"
@@ -318,17 +392,49 @@
step="0.01"
placeholder="0.00"
/>
<select id="currency" name="currency" bind:value={formData.currency} disabled={loadingCurrencies}>
{#each supportedCurrencies as currency}
<option value={currency}>{currency}</option>
{/each}
</select>
</div>
{#if formData.currency !== 'CHF'}
<div class="conversion-info">
<small class="help-text">Amount will be converted to CHF using exchange rates for the payment date</small>
{#if loadingExchangeRate}
<div class="conversion-preview loading">
<small>🔄 Fetching exchange rate...</small>
</div>
{:else if exchangeRateError}
<div class="conversion-preview error">
<small>⚠️ {exchangeRateError}</small>
</div>
{:else if convertedAmount !== null && currentExchangeRate !== null && formData.amount}
<div class="conversion-preview success">
<small>
{formData.currency} {parseFloat(formData.amount).toFixed(2)} ≈ CHF {convertedAmount.toFixed(2)}
<br>
(Rate: 1 {formData.currency} = {currentExchangeRate.toFixed(4)} CHF)
</small>
</div>
{/if}
</div>
{/if}
</div>
<div class="form-group">
<label for="date">Date</label>
<label for="date">Payment Date</label>
<input
type="date"
id="date"
name="date"
value={formData.date}
bind:value={formData.date}
required
/>
{#if formData.currency !== 'CHF'}
<small class="help-text">Exchange rate will be fetched for this date</small>
{/if}
</div>
</div>
@@ -480,6 +586,7 @@
bind:personalAmounts={personalAmounts}
{users}
amount={formData.amount}
currency={formData.currency}
paidBy={formData.paidBy}
currentUser={data.session?.user?.nickname || data.currentUser}
{predefinedMode}
@@ -851,6 +958,71 @@
}
}
/* Amount-currency styling */
.amount-currency {
display: flex;
gap: 0.5rem;
}
.amount-currency input {
flex: 2;
}
.amount-currency select {
flex: 1;
min-width: 80px;
}
/* Currency conversion preview */
.conversion-info {
margin-top: 0.5rem;
}
.conversion-preview {
margin-top: 0.5rem;
padding: 0.75rem;
border-radius: 0.5rem;
border: 1px solid transparent;
}
.conversion-preview.loading {
background-color: var(--nord8);
border-color: var(--blue);
color: var(--blue);
}
.conversion-preview.error {
background-color: var(--nord6);
border-color: var(--red);
color: var(--red);
}
.conversion-preview.success {
background-color: var(--nord14);
border-color: var(--green);
color: var(--nord0);
}
.conversion-preview small {
font-size: 0.85rem;
font-weight: 500;
}
@media (prefers-color-scheme: dark) {
.conversion-preview.loading {
background-color: var(--nord2);
}
.conversion-preview.error {
background-color: var(--accent-dark);
}
.conversion-preview.success {
background-color: var(--nord2);
color: var(--font-default-dark);
}
}
@media (max-width: 600px) {
.add-payment {
padding: 1rem;
@@ -863,5 +1035,14 @@
.form-actions {
flex-direction: column;
}
.amount-currency {
flex-direction: column;
}
.amount-currency input,
.amount-currency select {
flex: none;
}
}
</style>

View File

@@ -14,11 +14,22 @@
let error = null;
let imageFile = null;
let imagePreview = '';
let supportedCurrencies = ['CHF'];
let loadingCurrencies = false;
let currentExchangeRate = null;
let convertedAmount = null;
let loadingExchangeRate = false;
let exchangeRateError = null;
let exchangeRateTimeout;
let jsEnhanced = false;
$: categoryOptions = getCategoryOptions();
onMount(async () => {
jsEnhanced = true;
document.body.classList.add('js-loaded');
await loadPayment();
await loadSupportedCurrencies();
});
async function loadPayment() {
@@ -139,6 +150,71 @@
deleting = false;
}
}
async function loadSupportedCurrencies() {
try {
loadingCurrencies = true;
const response = await fetch('/api/cospend/exchange-rates?action=currencies');
if (response.ok) {
const data = await response.json();
supportedCurrencies = ['CHF', ...data.currencies.filter(c => c !== 'CHF')];
}
} catch (e) {
console.warn('Could not load supported currencies:', e);
} finally {
loadingCurrencies = false;
}
}
async function fetchExchangeRate() {
if (!payment || payment.currency === 'CHF' || !payment.currency || !payment.date) {
currentExchangeRate = null;
convertedAmount = null;
exchangeRateError = null;
return;
}
if (!payment.originalAmount || payment.originalAmount <= 0) {
convertedAmount = null;
return;
}
try {
loadingExchangeRate = true;
exchangeRateError = null;
const dateStr = new Date(payment.date).toISOString().split('T')[0];
const url = `/api/cospend/exchange-rates?from=${payment.currency}&date=${dateStr}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch exchange rate');
}
const data = await response.json();
currentExchangeRate = data.rate;
convertedAmount = payment.originalAmount * data.rate;
} catch (e) {
console.warn('Could not fetch exchange rate:', e);
exchangeRateError = e.message;
currentExchangeRate = null;
convertedAmount = null;
} finally {
loadingExchangeRate = false;
}
}
// Reactive statement for exchange rate fetching
$: if (jsEnhanced && payment && payment.currency && payment.currency !== 'CHF' && payment.date && payment.originalAmount) {
clearTimeout(exchangeRateTimeout);
exchangeRateTimeout = setTimeout(fetchExchangeRate, 300);
}
function formatDateForInput(dateString) {
if (!dateString) return '';
return new Date(dateString).toISOString().split('T')[0];
}
</script>
<svelte:head>
@@ -188,7 +264,25 @@
<div class="form-row">
<div class="form-group">
<label for="amount">Amount (CHF) *</label>
<label for="amount">Amount *</label>
<div class="amount-currency">
{#if payment.originalAmount && payment.currency !== 'CHF'}
<!-- Show original amount for foreign currency -->
<input
type="number"
id="originalAmount"
bind:value={payment.originalAmount}
required
min="0"
step="0.01"
/>
<select id="currency" bind:value={payment.currency} disabled={loadingCurrencies}>
{#each supportedCurrencies as currency}
<option value={currency}>{currency}</option>
{/each}
</select>
{:else}
<!-- Show CHF amount for CHF payments -->
<input
type="number"
id="amount"
@@ -197,6 +291,39 @@
min="0"
step="0.01"
/>
<select id="currency" bind:value={payment.currency} disabled={loadingCurrencies}>
{#each supportedCurrencies as currency}
<option value={currency}>{currency}</option>
{/each}
</select>
{/if}
</div>
{#if payment.currency !== 'CHF' && payment.originalAmount}
<div class="conversion-info">
<small class="help-text">Original amount in {payment.currency}, converted to CHF at payment date</small>
{#if loadingExchangeRate}
<div class="conversion-preview loading">
<small>🔄 Fetching current exchange rate...</small>
</div>
{:else if exchangeRateError}
<div class="conversion-preview error">
<small>⚠️ {exchangeRateError}</small>
</div>
{:else if convertedAmount !== null && currentExchangeRate !== null}
<div class="conversion-preview success">
<small>
{payment.currency} {payment.originalAmount.toFixed(2)} ≈ CHF {convertedAmount.toFixed(2)}
<br>
(Current rate: 1 {payment.currency} = {currentExchangeRate.toFixed(4)} CHF)
<br>
<strong>Stored: CHF {payment.amount.toFixed(2)} (Rate: {payment.exchangeRate ? payment.exchangeRate.toFixed(4) : 'N/A'})</strong>
</small>
</div>
{/if}
</div>
{/if}
</div>
<div class="form-group">
@@ -204,7 +331,7 @@
<input
type="date"
id="date"
value={formatDate(payment.date)}
value={formatDateForInput(payment.date)}
on:change={(e) => payment.date = new Date(e.target.value).toISOString()}
required
/>
@@ -537,6 +664,82 @@
cursor: not-allowed;
}
/* Amount-currency styling */
.amount-currency {
display: flex;
gap: 0.5rem;
}
.amount-currency input {
flex: 2;
}
.amount-currency select {
flex: 1;
min-width: 80px;
}
/* Currency conversion preview */
.conversion-info {
margin-top: 0.5rem;
}
.conversion-preview {
margin-top: 0.5rem;
padding: 0.75rem;
border-radius: 0.5rem;
border: 1px solid transparent;
}
.conversion-preview.loading {
background-color: var(--nord8);
border-color: var(--blue);
color: var(--blue);
}
.conversion-preview.error {
background-color: var(--nord6);
border-color: var(--red);
color: var(--red);
}
.conversion-preview.success {
background-color: var(--nord14);
border-color: var(--green);
color: var(--nord0);
}
.conversion-preview small {
font-size: 0.85rem;
font-weight: 500;
}
.help-text {
display: block;
margin-top: 0.25rem;
font-size: 0.8rem;
color: var(--nord3);
font-style: italic;
}
@media (prefers-color-scheme: dark) {
.conversion-preview.loading {
background-color: var(--nord2);
}
.conversion-preview.error {
background-color: var(--accent-dark);
}
.conversion-preview.success {
background-color: var(--nord2);
color: var(--font-default-dark);
}
.help-text {
color: var(--nord4);
}
}
@media (max-width: 600px) {
.edit-payment {
@@ -555,5 +758,14 @@
.main-actions {
flex-direction: column;
}
.amount-currency {
flex-direction: column;
}
.amount-currency input,
.amount-currency select {
flex: none;
}
}
</style>

View File

@@ -39,13 +39,21 @@
}
}
function formatCurrency(amount) {
function formatCurrency(amount, currency = 'CHF') {
return new Intl.NumberFormat('de-CH', {
style: 'currency',
currency: 'CHF'
currency: currency
}).format(Math.abs(amount));
}
function formatAmountWithCurrency(payment) {
if (payment.currency === 'CHF' || !payment.originalAmount) {
return formatCurrency(payment.amount);
}
return `${formatCurrency(payment.originalAmount, payment.currency)}${formatCurrency(payment.amount)}`;
}
function formatDate(dateString) {
return new Date(dateString).toLocaleDateString('de-CH');
}
@@ -111,7 +119,12 @@
<h1>{payment.title}</h1>
</div>
<div class="payment-amount">
{formatCurrency(payment.amount)}
{formatAmountWithCurrency(payment)}
{#if payment.currency !== 'CHF' && payment.exchangeRate}
<div class="exchange-rate-info">
<small>Exchange rate: 1 {payment.currency} = {payment.exchangeRate.toFixed(4)} CHF</small>
</div>
{/if}
</div>
</div>
{#if payment.image}
@@ -467,6 +480,22 @@
color: var(--red);
}
.exchange-rate-info {
margin-top: 0.5rem;
color: var(--nord3);
font-style: italic;
}
.exchange-rate-info small {
font-size: 0.8rem;
}
@media (prefers-color-scheme: dark) {
.exchange-rate-info {
color: var(--nord4);
}
}
@media (max-width: 600px) {
.payment-view {
padding: 1rem;

View File

@@ -14,6 +14,7 @@
title: '',
description: '',
amount: '',
currency: 'CHF',
paidBy: data.session?.user?.nickname || '',
category: 'groceries',
splitMethod: 'equal',
@@ -35,11 +36,22 @@
let predefinedMode = isPredefinedUsersMode();
let cronError = false;
let nextExecutionPreview = '';
let supportedCurrencies = ['CHF'];
let loadingCurrencies = false;
let currentExchangeRate = null;
let convertedAmount = null;
let loadingExchangeRate = false;
let exchangeRateError = null;
let exchangeRateTimeout;
let jsEnhanced = false;
$: categoryOptions = getCategoryOptions();
onMount(async () => {
jsEnhanced = true;
document.body.classList.add('js-loaded');
await loadRecurringPayment();
await loadSupportedCurrencies();
});
async function loadRecurringPayment() {
@@ -58,6 +70,7 @@
title: payment.title,
description: payment.description || '',
amount: payment.amount.toString(),
currency: payment.currency || 'CHF',
paidBy: payment.paidBy,
category: payment.category,
splitMethod: payment.splitMethod,
@@ -192,6 +205,65 @@
$: if (formData.frequency || formData.cronExpression || formData.startDate) {
updateNextExecutionPreview();
}
async function loadSupportedCurrencies() {
try {
loadingCurrencies = true;
const response = await fetch('/api/cospend/exchange-rates?action=currencies');
if (response.ok) {
const data = await response.json();
supportedCurrencies = ['CHF', ...data.currencies.filter(c => c !== 'CHF')];
}
} catch (e) {
console.warn('Could not load supported currencies:', e);
} finally {
loadingCurrencies = false;
}
}
async function fetchExchangeRate() {
if (formData.currency === 'CHF' || !formData.currency || !formData.startDate) {
currentExchangeRate = null;
convertedAmount = null;
exchangeRateError = null;
return;
}
if (!formData.amount || parseFloat(formData.amount) <= 0) {
convertedAmount = null;
return;
}
try {
loadingExchangeRate = true;
exchangeRateError = null;
const url = `/api/cospend/exchange-rates?from=${formData.currency}&date=${formData.startDate}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch exchange rate');
}
const data = await response.json();
currentExchangeRate = data.rate;
convertedAmount = parseFloat(formData.amount) * data.rate;
} catch (e) {
console.warn('Could not fetch exchange rate:', e);
exchangeRateError = e.message;
currentExchangeRate = null;
convertedAmount = null;
} finally {
loadingExchangeRate = false;
}
}
// Reactive statement for exchange rate fetching
$: if (jsEnhanced && formData.currency && formData.currency !== 'CHF' && formData.startDate && formData.amount) {
clearTimeout(exchangeRateTimeout);
exchangeRateTimeout = setTimeout(fetchExchangeRate, 300);
}
</script>
<svelte:head>
@@ -247,7 +319,8 @@
<div class="form-row">
<div class="form-group">
<label for="amount">Amount (CHF) *</label>
<label for="amount">Amount *</label>
<div class="amount-currency">
<input
type="number"
id="amount"
@@ -257,6 +330,35 @@
step="0.01"
placeholder="0.00"
/>
<select id="currency" bind:value={formData.currency} disabled={loadingCurrencies}>
{#each supportedCurrencies as currency}
<option value={currency}>{currency}</option>
{/each}
</select>
</div>
{#if formData.currency !== 'CHF'}
<div class="conversion-info">
<small class="help-text">Amount will be converted to CHF using exchange rates on each execution</small>
{#if loadingExchangeRate}
<div class="conversion-preview loading">
<small>🔄 Fetching exchange rate for start date...</small>
</div>
{:else if exchangeRateError}
<div class="conversion-preview error">
<small>⚠️ {exchangeRateError}</small>
</div>
{:else if convertedAmount !== null && currentExchangeRate !== null && formData.amount}
<div class="conversion-preview success">
<small>
{formData.currency} {parseFloat(formData.amount).toFixed(2)} ≈ CHF {convertedAmount.toFixed(2)}
<br>
(Rate for start date: 1 {formData.currency} = {currentExchangeRate.toFixed(4)} CHF)
</small>
</div>
{/if}
</div>
{/if}
</div>
<div class="form-group">
@@ -363,6 +465,7 @@
bind:personalAmounts={personalAmounts}
{users}
amount={formData.amount}
currency={formData.currency}
paidBy={formData.paidBy}
currentUser={data.session?.user?.nickname}
{predefinedMode}
@@ -637,6 +740,69 @@
.btn-secondary:hover {
background-color: var(--nord2);
}
.conversion-preview.loading {
background-color: var(--nord2);
}
.conversion-preview.error {
background-color: var(--accent-dark);
}
.conversion-preview.success {
background-color: var(--nord2);
color: var(--font-default-dark);
}
}
/* Amount-currency styling */
.amount-currency {
display: flex;
gap: 0.5rem;
}
.amount-currency input {
flex: 2;
}
.amount-currency select {
flex: 1;
min-width: 80px;
}
/* Currency conversion preview */
.conversion-info {
margin-top: 0.5rem;
}
.conversion-preview {
margin-top: 0.5rem;
padding: 0.75rem;
border-radius: 0.5rem;
border: 1px solid transparent;
}
.conversion-preview.loading {
background-color: var(--nord8);
border-color: var(--blue);
color: var(--blue);
}
.conversion-preview.error {
background-color: var(--nord6);
border-color: var(--red);
color: var(--red);
}
.conversion-preview.success {
background-color: var(--nord14);
border-color: var(--green);
color: var(--nord0);
}
.conversion-preview small {
font-size: 0.85rem;
font-weight: 500;
}
@media (max-width: 600px) {
@@ -651,5 +817,14 @@
.form-actions {
flex-direction: column;
}
.amount-currency {
flex-direction: column;
}
.amount-currency input,
.amount-currency select {
flex: none;
}
}
</style>

View File

@@ -1,35 +1,54 @@
import mongoose from 'mongoose';
import { MONGO_URL } from '$env/static/private';
/*
0 - disconnected
1 - connected
2 - connecting
3 - disconnecting
4 - uninitialized
*/
const mongoConnection = {
isConnected: 0,
};
let isConnected = false;
export const dbConnect = async () => {
if (mongoConnection.isConnected === 1) {
return;
// If already connected, return immediately
if (isConnected && mongoose.connection.readyState === 1) {
return mongoose.connection;
}
if (mongoose.connections.length > 0) {
mongoConnection.isConnected = mongoose.connections[0].readyState;
if (mongoConnection.isConnected === 1) {
return;
}
await mongoose.disconnect();
}
await mongoose.connect(MONGO_URL ?? '');
mongoConnection.isConnected = 1;
try {
// Configure MongoDB driver options
const options = {
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
};
const connection = await mongoose.connect(MONGO_URL ?? '', options);
isConnected = true;
console.log('MongoDB connected with persistent connection');
// Handle connection events
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error:', err);
isConnected = false;
});
mongoose.connection.on('disconnected', () => {
console.log('MongoDB disconnected');
isConnected = false;
});
mongoose.connection.on('reconnected', () => {
console.log('MongoDB reconnected');
isConnected = true;
});
return connection;
} catch (error) {
console.error('MongoDB connection failed:', error);
isConnected = false;
throw error;
}
};
// No longer disconnect - let the connection pool manage connections
export const dbDisconnect = async () => {
// Don't disconnect in production to avoid "Client must be connected" errors
// The connection pool will handle connection cleanup automatically
// Keep connections persistent for performance and to avoid race conditions
// MongoDB driver will handle connection pooling and cleanup automatically
return;
};

31377
static/allioli.tsv Normal file

File diff suppressed because it is too large Load Diff