Compare commits
12 Commits
ac6845d38a
...
master
Author | SHA1 | Date | |
---|---|---|---|
579cbd1bc9
|
|||
c8e542eec8
|
|||
08d7d8541b
|
|||
26abad6b54
|
|||
53b739144a
|
|||
7ffb9c0b86
|
|||
a22471a943
|
|||
4b2250ab03
|
|||
effed784b7
|
|||
b03ba61599
|
|||
db3de29e48
|
|||
e773a90f1d
|
@@ -27,6 +27,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@auth/sveltekit": "^1.10.0",
|
"@auth/sveltekit": "^1.10.0",
|
||||||
"@sveltejs/adapter-node": "^5.0.0",
|
"@sveltejs/adapter-node": "^5.0.0",
|
||||||
|
"chart.js": "^4.5.0",
|
||||||
"cheerio": "1.0.0-rc.12",
|
"cheerio": "1.0.0-rc.12",
|
||||||
"mongoose": "^8.0.0",
|
"mongoose": "^8.0.0",
|
||||||
"node-cron": "^4.2.1",
|
"node-cron": "^4.2.1",
|
||||||
|
16
pnpm-lock.yaml
generated
16
pnpm-lock.yaml
generated
@@ -14,6 +14,9 @@ importers:
|
|||||||
'@sveltejs/adapter-node':
|
'@sveltejs/adapter-node':
|
||||||
specifier: ^5.0.0
|
specifier: ^5.0.0
|
||||||
version: 5.3.1(@sveltejs/kit@2.37.0(@sveltejs/vite-plugin-svelte@6.1.3(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))
|
version: 5.3.1(@sveltejs/kit@2.37.0(@sveltejs/vite-plugin-svelte@6.1.3(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))
|
||||||
|
chart.js:
|
||||||
|
specifier: ^4.5.0
|
||||||
|
version: 4.5.0
|
||||||
cheerio:
|
cheerio:
|
||||||
specifier: 1.0.0-rc.12
|
specifier: 1.0.0-rc.12
|
||||||
version: 1.0.0-rc.12
|
version: 1.0.0-rc.12
|
||||||
@@ -376,6 +379,9 @@ packages:
|
|||||||
'@jridgewell/trace-mapping@0.3.30':
|
'@jridgewell/trace-mapping@0.3.30':
|
||||||
resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==}
|
resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==}
|
||||||
|
|
||||||
|
'@kurkle/color@0.3.4':
|
||||||
|
resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==}
|
||||||
|
|
||||||
'@mongodb-js/saslprep@1.3.0':
|
'@mongodb-js/saslprep@1.3.0':
|
||||||
resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==}
|
resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==}
|
||||||
|
|
||||||
@@ -625,6 +631,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
|
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
|
||||||
engines: {node: '>=16.20.1'}
|
engines: {node: '>=16.20.1'}
|
||||||
|
|
||||||
|
chart.js@4.5.0:
|
||||||
|
resolution: {integrity: sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==}
|
||||||
|
engines: {pnpm: '>=8'}
|
||||||
|
|
||||||
cheerio-select@2.1.0:
|
cheerio-select@2.1.0:
|
||||||
resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
|
resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
|
||||||
|
|
||||||
@@ -1251,6 +1261,8 @@ snapshots:
|
|||||||
'@jridgewell/resolve-uri': 3.1.0
|
'@jridgewell/resolve-uri': 3.1.0
|
||||||
'@jridgewell/sourcemap-codec': 1.4.15
|
'@jridgewell/sourcemap-codec': 1.4.15
|
||||||
|
|
||||||
|
'@kurkle/color@0.3.4': {}
|
||||||
|
|
||||||
'@mongodb-js/saslprep@1.3.0':
|
'@mongodb-js/saslprep@1.3.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
sparse-bitfield: 3.0.3
|
sparse-bitfield: 3.0.3
|
||||||
@@ -1455,6 +1467,10 @@ snapshots:
|
|||||||
|
|
||||||
bson@6.10.4: {}
|
bson@6.10.4: {}
|
||||||
|
|
||||||
|
chart.js@4.5.0:
|
||||||
|
dependencies:
|
||||||
|
'@kurkle/color': 0.3.4
|
||||||
|
|
||||||
cheerio-select@2.1.0:
|
cheerio-select@2.1.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
boolbase: 1.0.0
|
boolbase: 1.0.0
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
import type { Handle } from "@sveltejs/kit"
|
import type { Handle, HandleServerError } from "@sveltejs/kit"
|
||||||
import { redirect } from "@sveltejs/kit"
|
import { redirect } from "@sveltejs/kit"
|
||||||
import { error } from "@sveltejs/kit"
|
import { error } from "@sveltejs/kit"
|
||||||
import { SvelteKitAuth } from "@auth/sveltekit"
|
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 { sequence } from "@sveltejs/kit/hooks"
|
||||||
import * as auth from "./auth"
|
import * as auth from "./auth"
|
||||||
import { initializeScheduler } from "./lib/server/scheduler"
|
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();
|
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 }) {
|
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();
|
const session = await event.locals.auth();
|
||||||
|
|
||||||
|
// Protect rezepte routes
|
||||||
|
if (event.url.pathname.startsWith('/rezepte/edit') || event.url.pathname.startsWith('/rezepte/add')) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
// Preserve the original URL the user was trying to access
|
// Preserve the original URL the user was trying to access
|
||||||
const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search);
|
const callbackUrl = encodeURIComponent(event.url.pathname + event.url.search);
|
||||||
redirect(303, `/login?callbackUrl=${callbackUrl}`);
|
redirect(303, `/login?callbackUrl=${callbackUrl}`);
|
||||||
}
|
}
|
||||||
else if (!session.user.groups.includes('rezepte_users')) {
|
else if (!session.user.groups.includes('rezepte_users')) {
|
||||||
// strip last dir from url
|
error(403, {
|
||||||
// TODO: give indication of why access failed
|
message: 'Zugriff verweigert',
|
||||||
const new_url = event.url.pathname.split('/').slice(0, -1).join('/');
|
details: 'Du hast keine Berechtigung für diesen Bereich. Falls du glaubst, dass dies ein Fehler ist, wende dich bitte an Alexander.'
|
||||||
redirect(303, new_url);
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
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(
|
export const handle: Handle = sequence(
|
||||||
auth.handle,
|
auth.handle,
|
||||||
authorization
|
authorization
|
||||||
|
275
src/lib/components/BarChart.svelte
Normal file
275
src/lib/components/BarChart.svelte
Normal file
@@ -0,0 +1,275 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { Chart, registerables } from 'chart.js';
|
||||||
|
|
||||||
|
export let data = { labels: [], datasets: [] };
|
||||||
|
export let title = '';
|
||||||
|
export let height = '400px';
|
||||||
|
|
||||||
|
let canvas;
|
||||||
|
let chart;
|
||||||
|
|
||||||
|
// Register Chart.js components
|
||||||
|
Chart.register(...registerables);
|
||||||
|
|
||||||
|
// Nord theme colors for categories
|
||||||
|
const nordColors = [
|
||||||
|
'#5E81AC', // Nord Blue
|
||||||
|
'#88C0D0', // Nord Light Blue
|
||||||
|
'#81A1C1', // Nord Lighter Blue
|
||||||
|
'#A3BE8C', // Nord Green
|
||||||
|
'#EBCB8B', // Nord Yellow
|
||||||
|
'#D08770', // Nord Orange
|
||||||
|
'#BF616A', // Nord Red
|
||||||
|
'#B48EAD', // Nord Purple
|
||||||
|
'#8FBCBB', // Nord Cyan
|
||||||
|
'#ECEFF4', // Nord Light Gray
|
||||||
|
];
|
||||||
|
|
||||||
|
function getCategoryColor(category, index) {
|
||||||
|
const categoryColorMap = {
|
||||||
|
'groceries': '#A3BE8C', // Green
|
||||||
|
'restaurant': '#D08770', // Orange
|
||||||
|
'transport': '#5E81AC', // Blue
|
||||||
|
'entertainment': '#B48EAD', // Purple
|
||||||
|
'shopping': '#EBCB8B', // Yellow
|
||||||
|
'utilities': '#81A1C1', // Light Blue
|
||||||
|
'healthcare': '#BF616A', // Red
|
||||||
|
'education': '#88C0D0', // Cyan
|
||||||
|
'travel': '#8FBCBB', // Light Cyan
|
||||||
|
'other': '#4C566A' // Dark Gray
|
||||||
|
};
|
||||||
|
|
||||||
|
return categoryColorMap[category] || nordColors[index % nordColors.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
function createChart() {
|
||||||
|
if (!canvas || !data.datasets) return;
|
||||||
|
|
||||||
|
// Destroy existing chart
|
||||||
|
if (chart) {
|
||||||
|
chart.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}));
|
||||||
|
|
||||||
|
chart = new Chart(ctx, {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: data.labels,
|
||||||
|
datasets: processedDatasets
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
layout: {
|
||||||
|
padding: {
|
||||||
|
top: 40
|
||||||
|
}
|
||||||
|
},
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
stacked: true,
|
||||||
|
grid: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
border: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
ticks: {
|
||||||
|
color: '#ffffff',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif',
|
||||||
|
size: 14,
|
||||||
|
weight: 'bold'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
stacked: true,
|
||||||
|
beginAtZero: true,
|
||||||
|
grid: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
border: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
ticks: {
|
||||||
|
color: 'transparent',
|
||||||
|
font: {
|
||||||
|
size: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
datalabels: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
position: 'bottom',
|
||||||
|
labels: {
|
||||||
|
padding: 20,
|
||||||
|
usePointStyle: true,
|
||||||
|
color: '#ffffff',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif',
|
||||||
|
size: 14,
|
||||||
|
weight: 'bold'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
display: !!title,
|
||||||
|
text: title,
|
||||||
|
color: '#ffffff',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif',
|
||||||
|
size: 18,
|
||||||
|
weight: 'bold'
|
||||||
|
},
|
||||||
|
padding: 20
|
||||||
|
},
|
||||||
|
tooltip: {
|
||||||
|
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',
|
||||||
|
size: 13,
|
||||||
|
weight: 'bold'
|
||||||
|
},
|
||||||
|
bodyFont: {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
interaction: {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
createChart();
|
||||||
|
|
||||||
|
// Watch for theme changes
|
||||||
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
const handleThemeChange = () => {
|
||||||
|
setTimeout(createChart, 100); // Small delay to let CSS variables update
|
||||||
|
};
|
||||||
|
|
||||||
|
mediaQuery.addEventListener('change', handleThemeChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
mediaQuery.removeEventListener('change', handleThemeChange);
|
||||||
|
if (chart) {
|
||||||
|
chart.destroy();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Recreate chart when data changes
|
||||||
|
$: if (canvas && data) {
|
||||||
|
createChart();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="chart-container" style="height: {height}">
|
||||||
|
<canvas bind:this={canvas}></canvas>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.chart-container {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
padding: 1.5rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.chart-container {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas {
|
||||||
|
max-width: 100%;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
</style>
|
38
src/lib/components/FormSection.svelte
Normal file
38
src/lib/components/FormSection.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script>
|
||||||
|
export let title = '';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
{#if title}
|
||||||
|
<h2>{title}</h2>
|
||||||
|
{/if}
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
247
src/lib/components/ImageUpload.svelte
Normal file
247
src/lib/components/ImageUpload.svelte
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
<script>
|
||||||
|
export let imagePreview = '';
|
||||||
|
export let imageFile = null;
|
||||||
|
export let uploading = false;
|
||||||
|
export let currentImage = null; // For edit mode
|
||||||
|
export let title = 'Receipt Image';
|
||||||
|
|
||||||
|
// Events
|
||||||
|
import { createEventDispatcher } from 'svelte';
|
||||||
|
const dispatch = createEventDispatcher();
|
||||||
|
|
||||||
|
function handleImageChange(event) {
|
||||||
|
const file = event.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
|
dispatch('error', 'File size must be less than 5MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
dispatch('error', 'Please select a valid image file (JPEG, PNG, WebP)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
imageFile = file;
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (e) => {
|
||||||
|
imagePreview = e.target.result;
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
|
||||||
|
dispatch('imageSelected', file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeImage() {
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
currentImage = null;
|
||||||
|
dispatch('imageRemoved');
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeCurrentImage() {
|
||||||
|
currentImage = null;
|
||||||
|
dispatch('currentImageRemoved');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>{title}</h2>
|
||||||
|
|
||||||
|
{#if currentImage}
|
||||||
|
<div class="current-image">
|
||||||
|
<img src={currentImage} alt="Receipt" class="receipt-preview" />
|
||||||
|
<div class="image-actions">
|
||||||
|
<button type="button" class="btn-remove" on:click={removeCurrentImage}>
|
||||||
|
Remove Image
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if imagePreview}
|
||||||
|
<div class="image-preview">
|
||||||
|
<img src={imagePreview} alt="Receipt preview" />
|
||||||
|
<button type="button" class="remove-image" on:click={removeImage}>
|
||||||
|
Remove Image
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="image-upload">
|
||||||
|
<label for="image" class="upload-label">
|
||||||
|
<div class="upload-content">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/>
|
||||||
|
<line x1="16" y1="5" x2="22" y2="5"/>
|
||||||
|
<line x1="19" y1="2" x2="19" y2="8"/>
|
||||||
|
</svg>
|
||||||
|
<p>{currentImage ? 'Replace Image' : 'Upload Receipt Image'}</p>
|
||||||
|
<small>JPEG, PNG, WebP (max 5MB)</small>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
id="image"
|
||||||
|
accept="image/jpeg,image/jpg,image/png,image/webp"
|
||||||
|
on:change={handleImageChange}
|
||||||
|
disabled={uploading}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if uploading}
|
||||||
|
<div class="upload-status">Uploading image...</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload {
|
||||||
|
border: 2px dashed var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload:hover {
|
||||||
|
border-color: var(--blue);
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.image-upload {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-label {
|
||||||
|
cursor: pointer;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content svg {
|
||||||
|
color: var(--nord3);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content p {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content small {
|
||||||
|
color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.upload-content svg {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content p {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content small {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview img {
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 300px;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-image, .btn-remove {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-image:hover, .btn-remove:hover {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.current-image {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-preview {
|
||||||
|
max-width: 200px;
|
||||||
|
max-height: 200px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.receipt-preview {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-status {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
457
src/lib/components/SplitMethodSelector.svelte
Normal file
457
src/lib/components/SplitMethodSelector.svelte
Normal file
@@ -0,0 +1,457 @@
|
|||||||
|
<script>
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
export let splitMethod = 'equal';
|
||||||
|
export let users = [];
|
||||||
|
export let amount = 0;
|
||||||
|
export let paidBy = '';
|
||||||
|
export let splitAmounts = {};
|
||||||
|
export let personalAmounts = {};
|
||||||
|
export let currentUser = '';
|
||||||
|
export let predefinedMode = false;
|
||||||
|
export let currency = 'CHF';
|
||||||
|
|
||||||
|
let personalTotalError = false;
|
||||||
|
|
||||||
|
// Reactive text for "Paid in Full" option
|
||||||
|
$: paidInFullText = (() => {
|
||||||
|
if (!paidBy) {
|
||||||
|
return 'Paid in Full';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special handling for 2-user predefined setup
|
||||||
|
if (predefinedMode && users.length === 2) {
|
||||||
|
const otherUser = users.find(user => user !== paidBy);
|
||||||
|
return otherUser ? `Paid in Full for ${otherUser}` : 'Paid in Full';
|
||||||
|
}
|
||||||
|
|
||||||
|
// General case
|
||||||
|
if (paidBy === currentUser) {
|
||||||
|
return 'Paid in Full by You';
|
||||||
|
} else {
|
||||||
|
return `Paid in Full by ${paidBy}`;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
function calculateEqualSplits() {
|
||||||
|
if (!amount || users.length === 0) return;
|
||||||
|
|
||||||
|
const amountNum = parseFloat(amount);
|
||||||
|
const splitAmount = amountNum / users.length;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = splitAmount - amountNum;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = splitAmount;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculateFullPayment() {
|
||||||
|
if (!amount) return;
|
||||||
|
|
||||||
|
const amountNum = parseFloat(amount);
|
||||||
|
const otherUsers = users.filter(user => user !== paidBy);
|
||||||
|
const amountPerOtherUser = otherUsers.length > 0 ? amountNum / otherUsers.length : 0;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = -amountNum;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = amountPerOtherUser;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculatePersonalEqualSplit() {
|
||||||
|
if (!amount || users.length === 0) return;
|
||||||
|
|
||||||
|
const totalAmount = parseFloat(amount);
|
||||||
|
|
||||||
|
const totalPersonal = users.reduce((sum, user) => {
|
||||||
|
return sum + (parseFloat(personalAmounts[user]) || 0);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
const remainder = Math.max(0, totalAmount - totalPersonal);
|
||||||
|
const equalShare = remainder / users.length;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
const personalAmount = parseFloat(personalAmounts[user]) || 0;
|
||||||
|
const totalOwed = personalAmount + equalShare;
|
||||||
|
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = totalOwed - totalAmount;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = totalOwed;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSplitMethodChange() {
|
||||||
|
if (splitMethod === 'equal') {
|
||||||
|
calculateEqualSplits();
|
||||||
|
} else if (splitMethod === 'full') {
|
||||||
|
calculateFullPayment();
|
||||||
|
} else if (splitMethod === 'personal_equal') {
|
||||||
|
calculatePersonalEqualSplit();
|
||||||
|
} else if (splitMethod === 'proportional') {
|
||||||
|
users.forEach(user => {
|
||||||
|
if (!(user in splitAmounts)) {
|
||||||
|
splitAmounts[user] = 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate and recalculate when personal amounts change
|
||||||
|
$: if (splitMethod === 'personal_equal' && personalAmounts && amount) {
|
||||||
|
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
||||||
|
const totalAmount = parseFloat(amount);
|
||||||
|
personalTotalError = totalPersonal > totalAmount;
|
||||||
|
|
||||||
|
if (!personalTotalError) {
|
||||||
|
calculatePersonalEqualSplit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$: if (amount && splitMethod && paidBy) {
|
||||||
|
handleSplitMethodChange();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>Split Method</h2>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="splitMethod">How should this payment be split?</label>
|
||||||
|
<select id="splitMethod" name="splitMethod" bind:value={splitMethod} required>
|
||||||
|
<option value="equal">{predefinedMode && users.length === 2 ? 'Split 50/50' : 'Equal Split'}</option>
|
||||||
|
<option value="personal_equal">Personal + Equal Split</option>
|
||||||
|
<option value="full">{paidInFullText}</option>
|
||||||
|
<option value="proportional">Custom Proportions</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if splitMethod === 'proportional'}
|
||||||
|
<div class="proportional-splits">
|
||||||
|
<h3>Custom Split Amounts</h3>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-input">
|
||||||
|
<label>{user}</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
name="split_{user}"
|
||||||
|
bind:value={splitAmounts[user]}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if splitMethod === 'personal_equal'}
|
||||||
|
<div class="personal-splits">
|
||||||
|
<h3>Personal Amounts</h3>
|
||||||
|
<p class="description">Enter personal amounts for each user. The remainder will be split equally.</p>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-input">
|
||||||
|
<label>{user}</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
name="personal_{user}"
|
||||||
|
bind:value={personalAmounts[user]}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if amount}
|
||||||
|
<div class="remainder-info" class:error={personalTotalError}>
|
||||||
|
<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}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if Object.keys(splitAmounts).length > 0}
|
||||||
|
<div class="split-preview">
|
||||||
|
<h3>Split Preview</h3>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-item">
|
||||||
|
<div class="split-user">
|
||||||
|
<ProfilePicture username={user} size={24} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
</div>
|
||||||
|
<span class="amount" class:positive={splitAmounts[user] < 0} class:negative={splitAmounts[user] > 0}>
|
||||||
|
{#if splitAmounts[user] > 0}
|
||||||
|
owes {currency} {splitAmounts[user].toFixed(2)}
|
||||||
|
{:else if splitAmounts[user] < 0}
|
||||||
|
is owed {currency} {Math.abs(splitAmounts[user]).toFixed(2)}
|
||||||
|
{:else}
|
||||||
|
owes {currency} {splitAmounts[user].toFixed(2)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
label {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
select {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits, .personal-splits {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits {
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.proportional-splits {
|
||||||
|
border-color: var(--nord3);
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits h3, .personal-splits h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.proportional-splits h3, .personal-splits h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.personal-splits .description {
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.personal-splits .description {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input label {
|
||||||
|
min-width: 100px;
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input input {
|
||||||
|
max-width: 120px;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-input input {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info {
|
||||||
|
margin-top: 1rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info.error {
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.remainder-info {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
border-color: var(--red);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info span {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 600;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-preview {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-preview h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-preview h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
</style>
|
239
src/lib/components/UsersList.svelte
Normal file
239
src/lib/components/UsersList.svelte
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
<script>
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
export let users = [];
|
||||||
|
export let currentUser = '';
|
||||||
|
export let predefinedMode = false;
|
||||||
|
export let canRemoveUsers = true;
|
||||||
|
export let newUser = '';
|
||||||
|
|
||||||
|
function addUser() {
|
||||||
|
if (predefinedMode) return;
|
||||||
|
|
||||||
|
if (newUser.trim() && !users.includes(newUser.trim())) {
|
||||||
|
users = [...users, newUser.trim()];
|
||||||
|
newUser = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeUser(userToRemove) {
|
||||||
|
if (predefinedMode) return;
|
||||||
|
if (!canRemoveUsers) return;
|
||||||
|
|
||||||
|
if (users.length > 1 && userToRemove !== currentUser) {
|
||||||
|
users = users.filter(u => u !== userToRemove);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>Split Between Users</h2>
|
||||||
|
|
||||||
|
{#if predefinedMode}
|
||||||
|
<div class="predefined-users">
|
||||||
|
<p class="predefined-note">Splitting between predefined users:</p>
|
||||||
|
<div class="users-list">
|
||||||
|
{#each users as user}
|
||||||
|
<div class="user-item with-profile">
|
||||||
|
<ProfilePicture username={user} size={32} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
{#if user === currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="users-list">
|
||||||
|
{#each users as user}
|
||||||
|
<div class="user-item with-profile">
|
||||||
|
<ProfilePicture username={user} size={32} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
{#if user === currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
{#if canRemoveUsers && user !== currentUser}
|
||||||
|
<button type="button" class="remove-user" on:click={() => removeUser(user)}>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="add-user js-enhanced" style="display: none;">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={newUser}
|
||||||
|
placeholder="Add user..."
|
||||||
|
on:keydown={(e) => e.key === 'Enter' && (e.preventDefault(), addUser())}
|
||||||
|
/>
|
||||||
|
<button type="button" on:click={addUser}>Add User</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.users-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.user-item {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item.with-profile {
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item .username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.user-item .username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.predefined-users {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.predefined-users {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.predefined-note {
|
||||||
|
margin: 0 0 1rem 0;
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.predefined-note {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-user {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-user:hover {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.add-user input {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user button {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user button:hover {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
</style>
|
@@ -24,6 +24,12 @@ export async function getUserFavorites(fetch: any, locals: any): Promise<string[
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function addFavoriteStatusToRecipes(recipes: any[], userFavorites: string[]): any[] {
|
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 => ({
|
return recipes.map(recipe => ({
|
||||||
...recipe,
|
...recipe,
|
||||||
isFavorite: userFavorites.some(favId => favId.toString() === recipe._id.toString())
|
isFavorite: userFavorites.some(favId => favId.toString() === recipe._id.toString())
|
||||||
|
94
src/lib/utils/currency.ts
Normal file
94
src/lib/utils/currency.ts
Normal 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());
|
||||||
|
}
|
47
src/models/ExchangeRate.ts
Normal file
47
src/models/ExchangeRate.ts
Normal 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);
|
@@ -4,8 +4,10 @@ export interface IPayment {
|
|||||||
_id?: string;
|
_id?: string;
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
amount: number;
|
amount: number; // Always in CHF (converted if necessary)
|
||||||
currency: string;
|
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
|
paidBy: string; // username/nickname of the person who paid
|
||||||
date: Date;
|
date: Date;
|
||||||
image?: string; // path to uploaded image
|
image?: string; // path to uploaded image
|
||||||
@@ -36,7 +38,17 @@ const PaymentSchema = new mongoose.Schema(
|
|||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
default: 'CHF',
|
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: {
|
paidBy: {
|
||||||
type: String,
|
type: String,
|
||||||
|
@@ -4,16 +4,16 @@ export interface IRecurringPayment {
|
|||||||
_id?: string;
|
_id?: string;
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
amount: number;
|
amount: number; // Amount in the original currency
|
||||||
currency: string;
|
currency: string; // Original currency code
|
||||||
paidBy: string; // username/nickname of the person who paid
|
paidBy: string; // username/nickname of the person who paid
|
||||||
category: 'groceries' | 'shopping' | 'travel' | 'restaurant' | 'utilities' | 'fun' | 'settlement';
|
category: 'groceries' | 'shopping' | 'travel' | 'restaurant' | 'utilities' | 'fun' | 'settlement';
|
||||||
splitMethod: 'equal' | 'full' | 'proportional' | 'personal_equal';
|
splitMethod: 'equal' | 'full' | 'proportional' | 'personal_equal';
|
||||||
splits: Array<{
|
splits: Array<{
|
||||||
username: string;
|
username: string;
|
||||||
amount?: number;
|
amount?: number; // Amount in original currency
|
||||||
proportion?: number;
|
proportion?: number;
|
||||||
personalAmount?: number;
|
personalAmount?: number; // Amount in original currency
|
||||||
}>;
|
}>;
|
||||||
frequency: 'daily' | 'weekly' | 'monthly' | 'custom';
|
frequency: 'daily' | 'weekly' | 'monthly' | 'custom';
|
||||||
cronExpression?: string; // For custom frequencies using cron syntax
|
cronExpression?: string; // For custom frequencies using cron syntax
|
||||||
@@ -47,7 +47,7 @@ const RecurringPaymentSchema = new mongoose.Schema(
|
|||||||
type: String,
|
type: String,
|
||||||
required: true,
|
required: true,
|
||||||
default: 'CHF',
|
default: 'CHF',
|
||||||
enum: ['CHF']
|
uppercase: true
|
||||||
},
|
},
|
||||||
paidBy: {
|
paidBy: {
|
||||||
type: String,
|
type: String,
|
||||||
|
393
src/routes/+error.svelte
Normal file
393
src/routes/+error.svelte
Normal 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>
|
73
src/routes/api/bible-quote/+server.ts
Normal file
73
src/routes/api/bible-quote/+server.ts
Normal 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');
|
||||||
|
}
|
||||||
|
};
|
@@ -1,7 +1,7 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||||
import { Payment } from '../../../../models/Payment'; // Need to import Payment for populate to work
|
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';
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ locals, url }) => {
|
export const GET: RequestHandler = async ({ locals, url }) => {
|
||||||
@@ -94,7 +94,5 @@ export const GET: RequestHandler = async ({ locals, url }) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Error calculating balance:', e);
|
console.error('Error calculating balance:', e);
|
||||||
throw error(500, 'Failed to calculate balance');
|
throw error(500, 'Failed to calculate balance');
|
||||||
} finally {
|
|
||||||
await dbDisconnect();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,7 +1,7 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||||
import { Payment } from '../../../../models/Payment';
|
import { Payment } from '../../../../models/Payment';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
interface DebtSummary {
|
interface DebtSummary {
|
||||||
@@ -105,6 +105,6 @@ export const GET: RequestHandler = async ({ locals }) => {
|
|||||||
console.error('Error calculating debt breakdown:', e);
|
console.error('Error calculating debt breakdown:', e);
|
||||||
throw error(500, 'Failed to calculate debt breakdown');
|
throw error(500, 'Failed to calculate debt breakdown');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
115
src/routes/api/cospend/exchange-rates/+server.ts
Normal file
115
src/routes/api/cospend/exchange-rates/+server.ts
Normal 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);
|
||||||
|
}
|
145
src/routes/api/cospend/monthly-expenses/+server.ts
Normal file
145
src/routes/api/cospend/monthly-expenses/+server.ts
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { Payment } from '../../../../models/Payment';
|
||||||
|
import { dbConnect } from '../../../../utils/db';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ url, locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session || !session.user?.nickname) {
|
||||||
|
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
// Get query parameters for date range (default to last 12 months)
|
||||||
|
const monthsBack = parseInt(url.searchParams.get('months') || '12');
|
||||||
|
const endDate = new Date();
|
||||||
|
const startDate = new Date();
|
||||||
|
startDate.setMonth(startDate.getMonth() - monthsBack);
|
||||||
|
|
||||||
|
const totalPayments = await Payment.countDocuments();
|
||||||
|
const paymentsInRange = await Payment.countDocuments({
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const expensePayments = await Payment.countDocuments({
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
},
|
||||||
|
category: { $ne: 'settlement' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Aggregate payments by month and category
|
||||||
|
const pipeline = [
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
},
|
||||||
|
// Exclude settlements - only show actual expenses
|
||||||
|
category: { $ne: 'settlement' },
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$addFields: {
|
||||||
|
// Extract year-month from date
|
||||||
|
yearMonth: {
|
||||||
|
$dateToString: {
|
||||||
|
format: '%Y-%m',
|
||||||
|
date: '$date'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: {
|
||||||
|
yearMonth: '$yearMonth',
|
||||||
|
category: '$category'
|
||||||
|
},
|
||||||
|
totalAmount: { $sum: '$amount' },
|
||||||
|
count: { $sum: 1 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$sort: {
|
||||||
|
'_id.yearMonth': 1,
|
||||||
|
'_id.category': 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const results = await Payment.aggregate(pipeline);
|
||||||
|
console.log('Aggregation results:', results);
|
||||||
|
|
||||||
|
// Transform data into chart-friendly format
|
||||||
|
const monthsMap = new Map();
|
||||||
|
const categories = new Set();
|
||||||
|
|
||||||
|
// Initialize months
|
||||||
|
for (let i = 0; i < monthsBack; i++) {
|
||||||
|
const date = new Date();
|
||||||
|
date.setMonth(date.getMonth() - monthsBack + i + 1);
|
||||||
|
const yearMonth = date.toISOString().substring(0, 7);
|
||||||
|
monthsMap.set(yearMonth, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate data
|
||||||
|
results.forEach((result: any) => {
|
||||||
|
const { yearMonth, category } = result._id;
|
||||||
|
const amount = result.totalAmount;
|
||||||
|
|
||||||
|
categories.add(category);
|
||||||
|
|
||||||
|
if (!monthsMap.has(yearMonth)) {
|
||||||
|
monthsMap.set(yearMonth, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
monthsMap.get(yearMonth)[category] = amount;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Convert to arrays for Chart.js
|
||||||
|
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)
|
||||||
|
}));
|
||||||
|
|
||||||
|
return json({
|
||||||
|
labels: months.map(month => {
|
||||||
|
const [year, monthNum] = month.split('-');
|
||||||
|
const date = new Date(parseInt(year), parseInt(monthNum) - 1);
|
||||||
|
return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
|
||||||
|
}),
|
||||||
|
datasets,
|
||||||
|
categories: categoryList
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching monthly expenses:', error);
|
||||||
|
return json({ error: 'Failed to fetch monthly expenses' }, { status: 500 });
|
||||||
|
}
|
||||||
|
};
|
@@ -1,7 +1,8 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { Payment } from '../../../../models/Payment';
|
import { Payment } from '../../../../models/Payment';
|
||||||
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
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';
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ locals, url }) => {
|
export const GET: RequestHandler = async ({ locals, url }) => {
|
||||||
@@ -27,7 +28,7 @@ export const GET: RequestHandler = async ({ locals, url }) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw error(500, 'Failed to fetch payments');
|
throw error(500, 'Failed to fetch payments');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -38,7 +39,7 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = await request.json();
|
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) {
|
if (!title || !amount || !paidBy || !splitMethod || !splits) {
|
||||||
throw error(400, 'Missing required fields');
|
throw error(400, 'Missing required fields');
|
||||||
@@ -56,6 +57,12 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
throw error(400, 'Invalid category');
|
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
|
// Validate personal + equal split method
|
||||||
if (splitMethod === 'personal_equal' && splits) {
|
if (splitMethod === 'personal_equal' && splits) {
|
||||||
const totalPersonal = splits.reduce((sum: number, split: any) => {
|
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();
|
await dbConnect();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const payment = await Payment.create({
|
const payment = await Payment.create({
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
amount,
|
amount: finalAmount,
|
||||||
currency: 'CHF',
|
currency: inputCurrency,
|
||||||
|
originalAmount,
|
||||||
|
exchangeRate,
|
||||||
paidBy,
|
paidBy,
|
||||||
date: date ? new Date(date) : new Date(),
|
date: paymentDate,
|
||||||
image,
|
image,
|
||||||
category: category || 'groceries',
|
category: category || 'groceries',
|
||||||
splitMethod,
|
splitMethod,
|
||||||
createdBy: auth.user.nickname
|
createdBy: auth.user.nickname
|
||||||
});
|
});
|
||||||
|
|
||||||
const splitPromises = splits.map((split: any) => {
|
// Convert split amounts to CHF if needed
|
||||||
return PaymentSplit.create({
|
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,
|
paymentId: payment._id,
|
||||||
username: split.username,
|
username: split.username,
|
||||||
amount: split.amount,
|
amount: convertedAmount,
|
||||||
proportion: split.proportion,
|
proportion: split.proportion,
|
||||||
personalAmount: split.personalAmount
|
personalAmount: convertedPersonalAmount
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const splitPromises = convertedSplits.map((split) => {
|
||||||
|
return PaymentSplit.create(split);
|
||||||
});
|
});
|
||||||
|
|
||||||
await Promise.all(splitPromises);
|
await Promise.all(splitPromises);
|
||||||
@@ -104,6 +147,6 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
console.error('Error creating payment:', e);
|
console.error('Error creating payment:', e);
|
||||||
throw error(500, 'Failed to create payment');
|
throw error(500, 'Failed to create payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,7 +1,7 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { Payment } from '../../../../../models/Payment';
|
import { Payment } from '../../../../../models/Payment';
|
||||||
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ params, locals }) => {
|
export const GET: RequestHandler = async ({ params, locals }) => {
|
||||||
@@ -26,7 +26,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
|
|||||||
if (e.status === 404) throw e;
|
if (e.status === 404) throw e;
|
||||||
throw error(500, 'Failed to fetch payment');
|
throw error(500, 'Failed to fetch payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -88,7 +88,7 @@ export const PUT: RequestHandler = async ({ params, request, locals }) => {
|
|||||||
if (e.status) throw e;
|
if (e.status) throw e;
|
||||||
throw error(500, 'Failed to update payment');
|
throw error(500, 'Failed to update payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -121,6 +121,6 @@ export const DELETE: RequestHandler = async ({ params, locals }) => {
|
|||||||
if (e.status) throw e;
|
if (e.status) throw e;
|
||||||
throw error(500, 'Failed to delete payment');
|
throw error(500, 'Failed to delete payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,6 +1,6 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { RecurringPayment } from '../../../../models/RecurringPayment';
|
import { RecurringPayment } from '../../../../models/RecurringPayment';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
import { calculateNextExecutionDate, validateCronExpression } from '../../../../lib/utils/recurring';
|
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);
|
console.error('Error fetching recurring payments:', e);
|
||||||
throw error(500, 'Failed to fetch recurring payments');
|
throw error(500, 'Failed to fetch recurring payments');
|
||||||
} finally {
|
} 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);
|
console.error('Error creating recurring payment:', e);
|
||||||
throw error(500, 'Failed to create recurring payment');
|
throw error(500, 'Failed to create recurring payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,6 +1,6 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
import { calculateNextExecutionDate, validateCronExpression } from '../../../../../lib/utils/recurring';
|
import { calculateNextExecutionDate, validateCronExpression } from '../../../../../lib/utils/recurring';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
@@ -30,7 +30,7 @@ export const GET: RequestHandler = async ({ params, locals }) => {
|
|||||||
console.error('Error fetching recurring payment:', e);
|
console.error('Error fetching recurring payment:', e);
|
||||||
throw error(500, 'Failed to fetch recurring payment');
|
throw error(500, 'Failed to fetch recurring payment');
|
||||||
} finally {
|
} 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');
|
throw error(500, 'Failed to update recurring payment');
|
||||||
} finally {
|
} 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);
|
console.error('Error deleting recurring payment:', e);
|
||||||
throw error(500, 'Failed to delete recurring payment');
|
throw error(500, 'Failed to delete recurring payment');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -2,7 +2,7 @@ import type { RequestHandler } from '@sveltejs/kit';
|
|||||||
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
||||||
import { Payment } from '../../../../../models/Payment';
|
import { Payment } from '../../../../../models/Payment';
|
||||||
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
|
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
|
||||||
|
|
||||||
@@ -119,6 +119,6 @@ export const POST: RequestHandler = async ({ request }) => {
|
|||||||
console.error('[Cron] Error executing recurring payments:', e);
|
console.error('[Cron] Error executing recurring payments:', e);
|
||||||
throw error(500, 'Failed to execute recurring payments');
|
throw error(500, 'Failed to execute recurring payments');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -2,9 +2,10 @@ import type { RequestHandler } from '@sveltejs/kit';
|
|||||||
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
import { RecurringPayment } from '../../../../../models/RecurringPayment';
|
||||||
import { Payment } from '../../../../../models/Payment';
|
import { Payment } from '../../../../../models/Payment';
|
||||||
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { error, json } from '@sveltejs/kit';
|
import { error, json } from '@sveltejs/kit';
|
||||||
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
|
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
|
||||||
|
import { convertToCHF } from '../../../../../lib/utils/currency';
|
||||||
|
|
||||||
export const POST: RequestHandler = async ({ locals }) => {
|
export const POST: RequestHandler = async ({ locals }) => {
|
||||||
const auth = await locals.auth();
|
const auth = await locals.auth();
|
||||||
@@ -32,12 +33,35 @@ export const POST: RequestHandler = async ({ locals }) => {
|
|||||||
|
|
||||||
for (const recurringPayment of duePayments) {
|
for (const recurringPayment of duePayments) {
|
||||||
try {
|
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
|
// Create the payment
|
||||||
const payment = await Payment.create({
|
const payment = await Payment.create({
|
||||||
title: recurringPayment.title,
|
title: recurringPayment.title,
|
||||||
description: recurringPayment.description,
|
description: recurringPayment.description,
|
||||||
amount: recurringPayment.amount,
|
amount: finalAmount,
|
||||||
currency: recurringPayment.currency,
|
currency: recurringPayment.currency,
|
||||||
|
originalAmount,
|
||||||
|
exchangeRate,
|
||||||
paidBy: recurringPayment.paidBy,
|
paidBy: recurringPayment.paidBy,
|
||||||
date: now,
|
date: now,
|
||||||
category: recurringPayment.category,
|
category: recurringPayment.category,
|
||||||
@@ -45,15 +69,31 @@ export const POST: RequestHandler = async ({ locals }) => {
|
|||||||
createdBy: recurringPayment.createdBy
|
createdBy: recurringPayment.createdBy
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create payment splits
|
// Convert split amounts to CHF if needed
|
||||||
const splitPromises = recurringPayment.splits.map((split) => {
|
const convertedSplits = recurringPayment.splits.map((split) => {
|
||||||
return PaymentSplit.create({
|
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,
|
paymentId: payment._id,
|
||||||
username: split.username,
|
username: split.username,
|
||||||
amount: split.amount,
|
amount: convertedAmount,
|
||||||
proportion: split.proportion,
|
proportion: split.proportion,
|
||||||
personalAmount: split.personalAmount
|
personalAmount: convertedPersonalAmount
|
||||||
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Create payment splits
|
||||||
|
const splitPromises = convertedSplits.map((split) => {
|
||||||
|
return PaymentSplit.create(split);
|
||||||
});
|
});
|
||||||
|
|
||||||
await Promise.all(splitPromises);
|
await Promise.all(splitPromises);
|
||||||
@@ -99,6 +139,6 @@ export const POST: RequestHandler = async ({ locals }) => {
|
|||||||
console.error('Error executing recurring payments:', e);
|
console.error('Error executing recurring payments:', e);
|
||||||
throw error(500, 'Failed to execute recurring payments');
|
throw error(500, 'Failed to execute recurring payments');
|
||||||
} finally {
|
} finally {
|
||||||
await dbDisconnect();
|
// Connection will be reused
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,6 +1,6 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../models/Recipe';
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
// header: use for bearer token for now
|
// header: use for bearer token for now
|
||||||
// recipe json in body
|
// recipe json in body
|
||||||
@@ -22,7 +22,6 @@ export const POST: RequestHandler = async ({request, cookies, locals}) => {
|
|||||||
} catch(e){
|
} catch(e){
|
||||||
throw error(400, e)
|
throw error(400, e)
|
||||||
}
|
}
|
||||||
await dbDisconnect();
|
|
||||||
return new Response(JSON.stringify({msg: "Added recipe successfully"}),{
|
return new Response(JSON.stringify({msg: "Added recipe successfully"}),{
|
||||||
status: 200,
|
status: 200,
|
||||||
});
|
});
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../models/Recipe';
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import type {RecipeModelType} from '../../../../types/types';
|
import type {RecipeModelType} from '../../../../types/types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
// header: use for bearer token for now
|
// 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
|
const short_name = message.old_short_name
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
await Recipe.findOneAndDelete({short_name: short_name});
|
await Recipe.findOneAndDelete({short_name: short_name});
|
||||||
await dbDisconnect();
|
|
||||||
return new Response(JSON.stringify({msg: "Deleted recipe successfully"}),{
|
return new Response(JSON.stringify({msg: "Deleted recipe successfully"}),{
|
||||||
status: 200,
|
status: 200,
|
||||||
});
|
});
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../models/Recipe';
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import type {RecipeModelType} from '../../../../types/types';
|
import type {RecipeModelType} from '../../../../types/types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
// header: use for bearer token for now
|
// header: use for bearer token for now
|
||||||
@@ -15,7 +15,6 @@ export const POST: RequestHandler = async ({request, locals}) => {
|
|||||||
else{
|
else{
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
await Recipe.findOneAndUpdate({short_name: message.old_short_name }, recipe_json);
|
await Recipe.findOneAndUpdate({short_name: message.old_short_name }, recipe_json);
|
||||||
await dbDisconnect();
|
|
||||||
return new Response(JSON.stringify({msg: "Edited recipe successfully"}),{
|
return new Response(JSON.stringify({msg: "Edited recipe successfully"}),{
|
||||||
status: 200,
|
status: 200,
|
||||||
});
|
});
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { UserFavorites } from '../../../../models/UserFavorites';
|
import { UserFavorites } from '../../../../models/UserFavorites';
|
||||||
import { Recipe } from '../../../../models/Recipe';
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
@@ -19,13 +19,11 @@ export const GET: RequestHandler = async ({ locals }) => {
|
|||||||
username: session.user.nickname
|
username: session.user.nickname
|
||||||
}).lean();
|
}).lean();
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
return json({
|
return json({
|
||||||
favorites: userFavorites?.favorites || []
|
favorites: userFavorites?.favorites || []
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await dbDisconnect();
|
|
||||||
throw error(500, 'Failed to fetch favorites');
|
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
|
// Validate that the recipe exists and get its ObjectId
|
||||||
const recipe = await Recipe.findOne({ short_name: recipeId });
|
const recipe = await Recipe.findOne({ short_name: recipeId });
|
||||||
if (!recipe) {
|
if (!recipe) {
|
||||||
await dbDisconnect();
|
|
||||||
throw error(404, 'Recipe not found');
|
throw error(404, 'Recipe not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,11 +56,9 @@ export const POST: RequestHandler = async ({ request, locals }) => {
|
|||||||
{ upsert: true, new: true }
|
{ upsert: true, new: true }
|
||||||
);
|
);
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
return json({ success: true });
|
return json({ success: true });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await dbDisconnect();
|
|
||||||
if (e instanceof Error && e.message.includes('404')) {
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
@@ -90,7 +85,6 @@ export const DELETE: RequestHandler = async ({ request, locals }) => {
|
|||||||
// Find the recipe's ObjectId
|
// Find the recipe's ObjectId
|
||||||
const recipe = await Recipe.findOne({ short_name: recipeId });
|
const recipe = await Recipe.findOne({ short_name: recipeId });
|
||||||
if (!recipe) {
|
if (!recipe) {
|
||||||
await dbDisconnect();
|
|
||||||
throw error(404, 'Recipe not found');
|
throw error(404, 'Recipe not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,11 +93,9 @@ export const DELETE: RequestHandler = async ({ request, locals }) => {
|
|||||||
{ $pull: { favorites: recipe._id } }
|
{ $pull: { favorites: recipe._id } }
|
||||||
);
|
);
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
return json({ success: true });
|
return json({ success: true });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await dbDisconnect();
|
|
||||||
if (e instanceof Error && e.message.includes('404')) {
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { UserFavorites } from '../../../../../../models/UserFavorites';
|
import { UserFavorites } from '../../../../../../models/UserFavorites';
|
||||||
import { Recipe } from '../../../../../../models/Recipe';
|
import { Recipe } from '../../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
import { dbConnect } from '../../../../../../utils/db';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ locals, params }) => {
|
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
|
// Find the recipe by short_name to get its ObjectId
|
||||||
const recipe = await Recipe.findOne({ short_name: params.shortName });
|
const recipe = await Recipe.findOne({ short_name: params.shortName });
|
||||||
if (!recipe) {
|
if (!recipe) {
|
||||||
await dbDisconnect();
|
|
||||||
throw error(404, 'Recipe not found');
|
throw error(404, 'Recipe not found');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,13 +26,11 @@ export const GET: RequestHandler = async ({ locals, params }) => {
|
|||||||
favorites: recipe._id
|
favorites: recipe._id
|
||||||
}).lean();
|
}).lean();
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
return json({
|
return json({
|
||||||
isFavorite: !!userFavorites
|
isFavorite: !!userFavorites
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await dbDisconnect();
|
|
||||||
if (e instanceof Error && e.message.includes('404')) {
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { UserFavorites } from '../../../../../models/UserFavorites';
|
import { UserFavorites } from '../../../../../models/UserFavorites';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import type { RecipeModelType } from '../../../../../types/types';
|
import type { RecipeModelType } from '../../../../../types/types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
@@ -20,7 +20,6 @@ export const GET: RequestHandler = async ({ locals }) => {
|
|||||||
}).lean();
|
}).lean();
|
||||||
|
|
||||||
if (!userFavorites?.favorites?.length) {
|
if (!userFavorites?.favorites?.length) {
|
||||||
await dbDisconnect();
|
|
||||||
return json([]);
|
return json([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,13 +27,11 @@ export const GET: RequestHandler = async ({ locals }) => {
|
|||||||
_id: { $in: userFavorites.favorites }
|
_id: { $in: userFavorites.favorites }
|
||||||
}).lean() as RecipeModelType[];
|
}).lean() as RecipeModelType[];
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
recipes = JSON.parse(JSON.stringify(recipes));
|
recipes = JSON.parse(JSON.stringify(recipes));
|
||||||
|
|
||||||
return json(recipes);
|
return json(recipes);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await dbDisconnect();
|
|
||||||
throw error(500, 'Failed to fetch favorite recipes');
|
throw error(500, 'Failed to fetch favorite recipes');
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -1,13 +1,12 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import type {RecipeModelType} from '../../../../../types/types';
|
import type {RecipeModelType} from '../../../../../types/types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let recipe = (await Recipe.findOne({ short_name: params.name}).lean()) as RecipeModelType[];
|
let recipe = (await Recipe.findOne({ short_name: params.name}).lean()) as RecipeModelType[];
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
recipe = JSON.parse(JSON.stringify(recipe));
|
recipe = JSON.parse(JSON.stringify(recipe));
|
||||||
if(recipe == null){
|
if(recipe == null){
|
||||||
|
@@ -1,12 +1,11 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import type { BriefRecipeType } from '../../../../../types/types';
|
import type { BriefRecipeType } from '../../../../../types/types';
|
||||||
import { Recipe } from '../../../../../models/Recipe'
|
import { Recipe } from '../../../../../models/Recipe'
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { rand_array } from '$lib/js/randomize';
|
import { rand_array } from '$lib/js/randomize';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let found_brief = rand_array(await Recipe.find({}, 'name short_name tags category icon description season dateModified').lean()) as BriefRecipeType[];
|
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)));
|
return json(JSON.parse(JSON.stringify(found_brief)));
|
||||||
};
|
};
|
||||||
|
@@ -1,12 +1,11 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../types/types';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let categories = (await Recipe.distinct('category').lean());
|
let categories = (await Recipe.distinct('category').lean());
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
categories= JSON.parse(JSON.stringify(categories));
|
categories= JSON.parse(JSON.stringify(categories));
|
||||||
return json(categories);
|
return json(categories);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../../models/Recipe';
|
import { Recipe } from '../../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
import { dbConnect } from '../../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../../types/types';
|
||||||
import { rand_array } from '$lib/js/randomize';
|
import { rand_array } from '$lib/js/randomize';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
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[];
|
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));
|
recipes = JSON.parse(JSON.stringify(recipes));
|
||||||
return json(recipes);
|
return json(recipes);
|
||||||
|
@@ -1,12 +1,11 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../types/types';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let icons = (await Recipe.distinct('icon').lean());
|
let icons = (await Recipe.distinct('icon').lean());
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
icons = JSON.parse(JSON.stringify(icons));
|
icons = JSON.parse(JSON.stringify(icons));
|
||||||
return json(icons);
|
return json(icons);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../../models/Recipe';
|
import { Recipe } from '../../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
import { dbConnect } from '../../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../../types/types';
|
||||||
import { rand_array } from '$lib/js/randomize';
|
import { rand_array } from '$lib/js/randomize';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
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[];
|
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));
|
recipes = JSON.parse(JSON.stringify(recipes));
|
||||||
return json(recipes);
|
return json(recipes);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
import type {rand_array} from '$lib/js/randomize';
|
import type {rand_array} from '$lib/js/randomize';
|
||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../../models/Recipe'
|
import { Recipe } from '../../../../../../models/Recipe'
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
import { dbConnect } from '../../../../../../utils/db';
|
||||||
import { rand_array } from '$lib/js/randomize';
|
import { rand_array } from '$lib/js/randomize';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
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());
|
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));
|
found_in_season = JSON.parse(JSON.stringify(found_in_season));
|
||||||
return json(found_in_season);
|
return json(found_in_season);
|
||||||
};
|
};
|
||||||
|
@@ -1,12 +1,11 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../types/types';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let categories = (await Recipe.distinct('tags').lean());
|
let categories = (await Recipe.distinct('tags').lean());
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
categories= JSON.parse(JSON.stringify(categories));
|
categories= JSON.parse(JSON.stringify(categories));
|
||||||
return json(categories);
|
return json(categories);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../../models/Recipe';
|
import { Recipe } from '../../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
import { dbConnect } from '../../../../../../utils/db';
|
||||||
import type {BriefRecipeType} from '../../../../../../types/types';
|
import type {BriefRecipeType} from '../../../../../../types/types';
|
||||||
import { rand_array } from '$lib/js/randomize';
|
import { rand_array } from '$lib/js/randomize';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
export const GET: RequestHandler = async ({params}) => {
|
||||||
await dbConnect();
|
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[];
|
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));
|
recipes = JSON.parse(JSON.stringify(recipes));
|
||||||
return json(recipes);
|
return json(recipes);
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import { Recipe } from '../../../../../models/Recipe';
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
import { dbConnect } from '../../../../../utils/db';
|
||||||
import { generateRecipeJsonLd } from '$lib/js/recipeJsonLd';
|
import { generateRecipeJsonLd } from '$lib/js/recipeJsonLd';
|
||||||
import type { RecipeModelType } from '../../../../../types/types';
|
import type { RecipeModelType } from '../../../../../types/types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
@@ -8,7 +8,6 @@ import { error } from '@sveltejs/kit';
|
|||||||
export const GET: RequestHandler = async ({ params, setHeaders }) => {
|
export const GET: RequestHandler = async ({ params, setHeaders }) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
let recipe = (await Recipe.findOne({ short_name: params.name }).lean()) as RecipeModelType;
|
let recipe = (await Recipe.findOne({ short_name: params.name }).lean()) as RecipeModelType;
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
recipe = JSON.parse(JSON.stringify(recipe));
|
recipe = JSON.parse(JSON.stringify(recipe));
|
||||||
if (recipe == null) {
|
if (recipe == null) {
|
||||||
|
@@ -1,7 +1,7 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
import type { BriefRecipeType } from '../../../../types/types';
|
import type { BriefRecipeType } from '../../../../types/types';
|
||||||
import { Recipe } from '../../../../models/Recipe';
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
import { dbConnect } from '../../../../utils/db';
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ url, locals }) => {
|
export const GET: RequestHandler = async ({ url, locals }) => {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
@@ -64,11 +64,9 @@ export const GET: RequestHandler = async ({ url, locals }) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
await dbDisconnect();
|
|
||||||
return json(JSON.parse(JSON.stringify(recipes)));
|
return json(JSON.parse(JSON.stringify(recipes)));
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await dbDisconnect();
|
|
||||||
return json({ error: 'Search failed' }, { status: 500 });
|
return json({ error: 'Search failed' }, { status: 500 });
|
||||||
}
|
}
|
||||||
};
|
};
|
@@ -5,6 +5,7 @@
|
|||||||
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
import EnhancedBalance from '$lib/components/EnhancedBalance.svelte';
|
import EnhancedBalance from '$lib/components/EnhancedBalance.svelte';
|
||||||
import DebtBreakdown from '$lib/components/DebtBreakdown.svelte';
|
import DebtBreakdown from '$lib/components/DebtBreakdown.svelte';
|
||||||
|
import BarChart from '$lib/components/BarChart.svelte';
|
||||||
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||||
import { isSettlementPayment, getSettlementIcon, getSettlementClasses, getSettlementReceiver } from '$lib/utils/settlements';
|
import { isSettlementPayment, getSettlementIcon, getSettlementClasses, getSettlementReceiver } from '$lib/utils/settlements';
|
||||||
import AddButton from '$lib/components/AddButton.svelte';
|
import AddButton from '$lib/components/AddButton.svelte';
|
||||||
@@ -18,6 +19,8 @@
|
|||||||
};
|
};
|
||||||
let loading = false; // Start as false since we have server data
|
let loading = false; // Start as false since we have server data
|
||||||
let error = null;
|
let error = null;
|
||||||
|
let monthlyExpensesData = { labels: [], datasets: [] };
|
||||||
|
let expensesLoading = false;
|
||||||
|
|
||||||
// Component references for refreshing
|
// Component references for refreshing
|
||||||
let enhancedBalanceComponent;
|
let enhancedBalanceComponent;
|
||||||
@@ -27,7 +30,10 @@
|
|||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
// Mark that JavaScript is loaded for progressive enhancement
|
// Mark that JavaScript is loaded for progressive enhancement
|
||||||
document.body.classList.add('js-loaded');
|
document.body.classList.add('js-loaded');
|
||||||
await fetchBalance();
|
await Promise.all([
|
||||||
|
fetchBalance(),
|
||||||
|
fetchMonthlyExpenses()
|
||||||
|
]);
|
||||||
|
|
||||||
// Listen for dashboard refresh events from the layout
|
// Listen for dashboard refresh events from the layout
|
||||||
const handleDashboardRefresh = () => {
|
const handleDashboardRefresh = () => {
|
||||||
@@ -57,10 +63,29 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchMonthlyExpenses() {
|
||||||
|
try {
|
||||||
|
expensesLoading = true;
|
||||||
|
const response = await fetch('/api/cospend/monthly-expenses');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch monthly expenses');
|
||||||
|
}
|
||||||
|
monthlyExpensesData = await response.json();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error fetching monthly expenses:', err);
|
||||||
|
// Don't show this error in the main error state
|
||||||
|
} finally {
|
||||||
|
expensesLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Function to refresh all dashboard components after payment deletion
|
// Function to refresh all dashboard components after payment deletion
|
||||||
async function refreshAllComponents() {
|
async function refreshAllComponents() {
|
||||||
// Refresh the main balance and recent activity
|
// Refresh the main balance and recent activity
|
||||||
await fetchBalance();
|
await Promise.all([
|
||||||
|
fetchBalance(),
|
||||||
|
fetchMonthlyExpenses()
|
||||||
|
]);
|
||||||
|
|
||||||
// Refresh the enhanced balance component if it exists and has a refresh method
|
// Refresh the enhanced balance component if it exists and has a refresh method
|
||||||
if (enhancedBalanceComponent && enhancedBalanceComponent.refresh) {
|
if (enhancedBalanceComponent && enhancedBalanceComponent.refresh) {
|
||||||
@@ -128,6 +153,9 @@
|
|||||||
<main class="cospend-main">
|
<main class="cospend-main">
|
||||||
<h1>Cospend</h1>
|
<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} />
|
<EnhancedBalance bind:this={enhancedBalanceComponent} initialBalance={data.balance} initialDebtData={data.debtData} />
|
||||||
|
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
@@ -137,6 +165,27 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DebtBreakdown bind:this={debtBreakdownComponent} />
|
<DebtBreakdown bind:this={debtBreakdownComponent} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Monthly Expenses Chart -->
|
||||||
|
<div class="chart-section">
|
||||||
|
{#if expensesLoading}
|
||||||
|
<div class="loading">Loading monthly expenses chart...</div>
|
||||||
|
{:else if monthlyExpensesData.datasets && monthlyExpensesData.datasets.length > 0}
|
||||||
|
<BarChart
|
||||||
|
data={monthlyExpensesData}
|
||||||
|
title="Monthly Expenses by Category"
|
||||||
|
height="400px"
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="loading">
|
||||||
|
Debug: expensesLoading={expensesLoading},
|
||||||
|
datasets={monthlyExpensesData.datasets?.length || 0},
|
||||||
|
data={JSON.stringify(monthlyExpensesData)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{#if loading}
|
{#if loading}
|
||||||
<div class="loading">Loading recent activity...</div>
|
<div class="loading">Loading recent activity...</div>
|
||||||
@@ -230,7 +279,6 @@
|
|||||||
|
|
||||||
<style>
|
<style>
|
||||||
.cospend-main {
|
.cospend-main {
|
||||||
max-width: 800px;
|
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 2rem;
|
padding: 2rem;
|
||||||
}
|
}
|
||||||
@@ -311,6 +359,9 @@
|
|||||||
border-radius: 0.75rem;
|
border-radius: 0.75rem;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
border: 1px solid var(--nord4);
|
border: 1px solid var(--nord4);
|
||||||
|
max-width: 800px;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.recent-activity h2 {
|
.recent-activity h2 {
|
||||||
@@ -660,4 +711,51 @@
|
|||||||
font-size: 1.3rem;
|
font-size: 1.3rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.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 {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
padding: 2rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
text-align: center;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.chart-section .loading {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
@@ -80,13 +80,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCurrency(amount) {
|
function formatCurrency(amount, currency = 'CHF') {
|
||||||
return new Intl.NumberFormat('de-CH', {
|
return new Intl.NumberFormat('de-CH', {
|
||||||
style: 'currency',
|
style: 'currency',
|
||||||
currency: 'CHF'
|
currency: currency
|
||||||
}).format(amount);
|
}).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) {
|
function formatDate(dateString) {
|
||||||
return new Date(dateString).toLocaleDateString('de-CH');
|
return new Date(dateString).toLocaleDateString('de-CH');
|
||||||
}
|
}
|
||||||
@@ -158,7 +166,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="settlement-amount">
|
<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>
|
<span class="date">{formatDate(payment.date)}</span>
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
@@ -172,7 +180,7 @@
|
|||||||
<div class="payment-meta">
|
<div class="payment-meta">
|
||||||
<span class="category-name">{getCategoryName(payment.category || 'groceries')}</span>
|
<span class="category-name">{getCategoryName(payment.category || 'groceries')}</span>
|
||||||
<span class="date">{formatDate(payment.date)}</span>
|
<span class="date">{formatDate(payment.date)}</span>
|
||||||
<span class="amount">{formatCurrency(payment.amount)}</span>
|
<span class="amount">{formatAmountWithCurrency(payment)}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -219,25 +227,6 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<div class="payment-actions">
|
|
||||||
<span class="created-by">Created by {payment.createdBy}</span>
|
|
||||||
{#if payment.createdBy === data.session.user.nickname}
|
|
||||||
<div class="action-buttons">
|
|
||||||
<button
|
|
||||||
class="btn-edit"
|
|
||||||
on:click={() => goto(`/cospend/payments/edit/${payment._id}`)}
|
|
||||||
>
|
|
||||||
Edit
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
class="btn-delete"
|
|
||||||
on:click={() => deletePayment(payment._id)}
|
|
||||||
>
|
|
||||||
Delete
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</a>
|
</a>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
@@ -678,73 +667,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.payment-actions {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
border-top: 1px solid var(--nord4);
|
|
||||||
padding-top: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.created-by {
|
|
||||||
font-size: 0.9rem;
|
|
||||||
color: var(--nord3);
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
.payment-actions {
|
|
||||||
border-top-color: var(--nord2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.created-by {
|
|
||||||
color: var(--nord4);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.action-buttons {
|
|
||||||
display: flex;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-edit, .btn-delete {
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
border-radius: 0.25rem;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
transition: all 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-edit {
|
|
||||||
background-color: var(--nord5);
|
|
||||||
color: var(--nord0);
|
|
||||||
border: 1px solid var(--nord4);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-edit:hover {
|
|
||||||
background-color: var(--nord4);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-delete {
|
|
||||||
background-color: var(--red);
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-delete:hover {
|
|
||||||
background-color: var(--nord11);
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
.btn-edit {
|
|
||||||
background-color: var(--nord2);
|
|
||||||
color: var(--font-default-dark);
|
|
||||||
border-color: var(--nord3);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-edit:hover {
|
|
||||||
background-color: var(--nord3);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.pagination {
|
.pagination {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -781,10 +703,5 @@
|
|||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
.payment-actions {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: flex-start;
|
|
||||||
gap: 1rem;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
@@ -28,6 +28,7 @@ export const actions: Actions = {
|
|||||||
const title = formData.get('title')?.toString().trim();
|
const title = formData.get('title')?.toString().trim();
|
||||||
const description = formData.get('description')?.toString().trim() || '';
|
const description = formData.get('description')?.toString().trim() || '';
|
||||||
const amount = parseFloat(formData.get('amount')?.toString() || '0');
|
const amount = parseFloat(formData.get('amount')?.toString() || '0');
|
||||||
|
const currency = formData.get('currency')?.toString()?.toUpperCase() || 'CHF';
|
||||||
const paidBy = formData.get('paidBy')?.toString().trim();
|
const paidBy = formData.get('paidBy')?.toString().trim();
|
||||||
const date = formData.get('date')?.toString();
|
const date = formData.get('date')?.toString();
|
||||||
const category = formData.get('category')?.toString() || 'groceries';
|
const category = formData.get('category')?.toString() || 'groceries';
|
||||||
@@ -155,6 +156,7 @@ export const actions: Actions = {
|
|||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
amount,
|
amount,
|
||||||
|
currency,
|
||||||
paidBy,
|
paidBy,
|
||||||
date: date || new Date().toISOString().split('T')[0],
|
date: date || new Date().toISOString().split('T')[0],
|
||||||
category,
|
category,
|
||||||
@@ -186,6 +188,7 @@ export const actions: Actions = {
|
|||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
amount,
|
amount,
|
||||||
|
currency,
|
||||||
paidBy,
|
paidBy,
|
||||||
category,
|
category,
|
||||||
splitMethod,
|
splitMethod,
|
||||||
|
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,8 @@
|
|||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { getCategoryOptions } from '$lib/utils/categories';
|
import { getCategoryOptions } from '$lib/utils/categories';
|
||||||
|
import FormSection from '$lib/components/FormSection.svelte';
|
||||||
|
import ImageUpload from '$lib/components/ImageUpload.svelte';
|
||||||
|
|
||||||
export let data;
|
export let data;
|
||||||
|
|
||||||
@@ -11,11 +13,23 @@
|
|||||||
let uploading = false;
|
let uploading = false;
|
||||||
let error = null;
|
let error = null;
|
||||||
let imageFile = 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();
|
$: categoryOptions = getCategoryOptions();
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
|
jsEnhanced = true;
|
||||||
|
document.body.classList.add('js-loaded');
|
||||||
await loadPayment();
|
await loadPayment();
|
||||||
|
await loadSupportedCurrencies();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function loadPayment() {
|
async function loadPayment() {
|
||||||
@@ -33,6 +47,24 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleImageSelected(event) {
|
||||||
|
imageFile = event.detail;
|
||||||
|
handleImageUpload();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageError(event) {
|
||||||
|
error = event.detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageRemoved() {
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCurrentImageRemoved() {
|
||||||
|
payment.image = null;
|
||||||
|
}
|
||||||
|
|
||||||
async function handleImageUpload() {
|
async function handleImageUpload() {
|
||||||
if (!imageFile) return;
|
if (!imageFile) return;
|
||||||
|
|
||||||
@@ -53,6 +85,7 @@
|
|||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
payment.image = result.imageUrl;
|
payment.image = result.imageUrl;
|
||||||
imageFile = null;
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err.message;
|
error = err.message;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -60,18 +93,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleImageRemove() {
|
|
||||||
payment.image = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleFileChange(event) {
|
|
||||||
const file = event.target.files[0];
|
|
||||||
if (file) {
|
|
||||||
imageFile = file;
|
|
||||||
handleImageUpload();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
if (!payment) return;
|
if (!payment) return;
|
||||||
|
|
||||||
@@ -129,6 +150,71 @@
|
|||||||
deleting = false;
|
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>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
@@ -147,9 +233,7 @@
|
|||||||
<div class="error">Error: {error}</div>
|
<div class="error">Error: {error}</div>
|
||||||
{:else if payment}
|
{:else if payment}
|
||||||
<form on:submit|preventDefault={handleSubmit} class="payment-form">
|
<form on:submit|preventDefault={handleSubmit} class="payment-form">
|
||||||
<div class="form-section">
|
<FormSection title="Payment Details">
|
||||||
<h2>Payment Details</h2>
|
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="title">Title *</label>
|
<label for="title">Title *</label>
|
||||||
<input
|
<input
|
||||||
@@ -180,7 +264,25 @@
|
|||||||
|
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group">
|
<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
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
id="amount"
|
id="amount"
|
||||||
@@ -189,6 +291,39 @@
|
|||||||
min="0"
|
min="0"
|
||||||
step="0.01"
|
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>
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -196,7 +331,7 @@
|
|||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
id="date"
|
id="date"
|
||||||
value={formatDate(payment.date)}
|
value={formatDateForInput(payment.date)}
|
||||||
on:change={(e) => payment.date = new Date(e.target.value).toISOString()}
|
on:change={(e) => payment.date = new Date(e.target.value).toISOString()}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
@@ -212,43 +347,21 @@
|
|||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</FormSection>
|
||||||
|
|
||||||
<div class="form-section">
|
<ImageUpload
|
||||||
<h2>Receipt Image</h2>
|
bind:imagePreview={imagePreview}
|
||||||
|
bind:imageFile={imageFile}
|
||||||
{#if payment.image}
|
bind:uploading={uploading}
|
||||||
<div class="current-image">
|
currentImage={payment.image}
|
||||||
<img src={payment.image} alt="Receipt" class="receipt-preview" />
|
on:imageSelected={handleImageSelected}
|
||||||
<div class="image-actions">
|
on:imageRemoved={handleImageRemoved}
|
||||||
<button type="button" class="btn-remove" on:click={handleImageRemove}>
|
on:currentImageRemoved={handleCurrentImageRemoved}
|
||||||
Remove Image
|
on:error={handleImageError}
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="imageUpload" class="upload-label">
|
|
||||||
{payment.image ? 'Replace Image' : 'Upload Receipt Image'}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="file"
|
|
||||||
id="imageUpload"
|
|
||||||
accept="image/*"
|
|
||||||
on:change={handleFileChange}
|
|
||||||
disabled={uploading}
|
|
||||||
class="file-input"
|
|
||||||
/>
|
/>
|
||||||
{#if uploading}
|
|
||||||
<div class="upload-status">Uploading image...</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if payment.splits && payment.splits.length > 0}
|
{#if payment.splits && payment.splits.length > 0}
|
||||||
<div class="form-section">
|
<FormSection title="Current Splits">
|
||||||
<h2>Current Splits</h2>
|
|
||||||
<div class="splits-display">
|
<div class="splits-display">
|
||||||
{#each payment.splits as split}
|
{#each payment.splits as split}
|
||||||
<div class="split-item">
|
<div class="split-item">
|
||||||
@@ -266,7 +379,7 @@
|
|||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
<p class="note">Note: To modify splits, please delete and recreate the payment.</p>
|
<p class="note">Note: To modify splits, please delete and recreate the payment.</p>
|
||||||
</div>
|
</FormSection>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<div class="form-actions">
|
<div class="form-actions">
|
||||||
@@ -551,100 +664,81 @@
|
|||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
|
|
||||||
.current-image {
|
/* Amount-currency styling */
|
||||||
margin-bottom: 1rem;
|
.amount-currency {
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.receipt-preview {
|
|
||||||
max-width: 200px;
|
|
||||||
max-height: 200px;
|
|
||||||
object-fit: cover;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
border: 1px solid var(--nord4);
|
|
||||||
margin-bottom: 0.75rem;
|
|
||||||
display: block;
|
|
||||||
margin-left: auto;
|
|
||||||
margin-right: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
.receipt-preview {
|
|
||||||
border-color: var(--nord2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.image-actions {
|
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-remove {
|
.amount-currency input {
|
||||||
background-color: var(--red);
|
flex: 2;
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
padding: 0.5rem 1rem;
|
|
||||||
border-radius: 0.25rem;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
transition: all 0.2s;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-remove:hover {
|
.amount-currency select {
|
||||||
background-color: var(--nord11);
|
flex: 1;
|
||||||
transform: translateY(-1px);
|
min-width: 80px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.upload-label {
|
/* Currency conversion preview */
|
||||||
display: block;
|
.conversion-info {
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
font-weight: 500;
|
|
||||||
color: var(--nord2);
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
.upload-label {
|
|
||||||
color: var(--nord5);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-input {
|
|
||||||
width: 100%;
|
|
||||||
padding: 0.75rem;
|
|
||||||
border: 2px dashed var(--nord4);
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
background-color: var(--nord5);
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-input:hover {
|
|
||||||
border-color: var(--blue);
|
|
||||||
background-color: var(--nord4);
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
|
||||||
.file-input {
|
|
||||||
background-color: var(--nord2);
|
|
||||||
border-color: var(--nord3);
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-input:hover {
|
|
||||||
background-color: var(--nord3);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-input:disabled {
|
|
||||||
opacity: 0.6;
|
|
||||||
cursor: not-allowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
.upload-status {
|
|
||||||
margin-top: 0.5rem;
|
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);
|
color: var(--blue);
|
||||||
font-size: 0.9rem;
|
}
|
||||||
text-align: center;
|
|
||||||
|
.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) {
|
@media (max-width: 600px) {
|
||||||
@@ -664,5 +758,14 @@
|
|||||||
.main-actions {
|
.main-actions {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.amount-currency {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-currency input,
|
||||||
|
.amount-currency select {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
@@ -39,13 +39,21 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCurrency(amount) {
|
function formatCurrency(amount, currency = 'CHF') {
|
||||||
return new Intl.NumberFormat('de-CH', {
|
return new Intl.NumberFormat('de-CH', {
|
||||||
style: 'currency',
|
style: 'currency',
|
||||||
currency: 'CHF'
|
currency: currency
|
||||||
}).format(Math.abs(amount));
|
}).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) {
|
function formatDate(dateString) {
|
||||||
return new Date(dateString).toLocaleDateString('de-CH');
|
return new Date(dateString).toLocaleDateString('de-CH');
|
||||||
}
|
}
|
||||||
@@ -111,7 +119,12 @@
|
|||||||
<h1>{payment.title}</h1>
|
<h1>{payment.title}</h1>
|
||||||
</div>
|
</div>
|
||||||
<div class="payment-amount">
|
<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>
|
||||||
</div>
|
</div>
|
||||||
{#if payment.image}
|
{#if payment.image}
|
||||||
@@ -467,6 +480,22 @@
|
|||||||
color: var(--red);
|
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) {
|
@media (max-width: 600px) {
|
||||||
.payment-view {
|
.payment-view {
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
|
@@ -5,6 +5,8 @@
|
|||||||
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
||||||
import { validateCronExpression, getFrequencyDescription, calculateNextExecutionDate } from '$lib/utils/recurring';
|
import { validateCronExpression, getFrequencyDescription, calculateNextExecutionDate } from '$lib/utils/recurring';
|
||||||
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import SplitMethodSelector from '$lib/components/SplitMethodSelector.svelte';
|
||||||
|
import UsersList from '$lib/components/UsersList.svelte';
|
||||||
|
|
||||||
export let data;
|
export let data;
|
||||||
|
|
||||||
@@ -12,6 +14,7 @@
|
|||||||
title: '',
|
title: '',
|
||||||
description: '',
|
description: '',
|
||||||
amount: '',
|
amount: '',
|
||||||
|
currency: 'CHF',
|
||||||
paidBy: data.session?.user?.nickname || '',
|
paidBy: data.session?.user?.nickname || '',
|
||||||
category: 'groceries',
|
category: 'groceries',
|
||||||
splitMethod: 'equal',
|
splitMethod: 'equal',
|
||||||
@@ -30,15 +33,25 @@
|
|||||||
let loading = false;
|
let loading = false;
|
||||||
let loadingPayment = true;
|
let loadingPayment = true;
|
||||||
let error = null;
|
let error = null;
|
||||||
let personalTotalError = false;
|
|
||||||
let predefinedMode = isPredefinedUsersMode();
|
let predefinedMode = isPredefinedUsersMode();
|
||||||
let cronError = false;
|
let cronError = false;
|
||||||
let nextExecutionPreview = '';
|
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();
|
$: categoryOptions = getCategoryOptions();
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
|
jsEnhanced = true;
|
||||||
|
document.body.classList.add('js-loaded');
|
||||||
await loadRecurringPayment();
|
await loadRecurringPayment();
|
||||||
|
await loadSupportedCurrencies();
|
||||||
});
|
});
|
||||||
|
|
||||||
async function loadRecurringPayment() {
|
async function loadRecurringPayment() {
|
||||||
@@ -57,6 +70,7 @@
|
|||||||
title: payment.title,
|
title: payment.title,
|
||||||
description: payment.description || '',
|
description: payment.description || '',
|
||||||
amount: payment.amount.toString(),
|
amount: payment.amount.toString(),
|
||||||
|
currency: payment.currency || 'CHF',
|
||||||
paidBy: payment.paidBy,
|
paidBy: payment.paidBy,
|
||||||
category: payment.category,
|
category: payment.category,
|
||||||
splitMethod: payment.splitMethod,
|
splitMethod: payment.splitMethod,
|
||||||
@@ -86,28 +100,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function addUser() {
|
|
||||||
if (predefinedMode) return;
|
|
||||||
|
|
||||||
if (newUser.trim() && !users.includes(newUser.trim())) {
|
|
||||||
users = [...users, newUser.trim()];
|
|
||||||
addSplitForUser(newUser.trim());
|
|
||||||
newUser = '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeUser(userToRemove) {
|
|
||||||
if (predefinedMode) return;
|
|
||||||
|
|
||||||
if (users.length > 1) {
|
|
||||||
users = users.filter(u => u !== userToRemove);
|
|
||||||
delete splitAmounts[userToRemove];
|
|
||||||
delete personalAmounts[userToRemove];
|
|
||||||
splitAmounts = { ...splitAmounts };
|
|
||||||
personalAmounts = { ...personalAmounts };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addSplitForUser(username) {
|
function addSplitForUser(username) {
|
||||||
if (!splitAmounts[username]) {
|
if (!splitAmounts[username]) {
|
||||||
splitAmounts[username] = 0;
|
splitAmounts[username] = 0;
|
||||||
@@ -115,74 +107,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculateEqualSplits() {
|
|
||||||
if (!formData.amount || users.length === 0) return;
|
|
||||||
|
|
||||||
const amountNum = parseFloat(formData.amount);
|
|
||||||
const splitAmount = amountNum / users.length;
|
|
||||||
|
|
||||||
users.forEach(user => {
|
|
||||||
if (user === formData.paidBy) {
|
|
||||||
splitAmounts[user] = splitAmount - amountNum;
|
|
||||||
} else {
|
|
||||||
splitAmounts[user] = splitAmount;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
splitAmounts = { ...splitAmounts };
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculateFullPayment() {
|
|
||||||
if (!formData.amount) return;
|
|
||||||
|
|
||||||
const amountNum = parseFloat(formData.amount);
|
|
||||||
const otherUsers = users.filter(user => user !== formData.paidBy);
|
|
||||||
const amountPerOtherUser = otherUsers.length > 0 ? amountNum / otherUsers.length : 0;
|
|
||||||
|
|
||||||
users.forEach(user => {
|
|
||||||
if (user === formData.paidBy) {
|
|
||||||
splitAmounts[user] = -amountNum; // They paid it all, so they're owed the full amount
|
|
||||||
} else {
|
|
||||||
splitAmounts[user] = amountPerOtherUser; // Others owe their share of the full amount
|
|
||||||
}
|
|
||||||
});
|
|
||||||
splitAmounts = { ...splitAmounts };
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculatePersonalEqualSplit() {
|
|
||||||
if (!formData.amount || users.length === 0) return;
|
|
||||||
|
|
||||||
const totalAmount = parseFloat(formData.amount);
|
|
||||||
|
|
||||||
const totalPersonal = users.reduce((sum, user) => {
|
|
||||||
return sum + (parseFloat(personalAmounts[user]) || 0);
|
|
||||||
}, 0);
|
|
||||||
|
|
||||||
const remainder = Math.max(0, totalAmount - totalPersonal);
|
|
||||||
const equalShare = remainder / users.length;
|
|
||||||
|
|
||||||
users.forEach(user => {
|
|
||||||
const personalAmount = parseFloat(personalAmounts[user]) || 0;
|
|
||||||
const totalOwed = personalAmount + equalShare;
|
|
||||||
|
|
||||||
if (user === formData.paidBy) {
|
|
||||||
splitAmounts[user] = totalOwed - totalAmount;
|
|
||||||
} else {
|
|
||||||
splitAmounts[user] = totalOwed;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
splitAmounts = { ...splitAmounts };
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleSplitMethodChange() {
|
|
||||||
if (formData.splitMethod === 'equal') {
|
|
||||||
calculateEqualSplits();
|
|
||||||
} else if (formData.splitMethod === 'full') {
|
|
||||||
calculateFullPayment();
|
|
||||||
} else if (formData.splitMethod === 'personal_equal') {
|
|
||||||
calculatePersonalEqualSplit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function validateCron() {
|
function validateCron() {
|
||||||
if (formData.frequency !== 'custom') {
|
if (formData.frequency !== 'custom') {
|
||||||
cronError = false;
|
cronError = false;
|
||||||
@@ -224,15 +148,6 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (formData.splitMethod === 'personal_equal') {
|
|
||||||
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
|
||||||
const totalAmount = parseFloat(formData.amount);
|
|
||||||
|
|
||||||
if (totalPersonal > totalAmount) {
|
|
||||||
error = 'Personal amounts cannot exceed the total payment amount';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (users.length === 0) {
|
if (users.length === 0) {
|
||||||
error = 'Please add at least one user to split with';
|
error = 'Please add at least one user to split with';
|
||||||
@@ -282,19 +197,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$: if (formData.amount && formData.splitMethod && formData.paidBy && !loadingPayment) {
|
|
||||||
handleSplitMethodChange();
|
|
||||||
}
|
|
||||||
|
|
||||||
$: if (formData.splitMethod === 'personal_equal' && personalAmounts && formData.amount && !loadingPayment) {
|
|
||||||
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
|
||||||
const totalAmount = parseFloat(formData.amount);
|
|
||||||
personalTotalError = totalPersonal > totalAmount;
|
|
||||||
|
|
||||||
if (!personalTotalError) {
|
|
||||||
calculatePersonalEqualSplit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$: if (formData.cronExpression) {
|
$: if (formData.cronExpression) {
|
||||||
validateCron();
|
validateCron();
|
||||||
@@ -303,6 +205,65 @@
|
|||||||
$: if (formData.frequency || formData.cronExpression || formData.startDate) {
|
$: if (formData.frequency || formData.cronExpression || formData.startDate) {
|
||||||
updateNextExecutionPreview();
|
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>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
@@ -358,7 +319,8 @@
|
|||||||
|
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<label for="amount">Amount (CHF) *</label>
|
<label for="amount">Amount *</label>
|
||||||
|
<div class="amount-currency">
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
id="amount"
|
id="amount"
|
||||||
@@ -368,6 +330,35 @@
|
|||||||
step="0.01"
|
step="0.01"
|
||||||
placeholder="0.00"
|
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>
|
||||||
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
@@ -460,129 +451,25 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-section">
|
<UsersList
|
||||||
<h2>Split Between Users</h2>
|
bind:users={users}
|
||||||
|
bind:newUser={newUser}
|
||||||
<div class="users-list">
|
currentUser={data.session?.user?.nickname}
|
||||||
{#each users as user}
|
{predefinedMode}
|
||||||
<div class="user-item with-profile">
|
canRemoveUsers={!predefinedMode}
|
||||||
<ProfilePicture username={user} size={32} />
|
|
||||||
<span class="username">{user}</span>
|
|
||||||
{#if user === data.session?.user?.nickname}
|
|
||||||
<span class="you-badge">You</span>
|
|
||||||
{/if}
|
|
||||||
{#if !predefinedMode && user !== data.session?.user?.nickname}
|
|
||||||
<button type="button" class="remove-user" on:click={() => removeUser(user)}>
|
|
||||||
Remove
|
|
||||||
</button>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if !predefinedMode}
|
|
||||||
<div class="add-user">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
bind:value={newUser}
|
|
||||||
placeholder="Add user..."
|
|
||||||
on:keydown={(e) => e.key === 'Enter' && (e.preventDefault(), addUser())}
|
|
||||||
/>
|
/>
|
||||||
<button type="button" on:click={addUser}>Add User</button>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-section">
|
<SplitMethodSelector
|
||||||
<h2>Split Method</h2>
|
bind:splitMethod={formData.splitMethod}
|
||||||
|
bind:splitAmounts={splitAmounts}
|
||||||
<div class="split-method">
|
bind:personalAmounts={personalAmounts}
|
||||||
<label>
|
{users}
|
||||||
<input type="radio" bind:group={formData.splitMethod} value="equal" />
|
amount={formData.amount}
|
||||||
Equal Split
|
currency={formData.currency}
|
||||||
</label>
|
paidBy={formData.paidBy}
|
||||||
<label>
|
currentUser={data.session?.user?.nickname}
|
||||||
<input type="radio" bind:group={formData.splitMethod} value="personal_equal" />
|
{predefinedMode}
|
||||||
Personal + Equal Split
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" bind:group={formData.splitMethod} value="full" />
|
|
||||||
Paid in Full by {formData.paidBy}
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<input type="radio" bind:group={formData.splitMethod} value="proportional" />
|
|
||||||
Custom Proportions
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if formData.splitMethod === 'proportional'}
|
|
||||||
<div class="proportional-splits">
|
|
||||||
<h3>Custom Split Amounts</h3>
|
|
||||||
{#each users as user}
|
|
||||||
<div class="split-input">
|
|
||||||
<label>{user}</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
step="0.01"
|
|
||||||
bind:value={splitAmounts[user]}
|
|
||||||
placeholder="0.00"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if formData.splitMethod === 'personal_equal'}
|
|
||||||
<div class="personal-splits">
|
|
||||||
<h3>Personal Amounts</h3>
|
|
||||||
<p class="description">Enter personal amounts for each user. The remainder will be split equally.</p>
|
|
||||||
{#each users as user}
|
|
||||||
<div class="split-input">
|
|
||||||
<label>{user}</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
step="0.01"
|
|
||||||
min="0"
|
|
||||||
bind:value={personalAmounts[user]}
|
|
||||||
placeholder="0.00"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
{#if formData.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(formData.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}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
{#if Object.keys(splitAmounts).length > 0}
|
|
||||||
<div class="split-preview">
|
|
||||||
<h3>Split Preview</h3>
|
|
||||||
{#each users as user}
|
|
||||||
<div class="split-item">
|
|
||||||
<div class="split-user">
|
|
||||||
<ProfilePicture username={user} size={24} />
|
|
||||||
<span class="username">{user}</span>
|
|
||||||
</div>
|
|
||||||
<span class="amount" class:positive={splitAmounts[user] < 0} class:negative={splitAmounts[user] > 0}>
|
|
||||||
{#if splitAmounts[user] > 0}
|
|
||||||
owes CHF {splitAmounts[user].toFixed(2)}
|
|
||||||
{:else if splitAmounts[user] < 0}
|
|
||||||
is owed CHF {Math.abs(splitAmounts[user]).toFixed(2)}
|
|
||||||
{:else}
|
|
||||||
owes CHF {splitAmounts[user].toFixed(2)}
|
|
||||||
{/if}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{#if error}
|
{#if error}
|
||||||
<div class="error">{error}</div>
|
<div class="error">{error}</div>
|
||||||
@@ -616,11 +503,11 @@
|
|||||||
|
|
||||||
.header h1 {
|
.header h1 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
.back-link {
|
.back-link {
|
||||||
color: #1976d2;
|
color: var(--blue);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -637,16 +524,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.form-section {
|
.form-section {
|
||||||
background: white;
|
background: var(--nord6);
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
border-radius: 0.75rem;
|
border-radius: 0.75rem;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-section h2 {
|
.form-section h2 {
|
||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
font-size: 1.25rem;
|
font-size: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -664,39 +552,42 @@
|
|||||||
display: block;
|
display: block;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: #555;
|
color: var(--nord3);
|
||||||
}
|
}
|
||||||
|
|
||||||
input, textarea, select {
|
input, textarea, select {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
padding: 0.75rem;
|
padding: 0.75rem;
|
||||||
border: 1px solid #ddd;
|
border: 1px solid var(--nord4);
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
background: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
input:focus, textarea:focus, select:focus {
|
input:focus, textarea:focus, select:focus {
|
||||||
outline: none;
|
outline: none;
|
||||||
border-color: #1976d2;
|
border-color: var(--blue);
|
||||||
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
|
box-shadow: 0 0 0 2px rgba(136, 192, 208, 0.2);
|
||||||
}
|
}
|
||||||
|
|
||||||
input.error {
|
input.error {
|
||||||
border-color: #d32f2f;
|
border-color: var(--red);
|
||||||
}
|
}
|
||||||
|
|
||||||
.help-text {
|
.help-text {
|
||||||
margin-top: 0.5rem;
|
margin-top: 0.5rem;
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.help-text code {
|
.help-text code {
|
||||||
background-color: #f5f5f5;
|
background-color: var(--nord5);
|
||||||
padding: 0.125rem 0.25rem;
|
padding: 0.125rem 0.25rem;
|
||||||
border-radius: 0.25rem;
|
border-radius: 0.25rem;
|
||||||
font-family: monospace;
|
font-family: monospace;
|
||||||
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
.help-text ul {
|
.help-text ul {
|
||||||
@@ -709,14 +600,14 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.field-error {
|
.field-error {
|
||||||
color: #d32f2f;
|
color: var(--red);
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.execution-preview {
|
.execution-preview {
|
||||||
background-color: #e3f2fd;
|
background-color: var(--nord8);
|
||||||
border: 1px solid #2196f3;
|
border: 1px solid var(--blue);
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
margin-top: 1rem;
|
margin-top: 1rem;
|
||||||
@@ -724,200 +615,34 @@
|
|||||||
|
|
||||||
.execution-preview h3 {
|
.execution-preview h3 {
|
||||||
margin: 0 0 0.5rem 0;
|
margin: 0 0 0.5rem 0;
|
||||||
color: #1976d2;
|
color: var(--blue);
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.next-execution {
|
.next-execution {
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #1976d2;
|
color: var(--blue);
|
||||||
margin: 0.5rem 0;
|
margin: 0.5rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.frequency-description {
|
.frequency-description {
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.users-list {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 0.5rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-item {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
background-color: #f5f5f5;
|
|
||||||
padding: 0.5rem 0.75rem;
|
|
||||||
border-radius: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-item.with-profile {
|
|
||||||
gap: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.user-item .username {
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.you-badge {
|
|
||||||
background-color: #1976d2;
|
|
||||||
color: white;
|
|
||||||
padding: 0.125rem 0.5rem;
|
|
||||||
border-radius: 1rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.remove-user {
|
|
||||||
background-color: #d32f2f;
|
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
padding: 0.25rem 0.5rem;
|
|
||||||
border-radius: 0.25rem;
|
|
||||||
font-size: 0.75rem;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.add-user {
|
|
||||||
display: flex;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.add-user input {
|
|
||||||
flex: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.add-user button {
|
|
||||||
background-color: #1976d2;
|
|
||||||
color: white;
|
|
||||||
border: none;
|
|
||||||
padding: 0.75rem 1rem;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-method {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.75rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-method label {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.proportional-splits, .personal-splits {
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
padding: 1rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.proportional-splits h3, .personal-splits h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.personal-splits .description {
|
|
||||||
color: #666;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
font-style: italic;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-input {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 1rem;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-input label {
|
|
||||||
min-width: 100px;
|
|
||||||
margin-bottom: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-input input {
|
|
||||||
max-width: 120px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.remainder-info {
|
|
||||||
margin-top: 1rem;
|
|
||||||
padding: 1rem;
|
|
||||||
background-color: #f8f9fa;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
border: 1px solid #e9ecef;
|
|
||||||
}
|
|
||||||
|
|
||||||
.remainder-info.error {
|
|
||||||
background-color: #fff5f5;
|
|
||||||
border-color: #fed7d7;
|
|
||||||
}
|
|
||||||
|
|
||||||
.remainder-info span {
|
|
||||||
display: block;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error-message {
|
|
||||||
color: #d32f2f;
|
|
||||||
font-weight: 600;
|
|
||||||
margin-top: 0.5rem;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-preview {
|
|
||||||
background-color: #f8f9fa;
|
|
||||||
padding: 1rem;
|
|
||||||
border-radius: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-preview h3 {
|
|
||||||
margin-top: 0;
|
|
||||||
margin-bottom: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-item {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.split-user {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.amount.positive {
|
|
||||||
color: #2e7d32;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.amount.negative {
|
|
||||||
color: #d32f2f;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error {
|
.error {
|
||||||
background-color: #ffebee;
|
background-color: var(--nord6);
|
||||||
color: #d32f2f;
|
color: var(--red);
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-actions {
|
.form-actions {
|
||||||
@@ -935,13 +660,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary {
|
.btn-primary {
|
||||||
background-color: #1976d2;
|
background-color: var(--blue);
|
||||||
color: white;
|
color: white;
|
||||||
border: none;
|
border: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary:hover:not(:disabled) {
|
.btn-primary:hover:not(:disabled) {
|
||||||
background-color: #1565c0;
|
background-color: var(--lightblue);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary:disabled {
|
.btn-primary:disabled {
|
||||||
@@ -950,13 +675,134 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.btn-secondary {
|
.btn-secondary {
|
||||||
background-color: #f5f5f5;
|
background-color: var(--nord5);
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
border: 1px solid #ddd;
|
border: 1px solid var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-secondary:hover {
|
.btn-secondary:hover {
|
||||||
background-color: #e8e8e8;
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
input, textarea, select {
|
||||||
|
background: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus, select:focus {
|
||||||
|
box-shadow: 0 0 0 2px rgba(136, 192, 208, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text code {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.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) {
|
@media (max-width: 600px) {
|
||||||
@@ -971,5 +817,14 @@
|
|||||||
.form-actions {
|
.form-actions {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.amount-currency {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-currency input,
|
||||||
|
.amount-currency select {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
@@ -1,13 +1,133 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
import { redirect } from '@sveltejs/kit';
|
import type { PageServerLoad, Actions } from './$types';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ locals }) => {
|
export const load: PageServerLoad = async ({ fetch, locals, request }) => {
|
||||||
const auth = await locals.auth();
|
const session = await locals.auth();
|
||||||
if (!auth || !auth.user) {
|
|
||||||
|
if (!session) {
|
||||||
throw redirect(302, '/login');
|
throw redirect(302, '/login');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch debt data server-side with authentication cookies
|
||||||
|
const response = await fetch('/api/cospend/debts', {
|
||||||
|
headers: {
|
||||||
|
'Cookie': request.headers.get('Cookie') || ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch debt data');
|
||||||
|
}
|
||||||
|
|
||||||
|
const debtData = await response.json();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
session: auth
|
debtData,
|
||||||
|
session,
|
||||||
|
currentUser: session.user?.nickname || ''
|
||||||
};
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading debt data:', error);
|
||||||
|
return {
|
||||||
|
debtData: {
|
||||||
|
whoOwesMe: [],
|
||||||
|
whoIOwe: [],
|
||||||
|
totalOwedToMe: 0,
|
||||||
|
totalIOwe: 0
|
||||||
|
},
|
||||||
|
error: error.message,
|
||||||
|
session,
|
||||||
|
currentUser: session.user?.nickname || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const actions: Actions = {
|
||||||
|
settle: async ({ request, fetch, locals }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
|
||||||
|
const settlementType = data.get('settlementType');
|
||||||
|
const fromUser = data.get('fromUser');
|
||||||
|
const toUser = data.get('toUser');
|
||||||
|
const amount = parseFloat(data.get('amount'));
|
||||||
|
|
||||||
|
// Validation
|
||||||
|
if (!settlementType || !fromUser || !toUser || !amount) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'All fields are required',
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Please enter a valid positive amount',
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create a settlement payment
|
||||||
|
const payload = {
|
||||||
|
title: 'Settlement Payment',
|
||||||
|
description: `Settlement: ${fromUser} pays ${toUser}`,
|
||||||
|
amount: amount,
|
||||||
|
paidBy: fromUser,
|
||||||
|
date: new Date().toISOString().split('T')[0],
|
||||||
|
category: 'settlement',
|
||||||
|
splitMethod: 'full',
|
||||||
|
splits: [
|
||||||
|
{
|
||||||
|
username: fromUser,
|
||||||
|
amount: -amount // Payer gets negative (receives money back)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: toUser,
|
||||||
|
amount: amount // Receiver owes money
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch('/api/cospend/payments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Cookie': request.headers.get('Cookie') || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.message || 'Failed to record settlement');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect back to dashboard on success
|
||||||
|
throw redirect(303, '/cospend');
|
||||||
|
} catch (error) {
|
||||||
|
if (error.status === 303) {
|
||||||
|
throw error; // Re-throw redirect
|
||||||
|
}
|
||||||
|
|
||||||
|
return fail(500, {
|
||||||
|
error: error.message,
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
@@ -1,37 +1,27 @@
|
|||||||
<script>
|
<script>
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { goto } from '$app/navigation';
|
import { enhance } from '$app/forms';
|
||||||
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
||||||
|
|
||||||
export let data;
|
export let data;
|
||||||
|
export let form;
|
||||||
|
|
||||||
let debtData = {
|
// Use server-side data with progressive enhancement
|
||||||
|
let debtData = data.debtData || {
|
||||||
whoOwesMe: [],
|
whoOwesMe: [],
|
||||||
whoIOwe: [],
|
whoIOwe: [],
|
||||||
totalOwedToMe: 0,
|
totalOwedToMe: 0,
|
||||||
totalIOwe: 0
|
totalIOwe: 0
|
||||||
};
|
};
|
||||||
let loading = true;
|
let loading = false; // Start as false since we have server data
|
||||||
let error = null;
|
let error = data.error || form?.error || null;
|
||||||
let selectedSettlement = null;
|
let selectedSettlement = null;
|
||||||
let settlementAmount = '';
|
let settlementAmount = form?.values?.amount || '';
|
||||||
let submitting = false;
|
let submitting = false;
|
||||||
let predefinedMode = isPredefinedUsersMode();
|
let predefinedMode = isPredefinedUsersMode();
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(() => {
|
||||||
await fetchDebtData();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function fetchDebtData() {
|
|
||||||
try {
|
|
||||||
loading = true;
|
|
||||||
const response = await fetch('/api/cospend/debts');
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Failed to fetch debt data');
|
|
||||||
}
|
|
||||||
debtData = await response.json();
|
|
||||||
|
|
||||||
// For predefined mode with 2 users, auto-select the debt if there's only one
|
// For predefined mode with 2 users, auto-select the debt if there's only one
|
||||||
if (predefinedMode && PREDEFINED_USERS.length === 2) {
|
if (predefinedMode && PREDEFINED_USERS.length === 2) {
|
||||||
const totalDebts = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
const totalDebts = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
||||||
@@ -40,32 +30,31 @@
|
|||||||
selectedSettlement = {
|
selectedSettlement = {
|
||||||
type: 'receive',
|
type: 'receive',
|
||||||
from: debtData.whoOwesMe[0].username,
|
from: debtData.whoOwesMe[0].username,
|
||||||
to: data.session?.user?.nickname,
|
to: data.currentUser,
|
||||||
amount: debtData.whoOwesMe[0].netAmount,
|
amount: debtData.whoOwesMe[0].netAmount,
|
||||||
description: `Settlement: ${debtData.whoOwesMe[0].username} pays ${data.session?.user?.nickname}`
|
description: `Settlement: ${debtData.whoOwesMe[0].username} pays ${data.currentUser}`
|
||||||
};
|
};
|
||||||
|
if (!settlementAmount) {
|
||||||
settlementAmount = debtData.whoOwesMe[0].netAmount.toString();
|
settlementAmount = debtData.whoOwesMe[0].netAmount.toString();
|
||||||
|
}
|
||||||
} else if (debtData.whoIOwe.length === 1) {
|
} else if (debtData.whoIOwe.length === 1) {
|
||||||
selectedSettlement = {
|
selectedSettlement = {
|
||||||
type: 'pay',
|
type: 'pay',
|
||||||
from: data.session?.user?.nickname,
|
from: data.currentUser,
|
||||||
to: debtData.whoIOwe[0].username,
|
to: debtData.whoIOwe[0].username,
|
||||||
amount: debtData.whoIOwe[0].netAmount,
|
amount: debtData.whoIOwe[0].netAmount,
|
||||||
description: `Settlement: ${data.session?.user?.nickname} pays ${debtData.whoIOwe[0].username}`
|
description: `Settlement: ${data.currentUser} pays ${debtData.whoIOwe[0].username}`
|
||||||
};
|
};
|
||||||
|
if (!settlementAmount) {
|
||||||
settlementAmount = debtData.whoIOwe[0].netAmount.toString();
|
settlementAmount = debtData.whoIOwe[0].netAmount.toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
|
||||||
error = err.message;
|
|
||||||
} finally {
|
|
||||||
loading = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
function selectSettlement(type, user, amount) {
|
function selectSettlement(type, user, amount) {
|
||||||
const currentUser = data.session?.user?.nickname;
|
const currentUser = data.currentUser;
|
||||||
if (type === 'receive') {
|
if (type === 'receive') {
|
||||||
selectedSettlement = {
|
selectedSettlement = {
|
||||||
type: 'receive',
|
type: 'receive',
|
||||||
@@ -98,18 +87,18 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
submitting = true;
|
submitting = true;
|
||||||
error = null;
|
error = null;
|
||||||
|
|
||||||
// Create a settlement payment
|
try {
|
||||||
|
// Create a settlement payment directly using the API
|
||||||
const payload = {
|
const payload = {
|
||||||
title: `Settlement Payment`,
|
title: 'Settlement Payment',
|
||||||
description: selectedSettlement.description,
|
description: selectedSettlement.description,
|
||||||
amount: amount,
|
amount: amount,
|
||||||
paidBy: selectedSettlement.from,
|
paidBy: selectedSettlement.from,
|
||||||
date: new Date().toISOString().split('T')[0],
|
date: new Date().toISOString().split('T')[0],
|
||||||
category: 'settlement', // Using settlement category
|
category: 'settlement',
|
||||||
splitMethod: 'full',
|
splitMethod: 'full',
|
||||||
splits: [
|
splits: [
|
||||||
{
|
{
|
||||||
@@ -136,11 +125,10 @@
|
|||||||
throw new Error(errorData.message || 'Failed to record settlement');
|
throw new Error(errorData.message || 'Failed to record settlement');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Redirect back to dashboard
|
// Redirect back to dashboard on success
|
||||||
goto('/cospend');
|
window.location.href = '/cospend';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err.message;
|
error = err.message;
|
||||||
} finally {
|
|
||||||
submitting = false;
|
submitting = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -236,7 +224,7 @@
|
|||||||
<div class="user-from">
|
<div class="user-from">
|
||||||
<ProfilePicture username={selectedSettlement.from} size={48} />
|
<ProfilePicture username={selectedSettlement.from} size={48} />
|
||||||
<span class="username">{selectedSettlement.from}</span>
|
<span class="username">{selectedSettlement.from}</span>
|
||||||
{#if selectedSettlement.from === data.session?.user?.nickname}
|
{#if selectedSettlement.from === data.currentUser}
|
||||||
<span class="you-badge">You</span>
|
<span class="you-badge">You</span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -244,7 +232,7 @@
|
|||||||
<div class="user-to">
|
<div class="user-to">
|
||||||
<ProfilePicture username={selectedSettlement.to} size={48} />
|
<ProfilePicture username={selectedSettlement.to} size={48} />
|
||||||
<span class="username">{selectedSettlement.to}</span>
|
<span class="username">{selectedSettlement.to}</span>
|
||||||
{#if selectedSettlement.to === data.session?.user?.nickname}
|
{#if selectedSettlement.to === data.currentUser}
|
||||||
<span class="you-badge">You</span>
|
<span class="you-badge">You</span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -288,12 +276,75 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{:else}
|
||||||
|
<!-- No-JS Fallback Form -->
|
||||||
|
<div class="settlement-details no-js-fallback">
|
||||||
|
<h2>Record Settlement</h2>
|
||||||
|
<form method="POST" action="?/settle" class="settlement-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="settlementType">Settlement Type</label>
|
||||||
|
<select id="settlementType" name="settlementType" required>
|
||||||
|
<option value="">Select settlement type</option>
|
||||||
|
{#each debtData.whoOwesMe as debt}
|
||||||
|
<option value="receive" data-from="{debt.username}" data-to="{data.currentUser}">
|
||||||
|
Receive {formatCurrency(debt.netAmount)} from {debt.username}
|
||||||
|
</option>
|
||||||
|
{/each}
|
||||||
|
{#each debtData.whoIOwe as debt}
|
||||||
|
<option value="pay" data-from="{data.currentUser}" data-to="{debt.username}">
|
||||||
|
Pay {formatCurrency(debt.netAmount)} to {debt.username}
|
||||||
|
</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="fromUser">From User</label>
|
||||||
|
<select id="fromUser" name="fromUser" required>
|
||||||
|
<option value="">Select payer</option>
|
||||||
|
{#each [...debtData.whoOwesMe.map(d => d.username), data.currentUser].filter(Boolean) as user}
|
||||||
|
<option value="{user}">{user}{user === data.currentUser ? ' (You)' : ''}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="toUser">To User</label>
|
||||||
|
<select id="toUser" name="toUser" required>
|
||||||
|
<option value="">Select recipient</option>
|
||||||
|
{#each [...debtData.whoIOwe.map(d => d.username), data.currentUser].filter(Boolean) as user}
|
||||||
|
<option value="{user}">{user}{user === data.currentUser ? ' (You)' : ''}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="fallback-amount">Settlement Amount (CHF)</label>
|
||||||
|
<input
|
||||||
|
id="fallback-amount"
|
||||||
|
name="amount"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0.01"
|
||||||
|
value={form?.values?.amount || ''}
|
||||||
|
placeholder="0.00"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settlement-actions">
|
||||||
|
<button type="submit" class="btn btn-settlement">
|
||||||
|
Record Settlement
|
||||||
|
</button>
|
||||||
|
<a href="/cospend" class="btn btn-secondary">
|
||||||
|
Cancel
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="back-actions">
|
|
||||||
<a href="/cospend" class="btn btn-secondary">← Back to Dashboard</a>
|
|
||||||
</div>
|
|
||||||
{/if}
|
{/if}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
@@ -310,12 +361,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.header-section h1 {
|
.header-section h1 {
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.header-section p {
|
.header-section p {
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,8 +377,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.error {
|
.error {
|
||||||
color: #d32f2f;
|
color: var(--red);
|
||||||
background-color: #ffebee;
|
background-color: var(--nord6);
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
@@ -335,13 +386,14 @@
|
|||||||
.no-debts {
|
.no-debts {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 3rem 2rem;
|
padding: 3rem 2rem;
|
||||||
background: white;
|
background: var(--nord6);
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.no-debts h2 {
|
.no-debts h2 {
|
||||||
color: #28a745;
|
color: var(--green);
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,10 +411,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.available-settlements {
|
.available-settlements {
|
||||||
background: white;
|
background: var(--nord6);
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-section {
|
.settlement-section {
|
||||||
@@ -370,7 +423,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.settlement-section h3 {
|
.settlement-section h3 {
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
}
|
}
|
||||||
@@ -380,21 +433,22 @@
|
|||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
border: 2px solid #e9ecef;
|
border: 2px solid var(--nord4);
|
||||||
border-radius: 0.75rem;
|
border-radius: 0.75rem;
|
||||||
margin-bottom: 0.75rem;
|
margin-bottom: 0.75rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: all 0.2s ease;
|
transition: all 0.2s ease;
|
||||||
|
background: var(--nord5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-option:hover {
|
.settlement-option:hover {
|
||||||
border-color: #28a745;
|
border-color: var(--green);
|
||||||
box-shadow: 0 2px 8px rgba(40, 167, 69, 0.1);
|
box-shadow: 0 2px 8px rgba(163, 190, 140, 0.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-option.selected {
|
.settlement-option.selected {
|
||||||
border-color: #28a745;
|
border-color: var(--green);
|
||||||
background-color: #f8fff9;
|
background-color: var(--nord5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-user {
|
.settlement-user {
|
||||||
@@ -412,24 +466,25 @@
|
|||||||
|
|
||||||
.username {
|
.username {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
.debt-amount {
|
.debt-amount {
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-action {
|
.settlement-action {
|
||||||
color: #28a745;
|
color: var(--green);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-details {
|
.settlement-details {
|
||||||
background: white;
|
background: var(--nord6);
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
height: fit-content;
|
height: fit-content;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -444,7 +499,7 @@
|
|||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
margin-bottom: 1.5rem;
|
margin-bottom: 1.5rem;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
background-color: #f8f9fa;
|
background-color: var(--nord5);
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -457,12 +512,12 @@
|
|||||||
|
|
||||||
.flow-arrow {
|
.flow-arrow {
|
||||||
font-size: 1.5rem;
|
font-size: 1.5rem;
|
||||||
color: #28a745;
|
color: var(--green);
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
|
|
||||||
.you-badge {
|
.you-badge {
|
||||||
background-color: #1976d2;
|
background-color: var(--blue);
|
||||||
color: white;
|
color: white;
|
||||||
padding: 0.125rem 0.5rem;
|
padding: 0.125rem 0.5rem;
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
@@ -478,20 +533,20 @@
|
|||||||
display: block;
|
display: block;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
.amount-input {
|
.amount-input {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
background: #f8f9fa;
|
background: var(--nord5);
|
||||||
border: 1px solid #ced4da;
|
border: 1px solid var(--nord4);
|
||||||
border-radius: 0.375rem;
|
border-radius: 0.375rem;
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.currency {
|
.currency {
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
margin-right: 0.5rem;
|
margin-right: 0.5rem;
|
||||||
}
|
}
|
||||||
@@ -502,6 +557,7 @@
|
|||||||
flex: 1;
|
flex: 1;
|
||||||
padding: 0.25rem;
|
padding: 0.25rem;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
}
|
}
|
||||||
|
|
||||||
.amount-input input:focus {
|
.amount-input input:focus {
|
||||||
@@ -509,17 +565,17 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.max-amount {
|
.max-amount {
|
||||||
color: #666;
|
color: var(--nord3);
|
||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
margin-top: 0.25rem;
|
margin-top: 0.25rem;
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-description {
|
.settlement-description {
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
background-color: #f8f9fa;
|
background-color: var(--nord5);
|
||||||
border-radius: 0.375rem;
|
border-radius: 0.375rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -529,6 +585,48 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.settlement-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select,
|
||||||
|
.form-group input {
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select:focus,
|
||||||
|
.form-group input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-js-fallback {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(body:has(script)) .no-js-fallback {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.btn {
|
.btn {
|
||||||
padding: 0.75rem 1.5rem;
|
padding: 0.75rem 1.5rem;
|
||||||
border: none;
|
border: none;
|
||||||
@@ -542,31 +640,31 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary {
|
.btn-primary {
|
||||||
background-color: #1976d2;
|
background-color: var(--blue);
|
||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-primary:hover {
|
.btn-primary:hover {
|
||||||
background-color: #1565c0;
|
background-color: var(--lightblue);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-secondary {
|
.btn-secondary {
|
||||||
background-color: #f5f5f5;
|
background-color: var(--nord5);
|
||||||
color: #333;
|
color: var(--nord0);
|
||||||
border: 1px solid #ddd;
|
border: 1px solid var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-secondary:hover {
|
.btn-secondary:hover {
|
||||||
background-color: #e8e8e8;
|
background-color: var(--nord4);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-settlement {
|
.btn-settlement {
|
||||||
background: linear-gradient(135deg, #28a745, #20c997);
|
background: linear-gradient(135deg, var(--green), var(--lightblue));
|
||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-settlement:hover:not(:disabled) {
|
.btn-settlement:hover:not(:disabled) {
|
||||||
background: linear-gradient(135deg, #20c997, #1e7e34);
|
background: linear-gradient(135deg, var(--lightblue), var(--green));
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-settlement:disabled {
|
.btn-settlement:disabled {
|
||||||
@@ -583,6 +681,111 @@
|
|||||||
margin-top: 1.5rem;
|
margin-top: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header-section h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-debts {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.available-settlements {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-section h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
background: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option:hover {
|
||||||
|
box-shadow: 0 2px 8px rgba(163, 190, 140, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option.selected {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-amount {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-details {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-section label {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.currency {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.max-amount {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-description {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input input {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select,
|
||||||
|
.form-group input {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
@media (max-width: 600px) {
|
||||||
.settle-main {
|
.settle-main {
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
|
@@ -1,35 +1,54 @@
|
|||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { MONGO_URL } from '$env/static/private';
|
import { MONGO_URL } from '$env/static/private';
|
||||||
/*
|
|
||||||
0 - disconnected
|
let isConnected = false;
|
||||||
1 - connected
|
|
||||||
2 - connecting
|
|
||||||
3 - disconnecting
|
|
||||||
4 - uninitialized
|
|
||||||
*/
|
|
||||||
const mongoConnection = {
|
|
||||||
isConnected: 0,
|
|
||||||
};
|
|
||||||
|
|
||||||
export const dbConnect = async () => {
|
export const dbConnect = async () => {
|
||||||
if (mongoConnection.isConnected === 1) {
|
// If already connected, return immediately
|
||||||
return;
|
if (isConnected && mongoose.connection.readyState === 1) {
|
||||||
|
return mongoose.connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mongoose.connections.length > 0) {
|
try {
|
||||||
mongoConnection.isConnected = mongoose.connections[0].readyState;
|
// Configure MongoDB driver options
|
||||||
if (mongoConnection.isConnected === 1) {
|
const options = {
|
||||||
return;
|
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
|
||||||
await mongoose.disconnect();
|
|
||||||
}
|
|
||||||
await mongoose.connect(MONGO_URL ?? '');
|
|
||||||
mongoConnection.isConnected = 1;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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 () => {
|
export const dbDisconnect = async () => {
|
||||||
// Don't disconnect in production to avoid "Client must be connected" errors
|
// Keep connections persistent for performance and to avoid race conditions
|
||||||
// The connection pool will handle connection cleanup automatically
|
// MongoDB driver will handle connection pooling and cleanup automatically
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
31377
static/allioli.tsv
Normal file
31377
static/allioli.tsv
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user