Add comprehensive recurring payments system with scheduling

- Add RecurringPayment model with flexible scheduling options
- Implement node-cron based scheduler for payment processing
- Create API endpoints for CRUD operations on recurring payments
- Add recurring payments management UI with create/edit forms
- Integrate scheduler initialization in hooks.server.ts
- Enhance payments/add form with progressive enhancement
- Add recurring payments button to main dashboard
- Improve server-side rendering for better performance

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-12 12:41:18 +02:00
parent 701434d532
commit 6ab395e98a
28 changed files with 4412 additions and 94 deletions

191
RECURRING_PAYMENTS_SETUP.md Normal file
View File

@@ -0,0 +1,191 @@
# Recurring Payments Setup
This document explains how to set up and use the recurring payments feature in your Cospend application.
## Features
- **Daily, Weekly, Monthly recurring payments**: Simple frequency options
- **Custom Cron scheduling**: Advanced users can use cron expressions for complex schedules
- **Full payment management**: Create, edit, pause, and delete recurring payments
- **Automatic execution**: Payments are automatically created based on schedule
- **Split support**: All payment split methods are supported (equal, proportional, personal+equal, full payment)
## Setup
### 1. Environment Variables
Add the following optional environment variable to your `.env` file for secure cron job execution:
```env
CRON_API_TOKEN=your-secure-random-token-here
```
### 2. Database Setup
The recurring payments feature uses MongoDB models that are automatically created. No additional database setup is required.
### 3. Background Job Setup
You need to set up a recurring job to automatically process due payments. Here are several options:
#### Option A: System Cron (Linux/macOS)
Add the following to your crontab (run `crontab -e`):
```bash
# Run every 5 minutes
*/5 * * * * curl -X POST -H "Authorization: Bearer your-secure-random-token-here" https://yourdomain.com/api/cospend/recurring-payments/cron-execute
# Or run every hour
0 * * * * curl -X POST -H "Authorization: Bearer your-secure-random-token-here" https://yourdomain.com/api/cospend/recurring-payments/cron-execute
```
#### Option B: GitHub Actions (if hosted on a platform that supports it)
Create `.github/workflows/recurring-payments.yml`:
```yaml
name: Process Recurring Payments
on:
schedule:
- cron: '*/5 * * * *' # Every 5 minutes
workflow_dispatch: # Allow manual triggering
jobs:
process-payments:
runs-on: ubuntu-latest
steps:
- name: Process recurring payments
run: |
curl -X POST \
-H "Authorization: Bearer ${{ secrets.CRON_API_TOKEN }}" \
https://yourdomain.com/api/cospend/recurring-payments/cron-execute
```
#### Option C: Cloud Function/Serverless
Deploy a simple cloud function that calls the endpoint on a schedule:
```javascript
// Example for Vercel/Netlify Functions
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const response = await fetch('https://yourdomain.com/api/cospend/recurring-payments/cron-execute', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.CRON_API_TOKEN}`
}
});
const result = await response.json();
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
```
#### Option D: Manual Execution
For testing or manual processing, you can call the endpoint directly:
```bash
curl -X POST \
-H "Authorization: Bearer your-secure-random-token-here" \
-H "Content-Type: application/json" \
https://yourdomain.com/api/cospend/recurring-payments/cron-execute
```
## Usage
### Creating Recurring Payments
1. Navigate to `/cospend/recurring/add`
2. Fill in the payment details (title, amount, category, etc.)
3. Choose frequency:
- **Daily**: Executes every day
- **Weekly**: Executes every week
- **Monthly**: Executes every month
- **Custom**: Use cron expressions for advanced scheduling
4. Set up user splits (same options as regular payments)
5. Set start date and optional end date
### Managing Recurring Payments
1. Navigate to `/cospend/recurring`
2. View all recurring payments with their next execution dates
3. Edit, pause, activate, or delete recurring payments
4. Filter by active/inactive status
### Cron Expression Examples
For custom frequency, you can use cron expressions:
- `0 9 * * *` - Every day at 9:00 AM
- `0 9 * * 1` - Every Monday at 9:00 AM
- `0 9 1 * *` - Every 1st of the month at 9:00 AM
- `0 9 1,15 * *` - Every 1st and 15th of the month at 9:00 AM
- `0 9 * * 1-5` - Every weekday at 9:00 AM
- `0 */6 * * *` - Every 6 hours
## Monitoring
The cron execution endpoint returns detailed information about processed payments:
```json
{
"success": true,
"timestamp": "2024-01-01T09:00:00.000Z",
"processed": 3,
"successful": 2,
"failed": 1,
"results": [
{
"recurringPaymentId": "...",
"paymentId": "...",
"title": "Monthly Rent",
"amount": 1200,
"nextExecution": "2024-02-01T09:00:00.000Z",
"success": true
}
]
}
```
Check your application logs for detailed processing information.
## Security Considerations
1. **API Token**: Use a strong, random token for the `CRON_API_TOKEN`
2. **HTTPS**: Always use HTTPS for the cron endpoint
3. **Rate Limiting**: Consider adding rate limiting to the cron endpoint
4. **Monitoring**: Monitor the cron job execution and set up alerts for failures
## Troubleshooting
### Common Issues
1. **Payments not executing**: Check that your cron job is running and the API token is correct
2. **Permission errors**: Ensure the cron endpoint can access the database
3. **Time zone issues**: The system uses server time for scheduling
4. **Cron expression errors**: Validate cron expressions using online tools
### Logs
Check server logs for detailed error messages:
- Look for `[Cron]` prefixed messages
- Monitor database connection issues
- Check for validation errors in payment creation
## Future Enhancements
Potential improvements to consider:
- Web-based cron job management
- Email notifications for successful/failed executions
- Payment execution history and analytics
- Time zone support for scheduling
- Webhook notifications

View File

@@ -17,6 +17,7 @@
"@sveltejs/kit": "^2.37.0",
"@sveltejs/vite-plugin-svelte": "^6.1.3",
"@types/node": "^22.12.0",
"@types/node-cron": "^3.0.11",
"svelte": "^5.38.6",
"svelte-check": "^4.0.0",
"tslib": "^2.6.0",
@@ -28,6 +29,7 @@
"@sveltejs/adapter-node": "^5.0.0",
"cheerio": "1.0.0-rc.12",
"mongoose": "^8.0.0",
"node-cron": "^4.2.1",
"sharp": "^0.33.0"
}
}

17
pnpm-lock.yaml generated
View File

@@ -20,6 +20,9 @@ importers:
mongoose:
specifier: ^8.0.0
version: 8.18.0(socks@2.7.1)
node-cron:
specifier: ^4.2.1
version: 4.2.1
sharp:
specifier: ^0.33.0
version: 0.33.5
@@ -39,6 +42,9 @@ importers:
'@types/node':
specifier: ^22.12.0
version: 22.18.0
'@types/node-cron':
specifier: ^3.0.11
version: 3.0.11
svelte:
specifier: ^5.38.6
version: 5.38.6
@@ -584,6 +590,9 @@ packages:
'@types/estree@1.0.8':
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
'@types/node-cron@3.0.11':
resolution: {integrity: sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==}
'@types/node@22.18.0':
resolution: {integrity: sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==}
@@ -842,6 +851,10 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
node-cron@4.2.1:
resolution: {integrity: sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==}
engines: {node: '>=6.0.0'}
nth-check@2.1.1:
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
@@ -1418,6 +1431,8 @@ snapshots:
'@types/estree@1.0.8': {}
'@types/node-cron@3.0.11': {}
'@types/node@22.18.0':
dependencies:
undici-types: 6.21.0
@@ -1669,6 +1684,8 @@ snapshots:
nanoid@3.3.11: {}
node-cron@4.2.1: {}
nth-check@2.1.1:
dependencies:
boolbase: 1.0.0

View File

@@ -6,6 +6,10 @@ import Authentik from "@auth/core/providers/authentik"
import { AUTHENTIK_ID, AUTHENTIK_SECRET, AUTHENTIK_ISSUER } from "$env/static/private";
import { sequence } from "@sveltejs/kit/hooks"
import * as auth from "./auth"
import { initializeScheduler } from "./lib/server/scheduler"
// Initialize the recurring payment scheduler
initializeScheduler();
async function authorization({ event, resolve }) {
// Protect any routes under /authenticated

View File

@@ -2,17 +2,20 @@
import { onMount } from 'svelte';
import ProfilePicture from './ProfilePicture.svelte';
let balance = {
export let initialBalance = null;
export let initialDebtData = null;
let balance = initialBalance || {
netBalance: 0,
recentSplits: []
};
let debtData = {
let debtData = initialDebtData || {
whoOwesMe: [],
whoIOwe: [],
totalOwedToMe: 0,
totalIOwe: 0
};
let loading = true;
let loading = !initialBalance || !initialDebtData; // Only show loading if we don't have initial data
let error = null;
let singleDebtUser = null;
let shouldShowIntegratedView = false;
@@ -47,7 +50,15 @@
onMount(async () => {
// Mark that JavaScript is loaded
if (typeof document !== 'undefined') {
document.body.classList.add('js-loaded');
}
// Only fetch data if we don't have initial data (progressive enhancement)
if (!initialBalance || !initialDebtData) {
await Promise.all([fetchBalance(), fetchDebtBreakdown()]);
}
});
async function fetchBalance() {

184
src/lib/server/scheduler.ts Normal file
View File

@@ -0,0 +1,184 @@
import cron from 'node-cron';
import { RecurringPayment } from '../../models/RecurringPayment';
import { Payment } from '../../models/Payment';
import { PaymentSplit } from '../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../utils/db';
import { calculateNextExecutionDate } from '../utils/recurring';
class RecurringPaymentScheduler {
private isRunning = false;
private task: cron.ScheduledTask | null = null;
// Start the scheduler - runs every minute to check for due payments
start() {
if (this.task) {
console.log('[Scheduler] Already running');
return;
}
console.log('[Scheduler] Starting recurring payments scheduler');
// Run every minute to check for due payments
this.task = cron.schedule('* * * * *', async () => {
if (this.isRunning) {
console.log('[Scheduler] Previous execution still running, skipping');
return;
}
await this.processRecurringPayments();
}, {
scheduled: true,
timezone: 'Europe/Zurich' // Adjust timezone as needed
});
console.log('[Scheduler] Recurring payments scheduler started (runs every minute)');
}
stop() {
if (this.task) {
this.task.destroy();
this.task = null;
console.log('[Scheduler] Recurring payments scheduler stopped');
}
}
async processRecurringPayments() {
if (this.isRunning) return;
this.isRunning = true;
let dbConnected = false;
try {
await dbConnect();
dbConnected = true;
const now = new Date();
// Find all active recurring payments that are due (with 1 minute tolerance)
const duePayments = await RecurringPayment.find({
isActive: true,
nextExecutionDate: { $lte: now },
$or: [
{ endDate: { $exists: false } },
{ endDate: null },
{ endDate: { $gte: now } }
]
});
if (duePayments.length === 0) {
return; // No payments due
}
console.log(`[Scheduler] Processing ${duePayments.length} due recurring payments at ${now.toISOString()}`);
let successCount = 0;
let failureCount = 0;
for (const recurringPayment of duePayments) {
try {
console.log(`[Scheduler] Processing: ${recurringPayment.title} (${recurringPayment._id})`);
// Create the payment
const payment = await Payment.create({
title: `${recurringPayment.title}`,
description: recurringPayment.description ?
`${recurringPayment.description} (Auto-generated from recurring payment)` :
'Auto-generated from recurring payment',
amount: recurringPayment.amount,
currency: recurringPayment.currency,
paidBy: recurringPayment.paidBy,
date: now,
category: recurringPayment.category,
splitMethod: recurringPayment.splitMethod,
createdBy: `${recurringPayment.createdBy} (Auto)`
});
// Create payment splits
const splitPromises = recurringPayment.splits.map((split) => {
return PaymentSplit.create({
paymentId: payment._id,
username: split.username,
amount: split.amount,
proportion: split.proportion,
personalAmount: split.personalAmount
});
});
await Promise.all(splitPromises);
// Calculate next execution date
const nextExecutionDate = calculateNextExecutionDate(recurringPayment, now);
// Update the recurring payment
await RecurringPayment.findByIdAndUpdate(recurringPayment._id, {
lastExecutionDate: now,
nextExecutionDate: nextExecutionDate
});
successCount++;
console.log(`[Scheduler] ✓ Created payment for "${recurringPayment.title}", next execution: ${nextExecutionDate.toISOString()}`);
} catch (paymentError) {
console.error(`[Scheduler] ✗ Error processing recurring payment ${recurringPayment._id}:`, paymentError);
failureCount++;
// Optionally, you could disable recurring payments that fail repeatedly
// or implement a retry mechanism here
}
}
if (successCount > 0 || failureCount > 0) {
console.log(`[Scheduler] Completed. Success: ${successCount}, Failures: ${failureCount}`);
}
} catch (error) {
console.error('[Scheduler] Error during recurring payment processing:', error);
} finally {
this.isRunning = false;
if (dbConnected) {
try {
await dbDisconnect();
} catch (disconnectError) {
console.error('[Scheduler] Error disconnecting from database:', disconnectError);
}
}
}
}
// Manual execution for testing
async executeNow() {
console.log('[Scheduler] Manual execution requested');
await this.processRecurringPayments();
}
getStatus() {
return {
isRunning: this.isRunning,
isScheduled: this.task !== null,
nextRun: this.task?.nextDate()?.toISOString()
};
}
}
// Singleton instance
export const recurringPaymentScheduler = new RecurringPaymentScheduler();
// Helper function to initialize the scheduler
export function initializeScheduler() {
if (typeof window === 'undefined') { // Only run on server
recurringPaymentScheduler.start();
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('[Scheduler] Received SIGTERM, stopping scheduler...');
recurringPaymentScheduler.stop();
process.exit(0);
});
process.on('SIGINT', () => {
console.log('[Scheduler] Received SIGINT, stopping scheduler...');
recurringPaymentScheduler.stop();
process.exit(0);
});
}
}

230
src/lib/utils/recurring.ts Normal file
View File

@@ -0,0 +1,230 @@
import type { IRecurringPayment } from '../../models/RecurringPayment';
export interface CronJobFields {
minute: string;
hour: string;
dayOfMonth: string;
month: string;
dayOfWeek: string;
}
export function parseCronExpression(cronExpression: string): CronJobFields | null {
const parts = cronExpression.trim().split(/\s+/);
if (parts.length !== 5) {
return null;
}
return {
minute: parts[0],
hour: parts[1],
dayOfMonth: parts[2],
month: parts[3],
dayOfWeek: parts[4]
};
}
export function validateCronExpression(cronExpression: string): boolean {
const fields = parseCronExpression(cronExpression);
if (!fields) return false;
// Basic validation for cron fields
const validations = [
{ field: fields.minute, min: 0, max: 59 },
{ field: fields.hour, min: 0, max: 23 },
{ field: fields.dayOfMonth, min: 1, max: 31 },
{ field: fields.month, min: 1, max: 12 },
{ field: fields.dayOfWeek, min: 0, max: 7 }
];
for (const validation of validations) {
if (!isValidCronField(validation.field, validation.min, validation.max)) {
return false;
}
}
return true;
}
function isValidCronField(field: string, min: number, max: number): boolean {
if (field === '*') return true;
// Handle ranges (e.g., "1-5")
if (field.includes('-')) {
const [start, end] = field.split('-').map(Number);
return !isNaN(start) && !isNaN(end) && start >= min && end <= max && start <= end;
}
// Handle step values (e.g., "*/5", "1-10/2")
if (field.includes('/')) {
const [range, step] = field.split('/');
const stepNum = Number(step);
if (isNaN(stepNum) || stepNum <= 0) return false;
if (range === '*') return true;
if (range.includes('-')) {
const [start, end] = range.split('-').map(Number);
return !isNaN(start) && !isNaN(end) && start >= min && end <= max && start <= end;
}
const num = Number(range);
return !isNaN(num) && num >= min && num <= max;
}
// Handle comma-separated values (e.g., "1,3,5")
if (field.includes(',')) {
const values = field.split(',').map(Number);
return values.every(val => !isNaN(val) && val >= min && val <= max);
}
// Handle single number
const num = Number(field);
return !isNaN(num) && num >= min && num <= max;
}
export function calculateNextExecutionDate(
recurringPayment: IRecurringPayment,
fromDate: Date = new Date()
): Date {
const baseDate = new Date(fromDate);
switch (recurringPayment.frequency) {
case 'daily':
baseDate.setDate(baseDate.getDate() + 1);
break;
case 'weekly':
baseDate.setDate(baseDate.getDate() + 7);
break;
case 'monthly':
baseDate.setMonth(baseDate.getMonth() + 1);
break;
case 'custom':
if (!recurringPayment.cronExpression) {
throw new Error('Cron expression required for custom frequency');
}
return calculateNextCronDate(recurringPayment.cronExpression, baseDate);
default:
throw new Error('Invalid frequency');
}
return baseDate;
}
export function calculateNextCronDate(cronExpression: string, fromDate: Date): Date {
const fields = parseCronExpression(cronExpression);
if (!fields) {
throw new Error('Invalid cron expression');
}
const next = new Date(fromDate);
next.setSeconds(0);
next.setMilliseconds(0);
// Start from the next minute
next.setMinutes(next.getMinutes() + 1);
// Find the next valid date
for (let attempts = 0; attempts < 366; attempts++) { // Prevent infinite loops
if (matchesCronFields(next, fields)) {
return next;
}
next.setMinutes(next.getMinutes() + 1);
}
throw new Error('Unable to find next execution date within reasonable range');
}
function matchesCronFields(date: Date, fields: CronJobFields): boolean {
return (
matchesCronField(date.getMinutes(), fields.minute, 0, 59) &&
matchesCronField(date.getHours(), fields.hour, 0, 23) &&
matchesCronField(date.getDate(), fields.dayOfMonth, 1, 31) &&
matchesCronField(date.getMonth() + 1, fields.month, 1, 12) &&
matchesCronField(date.getDay(), fields.dayOfWeek, 0, 7)
);
}
function matchesCronField(value: number, field: string, min: number, max: number): boolean {
if (field === '*') return true;
// Handle ranges (e.g., "1-5")
if (field.includes('-')) {
const [start, end] = field.split('-').map(Number);
return value >= start && value <= end;
}
// Handle step values (e.g., "*/5", "1-10/2")
if (field.includes('/')) {
const [range, step] = field.split('/');
const stepNum = Number(step);
if (range === '*') {
return (value - min) % stepNum === 0;
}
if (range.includes('-')) {
const [start, end] = range.split('-').map(Number);
return value >= start && value <= end && (value - start) % stepNum === 0;
}
const rangeStart = Number(range);
return value >= rangeStart && (value - rangeStart) % stepNum === 0;
}
// Handle comma-separated values (e.g., "1,3,5")
if (field.includes(',')) {
const values = field.split(',').map(Number);
return values.includes(value);
}
// Handle single number
return value === Number(field);
}
export function getFrequencyDescription(recurringPayment: IRecurringPayment): string {
switch (recurringPayment.frequency) {
case 'daily':
return 'Every day';
case 'weekly':
return 'Every week';
case 'monthly':
return 'Every month';
case 'custom':
return `Custom: ${recurringPayment.cronExpression}`;
default:
return 'Unknown frequency';
}
}
export function formatNextExecution(date: Date): string {
const now = new Date();
const diffMs = date.getTime() - now.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) {
return `Today at ${date.toLocaleTimeString('de-CH', {
hour: '2-digit',
minute: '2-digit'
})}`;
} else if (diffDays === 1) {
return `Tomorrow at ${date.toLocaleTimeString('de-CH', {
hour: '2-digit',
minute: '2-digit'
})}`;
} else if (diffDays < 7) {
return `In ${diffDays} days at ${date.toLocaleTimeString('de-CH', {
hour: '2-digit',
minute: '2-digit'
})}`;
} else {
return date.toLocaleString('de-CH', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
}

View File

@@ -0,0 +1,141 @@
import mongoose from 'mongoose';
export interface IRecurringPayment {
_id?: string;
title: string;
description?: string;
amount: number;
currency: string;
paidBy: string; // username/nickname of the person who paid
category: 'groceries' | 'shopping' | 'travel' | 'restaurant' | 'utilities' | 'fun' | 'settlement';
splitMethod: 'equal' | 'full' | 'proportional' | 'personal_equal';
splits: Array<{
username: string;
amount?: number;
proportion?: number;
personalAmount?: number;
}>;
frequency: 'daily' | 'weekly' | 'monthly' | 'custom';
cronExpression?: string; // For custom frequencies using cron syntax
isActive: boolean;
nextExecutionDate: Date;
lastExecutionDate?: Date;
startDate: Date;
endDate?: Date; // Optional end date for the recurring payments
createdBy: string;
createdAt?: Date;
updatedAt?: Date;
}
const RecurringPaymentSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true
},
description: {
type: String,
trim: true
},
amount: {
type: Number,
required: true,
min: 0
},
currency: {
type: String,
required: true,
default: 'CHF',
enum: ['CHF']
},
paidBy: {
type: String,
required: true,
trim: true
},
category: {
type: String,
required: true,
enum: ['groceries', 'shopping', 'travel', 'restaurant', 'utilities', 'fun', 'settlement'],
default: 'groceries'
},
splitMethod: {
type: String,
required: true,
enum: ['equal', 'full', 'proportional', 'personal_equal'],
default: 'equal'
},
splits: [{
username: {
type: String,
required: true,
trim: true
},
amount: {
type: Number
},
proportion: {
type: Number,
min: 0,
max: 1
},
personalAmount: {
type: Number,
min: 0
}
}],
frequency: {
type: String,
required: true,
enum: ['daily', 'weekly', 'monthly', 'custom']
},
cronExpression: {
type: String,
validate: {
validator: function(value: string) {
// Only validate if frequency is custom
if (this.frequency === 'custom') {
return value != null && value.trim().length > 0;
}
return true;
},
message: 'Cron expression is required when frequency is custom'
}
},
isActive: {
type: Boolean,
default: true
},
nextExecutionDate: {
type: Date,
required: true
},
lastExecutionDate: {
type: Date
},
startDate: {
type: Date,
required: true,
default: Date.now
},
endDate: {
type: Date
},
createdBy: {
type: String,
required: true,
trim: true
}
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
// Index for efficiently finding payments that need to be executed
RecurringPaymentSchema.index({ nextExecutionDate: 1, isActive: 1 });
export const RecurringPayment = mongoose.model<IRecurringPayment>("RecurringPayment", RecurringPaymentSchema);

View File

@@ -0,0 +1,139 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../models/RecurringPayment';
import { dbConnect, dbDisconnect } from '../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate, validateCronExpression } from '../../../../lib/utils/recurring';
export const GET: RequestHandler = async ({ locals, url }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const limit = parseInt(url.searchParams.get('limit') || '50');
const offset = parseInt(url.searchParams.get('offset') || '0');
const activeOnly = url.searchParams.get('active') === 'true';
await dbConnect();
try {
const query: any = {};
if (activeOnly) {
query.isActive = true;
}
const recurringPayments = await RecurringPayment.find(query)
.sort({ nextExecutionDate: 1, createdAt: -1 })
.limit(limit)
.skip(offset)
.lean();
return json({ recurringPayments });
} catch (e) {
console.error('Error fetching recurring payments:', e);
throw error(500, 'Failed to fetch recurring payments');
} finally {
await dbDisconnect();
}
};
export const POST: RequestHandler = async ({ request, locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const data = await request.json();
const {
title,
description,
amount,
paidBy,
category,
splitMethod,
splits,
frequency,
cronExpression,
startDate,
endDate
} = data;
if (!title || !amount || !paidBy || !splitMethod || !splits || !frequency) {
throw error(400, 'Missing required fields');
}
if (amount <= 0) {
throw error(400, 'Amount must be positive');
}
if (!['equal', 'full', 'proportional', 'personal_equal'].includes(splitMethod)) {
throw error(400, 'Invalid split method');
}
if (!['daily', 'weekly', 'monthly', 'custom'].includes(frequency)) {
throw error(400, 'Invalid frequency');
}
if (frequency === 'custom') {
if (!cronExpression || !validateCronExpression(cronExpression)) {
throw error(400, 'Valid cron expression required for custom frequency');
}
}
if (category && !['groceries', 'shopping', 'travel', 'restaurant', 'utilities', 'fun', 'settlement'].includes(category)) {
throw error(400, 'Invalid category');
}
// Validate personal + equal split method
if (splitMethod === 'personal_equal' && splits) {
const totalPersonal = splits.reduce((sum: number, split: any) => {
return sum + (parseFloat(split.personalAmount) || 0);
}, 0);
if (totalPersonal > amount) {
throw error(400, 'Personal amounts cannot exceed total payment amount');
}
}
await dbConnect();
try {
const recurringPaymentData = {
title,
description,
amount,
currency: 'CHF',
paidBy,
category: category || 'groceries',
splitMethod,
splits,
frequency,
cronExpression: frequency === 'custom' ? cronExpression : undefined,
startDate: startDate ? new Date(startDate) : new Date(),
endDate: endDate ? new Date(endDate) : undefined,
createdBy: auth.user.nickname,
isActive: true,
nextExecutionDate: new Date() // Will be calculated below
};
// Calculate the next execution date
recurringPaymentData.nextExecutionDate = calculateNextExecutionDate({
...recurringPaymentData,
frequency,
cronExpression
} as any, recurringPaymentData.startDate);
const recurringPayment = await RecurringPayment.create(recurringPaymentData);
return json({
success: true,
recurringPayment: recurringPayment._id
});
} catch (e) {
console.error('Error creating recurring payment:', e);
throw error(500, 'Failed to create recurring payment');
} finally {
await dbDisconnect();
}
};

View File

@@ -0,0 +1,184 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate, validateCronExpression } from '../../../../../lib/utils/recurring';
import mongoose from 'mongoose';
export const GET: RequestHandler = async ({ params, locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const { id } = params;
if (!id || !mongoose.Types.ObjectId.isValid(id)) {
throw error(400, 'Invalid payment ID');
}
await dbConnect();
try {
const recurringPayment = await RecurringPayment.findById(id).lean();
if (!recurringPayment) {
throw error(404, 'Recurring payment not found');
}
return json({ recurringPayment });
} catch (e) {
console.error('Error fetching recurring payment:', e);
throw error(500, 'Failed to fetch recurring payment');
} finally {
await dbDisconnect();
}
};
export const PUT: RequestHandler = async ({ params, request, locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const { id } = params;
if (!id || !mongoose.Types.ObjectId.isValid(id)) {
throw error(400, 'Invalid payment ID');
}
const data = await request.json();
const {
title,
description,
amount,
paidBy,
category,
splitMethod,
splits,
frequency,
cronExpression,
startDate,
endDate,
isActive
} = data;
await dbConnect();
try {
const existingPayment = await RecurringPayment.findById(id);
if (!existingPayment) {
throw error(404, 'Recurring payment not found');
}
const updateData: any = {};
if (title !== undefined) updateData.title = title;
if (description !== undefined) updateData.description = description;
if (amount !== undefined) {
if (amount <= 0) {
throw error(400, 'Amount must be positive');
}
updateData.amount = amount;
}
if (paidBy !== undefined) updateData.paidBy = paidBy;
if (category !== undefined) {
if (!['groceries', 'shopping', 'travel', 'restaurant', 'utilities', 'fun', 'settlement'].includes(category)) {
throw error(400, 'Invalid category');
}
updateData.category = category;
}
if (splitMethod !== undefined) {
if (!['equal', 'full', 'proportional', 'personal_equal'].includes(splitMethod)) {
throw error(400, 'Invalid split method');
}
updateData.splitMethod = splitMethod;
}
if (splits !== undefined) {
updateData.splits = splits;
}
if (frequency !== undefined) {
if (!['daily', 'weekly', 'monthly', 'custom'].includes(frequency)) {
throw error(400, 'Invalid frequency');
}
updateData.frequency = frequency;
}
if (cronExpression !== undefined) {
if (frequency === 'custom' && !validateCronExpression(cronExpression)) {
throw error(400, 'Valid cron expression required for custom frequency');
}
updateData.cronExpression = frequency === 'custom' ? cronExpression : undefined;
}
if (startDate !== undefined) updateData.startDate = new Date(startDate);
if (endDate !== undefined) updateData.endDate = endDate ? new Date(endDate) : null;
if (isActive !== undefined) updateData.isActive = isActive;
// Validate personal + equal split method
if (splitMethod === 'personal_equal' && splits && amount) {
const totalPersonal = splits.reduce((sum: number, split: any) => {
return sum + (parseFloat(split.personalAmount) || 0);
}, 0);
if (totalPersonal > amount) {
throw error(400, 'Personal amounts cannot exceed total payment amount');
}
}
// Recalculate next execution date if frequency, cron expression, or start date changed
if (frequency !== undefined || cronExpression !== undefined || startDate !== undefined) {
const updatedPayment = { ...existingPayment.toObject(), ...updateData };
updateData.nextExecutionDate = calculateNextExecutionDate(
updatedPayment,
updateData.startDate || existingPayment.startDate
);
}
const recurringPayment = await RecurringPayment.findByIdAndUpdate(
id,
updateData,
{ new: true, runValidators: true }
);
return json({
success: true,
recurringPayment
});
} catch (e) {
console.error('Error updating recurring payment:', e);
if (e instanceof mongoose.Error.ValidationError) {
throw error(400, e.message);
}
throw error(500, 'Failed to update recurring payment');
} finally {
await dbDisconnect();
}
};
export const DELETE: RequestHandler = async ({ params, locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
const { id } = params;
if (!id || !mongoose.Types.ObjectId.isValid(id)) {
throw error(400, 'Invalid payment ID');
}
await dbConnect();
try {
const recurringPayment = await RecurringPayment.findByIdAndDelete(id);
if (!recurringPayment) {
throw error(404, 'Recurring payment not found');
}
return json({ success: true });
} catch (e) {
console.error('Error deleting recurring payment:', e);
throw error(500, 'Failed to delete recurring payment');
} finally {
await dbDisconnect();
}
};

View File

@@ -0,0 +1,124 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { Payment } from '../../../../../models/Payment';
import { PaymentSplit } from '../../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
// This endpoint is designed to be called by a cron job or external scheduler
// It processes all recurring payments that are due for execution
export const POST: RequestHandler = async ({ request }) => {
// Optional: Add basic authentication or API key validation here
const authHeader = request.headers.get('authorization');
const expectedToken = process.env.CRON_API_TOKEN;
if (expectedToken && authHeader !== `Bearer ${expectedToken}`) {
throw error(401, 'Unauthorized');
}
await dbConnect();
try {
const now = new Date();
console.log(`[Cron] Starting recurring payments processing at ${now.toISOString()}`);
// Find all active recurring payments that are due
const duePayments = await RecurringPayment.find({
isActive: true,
nextExecutionDate: { $lte: now },
$or: [
{ endDate: { $exists: false } },
{ endDate: null },
{ endDate: { $gte: now } }
]
});
console.log(`[Cron] Found ${duePayments.length} due recurring payments`);
const results = [];
let successCount = 0;
let failureCount = 0;
for (const recurringPayment of duePayments) {
try {
console.log(`[Cron] Processing recurring payment: ${recurringPayment.title} (${recurringPayment._id})`);
// Create the payment
const payment = await Payment.create({
title: `${recurringPayment.title} (Auto)`,
description: `Automatically generated from recurring payment: ${recurringPayment.description || 'No description'}`,
amount: recurringPayment.amount,
currency: recurringPayment.currency,
paidBy: recurringPayment.paidBy,
date: now,
category: recurringPayment.category,
splitMethod: recurringPayment.splitMethod,
createdBy: recurringPayment.createdBy
});
// Create payment splits
const splitPromises = recurringPayment.splits.map((split) => {
return PaymentSplit.create({
paymentId: payment._id,
username: split.username,
amount: split.amount,
proportion: split.proportion,
personalAmount: split.personalAmount
});
});
await Promise.all(splitPromises);
// Calculate next execution date
const nextExecutionDate = calculateNextExecutionDate(recurringPayment, now);
// Update the recurring payment
await RecurringPayment.findByIdAndUpdate(recurringPayment._id, {
lastExecutionDate: now,
nextExecutionDate: nextExecutionDate
});
successCount++;
results.push({
recurringPaymentId: recurringPayment._id,
paymentId: payment._id,
title: recurringPayment.title,
amount: recurringPayment.amount,
nextExecution: nextExecutionDate,
success: true
});
console.log(`[Cron] Successfully processed: ${recurringPayment.title}, next execution: ${nextExecutionDate.toISOString()}`);
} catch (paymentError) {
console.error(`[Cron] Error processing recurring payment ${recurringPayment._id}:`, paymentError);
failureCount++;
results.push({
recurringPaymentId: recurringPayment._id,
title: recurringPayment.title,
amount: recurringPayment.amount,
success: false,
error: paymentError instanceof Error ? paymentError.message : 'Unknown error'
});
}
}
console.log(`[Cron] Completed processing. Success: ${successCount}, Failures: ${failureCount}`);
return json({
success: true,
timestamp: now.toISOString(),
processed: duePayments.length,
successful: successCount,
failed: failureCount,
results: results
});
} catch (e) {
console.error('[Cron] Error executing recurring payments:', e);
throw error(500, 'Failed to execute recurring payments');
} finally {
await dbDisconnect();
}
};

View File

@@ -0,0 +1,104 @@
import type { RequestHandler } from '@sveltejs/kit';
import { RecurringPayment } from '../../../../../models/RecurringPayment';
import { Payment } from '../../../../../models/Payment';
import { PaymentSplit } from '../../../../../models/PaymentSplit';
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
import { error, json } from '@sveltejs/kit';
import { calculateNextExecutionDate } from '../../../../../lib/utils/recurring';
export const POST: RequestHandler = async ({ locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
await dbConnect();
try {
const now = new Date();
// Find all active recurring payments that are due
const duePayments = await RecurringPayment.find({
isActive: true,
nextExecutionDate: { $lte: now },
$or: [
{ endDate: { $exists: false } },
{ endDate: null },
{ endDate: { $gte: now } }
]
});
const results = [];
for (const recurringPayment of duePayments) {
try {
// Create the payment
const payment = await Payment.create({
title: recurringPayment.title,
description: recurringPayment.description,
amount: recurringPayment.amount,
currency: recurringPayment.currency,
paidBy: recurringPayment.paidBy,
date: now,
category: recurringPayment.category,
splitMethod: recurringPayment.splitMethod,
createdBy: recurringPayment.createdBy
});
// Create payment splits
const splitPromises = recurringPayment.splits.map((split) => {
return PaymentSplit.create({
paymentId: payment._id,
username: split.username,
amount: split.amount,
proportion: split.proportion,
personalAmount: split.personalAmount
});
});
await Promise.all(splitPromises);
// Calculate next execution date
const nextExecutionDate = calculateNextExecutionDate(recurringPayment, now);
// Update the recurring payment
await RecurringPayment.findByIdAndUpdate(recurringPayment._id, {
lastExecutionDate: now,
nextExecutionDate: nextExecutionDate
});
results.push({
recurringPaymentId: recurringPayment._id,
paymentId: payment._id,
title: recurringPayment.title,
amount: recurringPayment.amount,
nextExecution: nextExecutionDate,
success: true
});
} catch (paymentError) {
console.error(`Error executing recurring payment ${recurringPayment._id}:`, paymentError);
results.push({
recurringPaymentId: recurringPayment._id,
title: recurringPayment.title,
amount: recurringPayment.amount,
success: false,
error: paymentError instanceof Error ? paymentError.message : 'Unknown error'
});
}
}
return json({
success: true,
executed: results.filter(r => r.success).length,
failed: results.filter(r => !r.success).length,
results
});
} catch (e) {
console.error('Error executing recurring payments:', e);
throw error(500, 'Failed to execute recurring payments');
} finally {
await dbDisconnect();
}
};

View File

@@ -0,0 +1,57 @@
import type { RequestHandler } from '@sveltejs/kit';
import { error, json } from '@sveltejs/kit';
import { recurringPaymentScheduler } from '../../../../../lib/server/scheduler';
export const GET: RequestHandler = async ({ locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
try {
const status = recurringPaymentScheduler.getStatus();
return json({
success: true,
scheduler: status,
message: status.isScheduled ? 'Scheduler is running' : 'Scheduler is stopped'
});
} catch (e) {
console.error('Error getting scheduler status:', e);
throw error(500, 'Failed to get scheduler status');
}
};
export const POST: RequestHandler = async ({ request, locals }) => {
const auth = await locals.auth();
if (!auth || !auth.user?.nickname) {
throw error(401, 'Not logged in');
}
try {
const body = await request.json();
const { action } = body;
switch (action) {
case 'execute':
console.log(`[API] Manual execution requested by ${auth.user.nickname}`);
await recurringPaymentScheduler.executeNow();
return json({
success: true,
message: 'Manual execution completed'
});
case 'status':
const status = recurringPaymentScheduler.getStatus();
return json({
success: true,
scheduler: status
});
default:
throw error(400, 'Invalid action. Use "execute" or "status"');
}
} catch (e) {
console.error('Error in scheduler API:', e);
throw error(500, 'Scheduler operation failed');
}
};

View File

@@ -15,15 +15,6 @@
const statePaymentId = $page.state?.paymentId;
const isOnDashboard = $page.route.id === '/cospend';
console.log('Layout debug:', {
pathname: $page.url.pathname,
routeId: $page.route.id,
match: match,
statePaymentId: statePaymentId,
isOnDashboard: isOnDashboard,
showModal: showModal
});
// Only show modal if we're on the dashboard AND have a payment to show
if (isOnDashboard && (match || statePaymentId)) {
showModal = true;

View File

@@ -1,14 +1,38 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { redirect, error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals }) => {
export const load: PageServerLoad = async ({ locals, fetch }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
try {
// Fetch both balance and debt data server-side using existing APIs
const [balanceResponse, debtResponse] = await Promise.all([
fetch('/api/cospend/balance'),
fetch('/api/cospend/debts')
]);
if (!balanceResponse.ok) {
throw new Error('Failed to fetch balance');
}
if (!debtResponse.ok) {
throw new Error('Failed to fetch debt data');
}
const balance = await balanceResponse.json();
const debtData = await debtResponse.json();
return {
session
session,
balance,
debtData
};
} catch (e) {
console.error('Error loading dashboard data:', e);
throw error(500, 'Failed to load dashboard data');
}
};

View File

@@ -8,16 +8,20 @@
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
import { isSettlementPayment, getSettlementIcon, getSettlementClasses, getSettlementReceiver } from '$lib/utils/settlements';
export let data; // Used by the layout for session data
export let data; // Contains session data and balance from server
let balance = {
// Use server-side data, with fallback for progressive enhancement
let balance = data.balance || {
netBalance: 0,
recentSplits: []
};
let loading = true;
let loading = false; // Start as false since we have server data
let error = null;
// Progressive enhancement: refresh data if JavaScript is available
onMount(async () => {
// Mark that JavaScript is loaded for progressive enhancement
document.body.classList.add('js-loaded');
await fetchBalance();
});
@@ -54,10 +58,13 @@
}
function handlePaymentClick(paymentId, event) {
// Progressive enhancement: if JavaScript is available, use pushState for modal behavior
if (typeof pushState !== 'undefined') {
event.preventDefault();
// Use pushState for true shallow routing - only updates URL without navigation
pushState(`/cospend/payments/view/${paymentId}`, { paymentId });
}
// Otherwise, let the regular link navigation happen (no preventDefault)
}
function getSettlementReceiverFromSplit(split) {
if (!isSettlementPayment(split.paymentId)) {
@@ -91,11 +98,12 @@
<p>Track and split expenses with your friends and family</p>
</div>
<EnhancedBalance />
<EnhancedBalance initialBalance={data.balance} initialDebtData={data.debtData} />
<div class="actions">
<a href="/cospend/payments/add" class="btn btn-primary">Add Payment</a>
<a href="/cospend/payments" class="btn btn-secondary">View All Payments</a>
<a href="/cospend/recurring" class="btn btn-recurring">Recurring Payments</a>
{#if balance.netBalance !== 0}
<a href="/cospend/settle" class="btn btn-settlement">Settle Debts</a>
{/if}
@@ -274,6 +282,16 @@
background-color: #e8e8e8;
}
.btn-recurring {
background: linear-gradient(135deg, #9c27b0, #673ab7);
color: white;
border: none;
}
.btn-recurring:hover {
background: linear-gradient(135deg, #8e24aa, #5e35b1);
}
.btn-settlement {
background: linear-gradient(135deg, #28a745, #20c997);
color: white;

View File

@@ -1,14 +1,34 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { redirect, error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals }) => {
export const load: PageServerLoad = async ({ locals, fetch, url }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
try {
// Get pagination params from URL
const limit = parseInt(url.searchParams.get('limit') || '20');
const offset = parseInt(url.searchParams.get('offset') || '0');
// Fetch payments data server-side using existing API
const paymentsResponse = await fetch(`/api/cospend/payments?limit=${limit}&offset=${offset}`);
if (!paymentsResponse.ok) {
throw new Error('Failed to fetch payments');
}
const paymentsData = await paymentsResponse.json();
return {
session
session,
payments: paymentsData.payments,
hasMore: paymentsData.payments.length === limit,
currentOffset: offset,
limit
};
} catch (e) {
console.error('Error loading payments data:', e);
throw error(500, 'Failed to load payments data');
}
};

View File

@@ -7,15 +7,23 @@
export let data;
let payments = [];
let loading = true;
// Use server-side data with progressive enhancement
let payments = data.payments || [];
let loading = false; // Start as false since we have server data
let error = null;
let currentPage = 0;
let limit = 20;
let hasMore = true;
let currentPage = Math.floor(data.currentOffset / data.limit);
let limit = data.limit || 20;
let hasMore = data.hasMore || false;
// Progressive enhancement: only load if JavaScript is available
onMount(async () => {
// Mark that JavaScript is loaded for CSS
document.body.classList.add('js-loaded');
// Only refresh if we don't have server data
if (payments.length === 0) {
await loadPayments();
}
});
async function loadPayments(page = 0) {
@@ -136,7 +144,7 @@
{:else}
<div class="payments-grid">
{#each payments as payment}
<div class="payment-card" class:settlement-card={isSettlementPayment(payment)}>
<a href="/cospend/payments/view/{payment._id}" class="payment-card" class:settlement-card={isSettlementPayment(payment)}>
<div class="payment-header">
{#if isSettlementPayment(payment)}
<div class="settlement-flow">
@@ -234,17 +242,34 @@
</div>
{/if}
</div>
</div>
</a>
{/each}
</div>
{#if hasMore}
<div class="load-more">
<button class="btn btn-secondary" on:click={loadMore} disabled={loading}>
{loading ? 'Loading...' : 'Load More'}
</button>
</div>
<!-- Pagination that works without JavaScript -->
<div class="pagination">
{#if data.currentOffset > 0}
<a href="?offset={Math.max(0, data.currentOffset - data.limit)}&limit={data.limit}"
class="btn btn-secondary">
← Previous
</a>
{/if}
{#if hasMore}
<a href="?offset={data.currentOffset + data.limit}&limit={data.limit}"
class="btn btn-secondary">
Next →
</a>
{/if}
<!-- Progressive enhancement: JavaScript load more button -->
{#if hasMore}
<button class="btn btn-secondary js-only" on:click={loadMore} disabled={loading}
style="display: none;">
{loading ? 'Loading...' : 'Load More (JS)'}
</button>
{/if}
</div>
{/if}
</main>
@@ -350,15 +375,20 @@
}
.payment-card {
display: block;
background: white;
border-radius: 0.75rem;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: all 0.2s;
text-decoration: none;
color: inherit;
}
.payment-card:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
text-decoration: none;
color: inherit;
}
.settlement-card {
@@ -593,11 +623,22 @@
background-color: #c62828;
}
.load-more {
text-align: center;
.pagination {
display: flex;
justify-content: center;
gap: 1rem;
margin-top: 2rem;
}
/* Progressive enhancement: show JS features only when JS is loaded */
.js-only {
display: none;
}
:global(body.js-loaded) .js-only {
display: inline-block;
}
@media (max-width: 600px) {
.payments-list {
padding: 1rem;

View File

@@ -1,5 +1,6 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';
import { redirect, fail } from '@sveltejs/kit';
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
export const load: PageServerLoad = async ({ locals }) => {
const session = await locals.auth();
@@ -9,6 +10,165 @@ export const load: PageServerLoad = async ({ locals }) => {
}
return {
session
session,
predefinedUsers: isPredefinedUsersMode() ? PREDEFINED_USERS : [],
currentUser: session.user?.nickname || ''
};
};
export const actions: Actions = {
default: async ({ request, locals, fetch }) => {
const session = await locals.auth();
if (!session || !session.user?.nickname) {
throw redirect(302, '/login');
}
const formData = await request.formData();
const title = formData.get('title')?.toString().trim();
const description = formData.get('description')?.toString().trim() || '';
const amount = parseFloat(formData.get('amount')?.toString() || '0');
const paidBy = formData.get('paidBy')?.toString().trim();
const date = formData.get('date')?.toString();
const category = formData.get('category')?.toString() || 'groceries';
const splitMethod = formData.get('splitMethod')?.toString() || 'equal';
// Basic validation
if (!title || amount <= 0 || !paidBy) {
return fail(400, {
error: 'Please fill in all required fields with valid values',
values: Object.fromEntries(formData)
});
}
try {
// Get users from form - either predefined or manual
const users = [];
if (isPredefinedUsersMode()) {
users.push(...PREDEFINED_USERS);
} else {
// First check if we have JavaScript-managed users (hidden inputs)
const entries = Array.from(formData.entries());
const userEntries = entries.filter(([key]) => key.startsWith('user_'));
const jsUsers = userEntries.map(([, value]) => value.toString().trim()).filter(Boolean);
if (jsUsers.length > 0) {
users.push(...jsUsers);
} else {
// Fallback: parse manual textarea input (no-JS mode)
const usersManual = formData.get('users_manual')?.toString().trim() || '';
const manualUsers = usersManual.split('\n')
.map(user => user.trim())
.filter(Boolean);
users.push(...manualUsers);
}
}
if (users.length === 0) {
return fail(400, {
error: 'Please add at least one user to split with',
values: Object.fromEntries(formData)
});
}
// Calculate splits based on method
let splits = [];
if (splitMethod === 'equal') {
const splitAmount = amount / users.length;
const paidByAmount = splitAmount - amount; // Payer gets negative (they're owed back)
splits = users.map(user => ({
username: user,
amount: user === paidBy ? paidByAmount : splitAmount
}));
} else if (splitMethod === 'full') {
// Payer pays everything, others owe nothing
splits = users.map(user => ({
username: user,
amount: user === paidBy ? -amount : 0
}));
} else if (splitMethod === 'personal_equal') {
// Get personal amounts from form
const personalAmounts = {};
let totalPersonal = 0;
for (const user of users) {
const personalKey = `personal_${user}`;
const personalAmount = parseFloat(formData.get(personalKey)?.toString() || '0');
personalAmounts[user] = personalAmount;
totalPersonal += personalAmount;
}
if (totalPersonal > amount) {
return fail(400, {
error: 'Personal amounts cannot exceed the total payment amount',
values: Object.fromEntries(formData)
});
}
const remainingAmount = amount - totalPersonal;
const sharedPerPerson = remainingAmount / users.length;
splits = users.map(user => {
const personalAmount = personalAmounts[user] || 0;
const totalOwed = personalAmount + sharedPerPerson;
return {
username: user,
amount: user === paidBy ? totalOwed - amount : totalOwed,
personalAmount
};
});
} else {
// Default to equal split for unknown methods
const splitAmount = amount / users.length;
const paidByAmount = splitAmount - amount;
splits = users.map(user => ({
username: user,
amount: user === paidBy ? paidByAmount : splitAmount
}));
}
// Submit to API
const payload = {
title,
description,
amount,
paidBy,
date: date || new Date().toISOString().split('T')[0],
category,
splitMethod,
splits
};
const response = await fetch('/api/cospend/payments', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
return fail(400, {
error: errorData.message || 'Failed to create payment',
values: Object.fromEntries(formData)
});
}
// Success - redirect to payments list
throw redirect(303, '/cospend/payments');
} catch (error) {
if (error.status === 303) throw error; // Re-throw redirect
console.error('Error creating payment:', error);
return fail(500, {
error: 'Failed to create payment. Please try again.',
values: Object.fromEntries(formData)
});
}
}
};

View File

@@ -1,52 +1,98 @@
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { enhance } from '$app/forms';
import { getCategoryOptions } from '$lib/utils/categories';
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
export let data;
export let form;
// Initialize form data with server values if available (for error handling)
let formData = {
title: '',
description: '',
amount: '',
paidBy: data.session?.user?.nickname || '',
date: new Date().toISOString().split('T')[0],
category: 'groceries',
splitMethod: 'equal',
title: form?.values?.title || '',
description: form?.values?.description || '',
amount: form?.values?.amount || '',
paidBy: form?.values?.paidBy || data.currentUser || '',
date: form?.values?.date || new Date().toISOString().split('T')[0],
category: form?.values?.category || 'groceries',
splitMethod: form?.values?.splitMethod || 'equal',
splits: []
};
let imageFile = null;
let imagePreview = '';
let users = [];
let newUser = '';
let splitAmounts = {};
let personalAmounts = {};
let loading = false;
let error = null;
let error = form?.error || null;
let personalTotalError = false;
let predefinedMode = isPredefinedUsersMode();
let predefinedMode = data.predefinedUsers.length > 0;
let jsEnhanced = false;
// Initialize users from server data for no-JS support
let users = predefinedMode ? [...data.predefinedUsers] : (data.currentUser ? [data.currentUser] : []);
// Initialize split amounts for server-side users
users.forEach(user => {
splitAmounts[user] = 0;
personalAmounts[user] = 0;
});
$: categoryOptions = getCategoryOptions();
// Reactive text for "Paid in Full" option
$: paidInFullText = (() => {
// No-JS fallback text - always generic
if (!jsEnhanced) {
if (predefinedMode) {
return users.length === 2 ? 'Paid in Full for other' : 'Paid in Full for others';
} else {
return 'Paid in Full for others';
}
}
// JavaScript-enhanced reactive text
if (!formData.paidBy) {
return 'Paid in Full';
}
// Special handling for 2-user predefined setup
if (predefinedMode && users.length === 2) {
const otherUser = users.find(user => user !== formData.paidBy);
// Always show "for" the other user (who benefits) regardless of who pays
return otherUser ? `Paid in Full for ${otherUser}` : 'Paid in Full';
}
// General case with JS
if (formData.paidBy === data.currentUser) {
return 'Paid in Full by You';
} else {
return `Paid in Full by ${formData.paidBy}`;
}
})();
onMount(() => {
jsEnhanced = true;
document.body.classList.add('js-loaded');
if (predefinedMode) {
// Use predefined users and always split between them
users = [...PREDEFINED_USERS];
users = [...data.predefinedUsers];
users.forEach(user => addSplitForUser(user));
// Default to current user as payer if they're in the predefined list
if (data.session?.user?.nickname && PREDEFINED_USERS.includes(data.session.user.nickname)) {
formData.paidBy = data.session.user.nickname;
if (data.currentUser && data.predefinedUsers.includes(data.currentUser)) {
formData.paidBy = data.currentUser;
} else {
formData.paidBy = PREDEFINED_USERS[0];
formData.paidBy = data.predefinedUsers[0];
}
} else {
// Original behavior for manual user management
if (data.session?.user?.nickname) {
users = [data.session.user.nickname];
addSplitForUser(data.session.user.nickname);
if (data.currentUser) {
users = [data.currentUser];
addSplitForUser(data.currentUser);
}
}
});
@@ -173,6 +219,14 @@
calculateFullPayment();
} else if (formData.splitMethod === 'personal_equal') {
calculatePersonalEqualSplit();
} else if (formData.splitMethod === 'proportional') {
// For proportional, user enters amounts manually - just ensure all users have entries
users.forEach(user => {
if (!(user in splitAmounts)) {
splitAmounts[user] = 0;
}
});
splitAmounts = { ...splitAmounts };
}
}
@@ -294,7 +348,7 @@
<a href="/cospend" class="back-link">← Back to Cospend</a>
</div>
<form on:submit|preventDefault={handleSubmit} class="payment-form">
<form method="POST" use:enhance class="payment-form">
<div class="form-section">
<h2>Payment Details</h2>
@@ -303,7 +357,8 @@
<input
type="text"
id="title"
bind:value={formData.title}
name="title"
value={formData.title}
required
placeholder="e.g., Dinner at restaurant"
/>
@@ -313,7 +368,8 @@
<label for="description">Description</label>
<textarea
id="description"
bind:value={formData.description}
name="description"
value={formData.description}
placeholder="Additional details..."
rows="3"
></textarea>
@@ -321,7 +377,7 @@
<div class="form-group">
<label for="category">Category *</label>
<select id="category" bind:value={formData.category} required>
<select id="category" name="category" value={formData.category} required>
{#each categoryOptions as option}
<option value={option.value}>{option.label}</option>
{/each}
@@ -334,6 +390,7 @@
<input
type="number"
id="amount"
name="amount"
bind:value={formData.amount}
required
min="0"
@@ -347,7 +404,8 @@
<input
type="date"
id="date"
bind:value={formData.date}
name="date"
value={formData.date}
required
/>
</div>
@@ -355,7 +413,7 @@
<div class="form-group">
<label for="paidBy">Paid by</label>
<select id="paidBy" bind:value={formData.paidBy} required>
<select id="paidBy" name="paidBy" bind:value={formData.paidBy} required>
{#each users as user}
<option value={user}>{user}</option>
{/each}
@@ -430,7 +488,7 @@
{/each}
</div>
<div class="add-user">
<div class="add-user js-enhanced" style="display: none;">
<input
type="text"
bind:value={newUser}
@@ -439,6 +497,27 @@
/>
<button type="button" on:click={addUser}>Add User</button>
</div>
<!-- Server-side fallback: simple text inputs for users -->
<div class="manual-users no-js-only">
<p>Enter users to split with (one per line):</p>
<textarea
name="users_manual"
placeholder="{data.currentUser}&#10;Enter additional users..."
rows="4"
>{data.currentUser}</textarea>
</div>
{/if}
<!-- Hidden inputs for JavaScript-managed users -->
{#if predefinedMode}
{#each data.predefinedUsers as user, i}
<input type="hidden" name="user_{i}" value={user} />
{/each}
{:else}
{#each users as user, i}
<input type="hidden" name="user_{i}" value={user} />
{/each}
{/if}
</div>
@@ -447,19 +526,19 @@
<div class="split-method">
<label>
<input type="radio" bind:group={formData.splitMethod} value="equal" />
<input type="radio" name="splitMethod" value="equal" bind:group={formData.splitMethod} />
{predefinedMode && users.length === 2 ? 'Split 50/50' : 'Equal Split'}
</label>
<label>
<input type="radio" bind:group={formData.splitMethod} value="personal_equal" />
<input type="radio" name="splitMethod" value="personal_equal" bind:group={formData.splitMethod} />
Personal + Equal Split
</label>
<label>
<input type="radio" bind:group={formData.splitMethod} value="full" />
Paid in Full by {formData.paidBy}
<input type="radio" name="splitMethod" value="full" bind:group={formData.splitMethod} />
{paidInFullText}
</label>
<label>
<input type="radio" bind:group={formData.splitMethod} value="proportional" />
<input type="radio" name="splitMethod" value="proportional" bind:group={formData.splitMethod} />
Custom Proportions
</label>
</div>
@@ -473,6 +552,7 @@
<input
type="number"
step="0.01"
name="split_{user}"
bind:value={splitAmounts[user]}
placeholder="0.00"
/>
@@ -492,6 +572,7 @@
type="number"
step="0.01"
min="0"
name="personal_{user}"
bind:value={personalAmounts[user]}
placeholder="0.00"
/>
@@ -538,9 +619,9 @@
{/if}
<div class="form-actions">
<button type="button" class="btn-secondary" on:click={() => goto('/cospend')}>
<a href="/cospend" class="btn-secondary">
Cancel
</button>
</a>
<button type="submit" class="btn-primary" disabled={loading}>
{loading ? 'Creating...' : 'Create Payment'}
</button>
@@ -913,6 +994,39 @@
font-size: 0.9rem;
}
/* Progressive enhancement styles */
.no-js-only {
display: block;
}
.js-enhanced {
display: none;
}
:global(body.js-loaded) .no-js-only {
display: none;
}
:global(body.js-loaded) .js-enhanced {
display: block;
}
.manual-users textarea {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 0.5rem;
font-family: inherit;
font-size: 0.9rem;
resize: vertical;
}
.manual-users p {
margin: 0 0 0.5rem 0;
font-size: 0.9rem;
color: #666;
}
@media (max-width: 600px) {
.add-payment {
padding: 1rem;

View File

@@ -1,15 +1,28 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { redirect, error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals, params }) => {
export const load: PageServerLoad = async ({ locals, params, fetch }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
try {
// Fetch payment data server-side using existing API
const paymentResponse = await fetch(`/api/cospend/payments/${params.id}`);
if (!paymentResponse.ok) {
throw new Error('Failed to fetch payment');
}
const paymentData = await paymentResponse.json();
return {
session,
paymentId: params.id
paymentId: params.id,
payment: paymentData.payment
};
} catch (e) {
console.error('Error loading payment data:', e);
throw error(500, 'Failed to load payment data');
}
};

View File

@@ -6,16 +6,25 @@
export let data;
let payment = null;
let loading = true;
// Use server-side data with progressive enhancement
let payment = data.payment || null;
let loading = false; // Start as false since we have server data
let error = null;
// Progressive enhancement: refresh data if JavaScript is available
onMount(async () => {
// Mark that JavaScript is loaded
document.body.classList.add('js-loaded');
// Only refresh if we don't have server data
if (!payment) {
await loadPayment();
}
});
async function loadPayment() {
try {
loading = true;
const response = await fetch(`/api/cospend/payments/${data.paymentId}`);
if (!response.ok) {
throw new Error('Failed to load payment');

View File

@@ -0,0 +1,14 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
return {
session
};
};

View File

@@ -0,0 +1,582 @@
<script>
import { onMount } from 'svelte';
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
import { getFrequencyDescription, formatNextExecution } from '$lib/utils/recurring';
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
export let data;
let recurringPayments = [];
let loading = true;
let error = null;
let showActiveOnly = true;
onMount(async () => {
await fetchRecurringPayments();
});
async function fetchRecurringPayments() {
try {
loading = true;
const activeParam = showActiveOnly ? '?active=true' : '';
const response = await fetch(`/api/cospend/recurring-payments${activeParam}`);
if (!response.ok) {
throw new Error('Failed to fetch recurring payments');
}
const result = await response.json();
recurringPayments = result.recurringPayments;
} catch (err) {
error = err.message;
} finally {
loading = false;
}
}
async function toggleActiveStatus(paymentId, currentStatus) {
try {
const response = await fetch(`/api/cospend/recurring-payments/${paymentId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ isActive: !currentStatus })
});
if (!response.ok) {
throw new Error('Failed to update payment status');
}
// Refresh the list
await fetchRecurringPayments();
} catch (err) {
alert(`Error: ${err.message}`);
}
}
async function deleteRecurringPayment(paymentId, title) {
if (!confirm(`Are you sure you want to delete the recurring payment "${title}"?`)) {
return;
}
try {
const response = await fetch(`/api/cospend/recurring-payments/${paymentId}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Failed to delete payment');
}
// Refresh the list
await fetchRecurringPayments();
} catch (err) {
alert(`Error: ${err.message}`);
}
}
function formatCurrency(amount) {
return new Intl.NumberFormat('de-CH', {
style: 'currency',
currency: 'CHF'
}).format(Math.abs(amount));
}
function formatDate(dateString) {
return new Date(dateString).toLocaleDateString('de-CH');
}
$: if (showActiveOnly !== undefined) {
fetchRecurringPayments();
}
</script>
<svelte:head>
<title>Recurring Payments - Cospend</title>
</svelte:head>
<main class="recurring-payments">
<div class="header">
<h1>Recurring Payments</h1>
<div class="header-actions">
<a href="/cospend/recurring/add" class="btn btn-primary">Add Recurring Payment</a>
<a href="/cospend" class="back-link">← Back to Cospend</a>
</div>
</div>
<div class="filters">
<label>
<input type="checkbox" bind:checked={showActiveOnly} />
Show active only
</label>
</div>
{#if loading}
<div class="loading">Loading recurring payments...</div>
{:else if error}
<div class="error">Error: {error}</div>
{:else if recurringPayments.length === 0}
<div class="empty-state">
<h2>No recurring payments found</h2>
<p>Create your first recurring payment to automate regular expenses like rent, utilities, or subscriptions.</p>
<a href="/cospend/recurring/add" class="btn btn-primary">Add Your First Recurring Payment</a>
</div>
{:else}
<div class="payments-grid">
{#each recurringPayments as payment}
<div class="payment-card" class:inactive={!payment.isActive}>
<div class="card-header">
<div class="payment-title">
<span class="category-emoji">{getCategoryEmoji(payment.category)}</span>
<h3>{payment.title}</h3>
<span class="status-badge" class:active={payment.isActive} class:inactive={!payment.isActive}>
{payment.isActive ? 'Active' : 'Inactive'}
</span>
</div>
<div class="payment-amount">
{formatCurrency(payment.amount)}
</div>
</div>
{#if payment.description}
<p class="payment-description">{payment.description}</p>
{/if}
<div class="payment-details">
<div class="detail-row">
<span class="label">Category:</span>
<span class="value">{getCategoryName(payment.category)}</span>
</div>
<div class="detail-row">
<span class="label">Frequency:</span>
<span class="value">{getFrequencyDescription(payment)}</span>
</div>
<div class="detail-row">
<span class="label">Paid by:</span>
<div class="payer-info">
<ProfilePicture username={payment.paidBy} size={20} />
<span class="value">{payment.paidBy}</span>
</div>
</div>
<div class="detail-row">
<span class="label">Next execution:</span>
<span class="value next-execution">
{formatNextExecution(new Date(payment.nextExecutionDate))}
</span>
</div>
{#if payment.lastExecutionDate}
<div class="detail-row">
<span class="label">Last executed:</span>
<span class="value">{formatDate(payment.lastExecutionDate)}</span>
</div>
{/if}
{#if payment.endDate}
<div class="detail-row">
<span class="label">Ends:</span>
<span class="value">{formatDate(payment.endDate)}</span>
</div>
{/if}
</div>
<div class="splits-preview">
<h4>Split between:</h4>
<div class="splits-list">
{#each payment.splits as split}
<div class="split-item">
<ProfilePicture username={split.username} size={24} />
<span class="username">{split.username}</span>
<span class="split-amount" class:positive={split.amount < 0} class:negative={split.amount > 0}>
{#if split.amount > 0}
owes {formatCurrency(split.amount)}
{:else if split.amount < 0}
gets {formatCurrency(split.amount)}
{:else}
even
{/if}
</span>
</div>
{/each}
</div>
</div>
<div class="card-actions">
<a href="/cospend/recurring/edit/{payment._id}" class="btn btn-secondary btn-small">
Edit
</a>
<button
class="btn btn-small"
class:btn-warning={payment.isActive}
class:btn-success={!payment.isActive}
on:click={() => toggleActiveStatus(payment._id, payment.isActive)}
>
{payment.isActive ? 'Pause' : 'Activate'}
</button>
<button
class="btn btn-danger btn-small"
on:click={() => deleteRecurringPayment(payment._id, payment.title)}
>
Delete
</button>
</div>
</div>
{/each}
</div>
{/if}
</main>
<style>
.recurring-payments {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.header h1 {
margin: 0;
color: #333;
}
.header-actions {
display: flex;
align-items: center;
gap: 1rem;
}
.back-link {
color: #1976d2;
text-decoration: none;
}
.filters {
margin-bottom: 1.5rem;
padding: 1rem;
background: white;
border-radius: 0.5rem;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.filters label {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
font-weight: 500;
}
.loading, .error {
text-align: center;
padding: 2rem;
font-size: 1.1rem;
}
.error {
color: #d32f2f;
background-color: #ffebee;
border-radius: 0.5rem;
}
.empty-state {
text-align: center;
padding: 4rem 2rem;
background: white;
border-radius: 0.75rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.empty-state h2 {
margin-bottom: 1rem;
color: #333;
}
.empty-state p {
color: #666;
margin-bottom: 2rem;
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
.payments-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
gap: 1.5rem;
}
.payment-card {
background: white;
border-radius: 0.75rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
padding: 1.5rem;
transition: transform 0.2s;
}
.payment-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}
.payment-card.inactive {
opacity: 0.7;
background: #f8f9fa;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 1rem;
}
.payment-title {
display: flex;
align-items: center;
gap: 0.75rem;
flex: 1;
}
.category-emoji {
font-size: 1.5rem;
}
.payment-title h3 {
margin: 0;
color: #333;
font-size: 1.25rem;
}
.status-badge {
padding: 0.25rem 0.75rem;
border-radius: 1rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-badge.active {
background-color: #e8f5e8;
color: #2e7d32;
}
.status-badge.inactive {
background-color: #fff3e0;
color: #f57c00;
}
.payment-amount {
font-size: 1.5rem;
font-weight: 700;
color: #1976d2;
}
.payment-description {
color: #666;
margin-bottom: 1rem;
font-style: italic;
}
.payment-details {
margin-bottom: 1.5rem;
}
.detail-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
padding: 0.25rem 0;
}
.label {
font-weight: 500;
color: #666;
font-size: 0.9rem;
}
.value {
color: #333;
font-weight: 500;
}
.next-execution {
color: #1976d2;
font-weight: 600;
}
.payer-info {
display: flex;
align-items: center;
gap: 0.5rem;
}
.splits-preview {
margin-bottom: 1.5rem;
padding: 1rem;
background-color: #f8f9fa;
border-radius: 0.5rem;
}
.splits-preview h4 {
margin: 0 0 0.75rem 0;
font-size: 0.9rem;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.splits-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.split-item {
display: flex;
align-items: center;
gap: 0.5rem;
}
.split-item .username {
flex: 1;
font-weight: 500;
}
.split-amount {
font-size: 0.9rem;
font-weight: 500;
}
.split-amount.positive {
color: #2e7d32;
}
.split-amount.negative {
color: #d32f2f;
}
.card-actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.btn {
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
text-decoration: none;
font-weight: 500;
border: none;
cursor: pointer;
transition: all 0.2s;
text-align: center;
}
.btn-small {
padding: 0.5rem 1rem;
font-size: 0.875rem;
}
.btn-primary {
background-color: #1976d2;
color: white;
}
.btn-primary:hover {
background-color: #1565c0;
}
.btn-secondary {
background-color: #f5f5f5;
color: #333;
border: 1px solid #ddd;
}
.btn-secondary:hover {
background-color: #e8e8e8;
}
.btn-warning {
background-color: #ff9800;
color: white;
}
.btn-warning:hover {
background-color: #f57c00;
}
.btn-success {
background-color: #4caf50;
color: white;
}
.btn-success:hover {
background-color: #45a049;
}
.btn-danger {
background-color: #f44336;
color: white;
}
.btn-danger:hover {
background-color: #d32f2f;
}
@media (max-width: 768px) {
.recurring-payments {
padding: 1rem;
}
.header {
flex-direction: column;
gap: 1rem;
align-items: stretch;
}
.header-actions {
justify-content: space-between;
}
.payments-grid {
grid-template-columns: 1fr;
}
.payment-card {
padding: 1rem;
}
.card-header {
flex-direction: column;
gap: 1rem;
}
.payment-title {
justify-content: space-between;
}
.detail-row {
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
}
.card-actions {
justify-content: stretch;
}
.card-actions .btn {
flex: 1;
}
}
</style>

View File

@@ -0,0 +1,14 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
return {
session
};
};

View File

@@ -0,0 +1,942 @@
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { getCategoryOptions } from '$lib/utils/categories';
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
import { validateCronExpression, getFrequencyDescription, calculateNextExecutionDate } from '$lib/utils/recurring';
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
export let data;
let formData = {
title: '',
description: '',
amount: '',
paidBy: data.session?.user?.nickname || '',
category: 'groceries',
splitMethod: 'equal',
splits: [],
frequency: 'monthly',
cronExpression: '',
startDate: new Date().toISOString().split('T')[0],
endDate: ''
};
let users = [];
let newUser = '';
let splitAmounts = {};
let personalAmounts = {};
let loading = false;
let error = null;
let personalTotalError = false;
let predefinedMode = isPredefinedUsersMode();
let cronError = false;
let nextExecutionPreview = '';
$: categoryOptions = getCategoryOptions();
onMount(() => {
if (predefinedMode) {
users = [...PREDEFINED_USERS];
users.forEach(user => addSplitForUser(user));
if (data.session?.user?.nickname && PREDEFINED_USERS.includes(data.session.user.nickname)) {
formData.paidBy = data.session.user.nickname;
} else {
formData.paidBy = PREDEFINED_USERS[0];
}
} else {
if (data.session?.user?.nickname) {
users = [data.session.user.nickname];
addSplitForUser(data.session.user.nickname);
}
}
updateNextExecutionPreview();
});
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 && userToRemove !== data.session.user.nickname) {
users = users.filter(u => u !== userToRemove);
delete splitAmounts[userToRemove];
splitAmounts = { ...splitAmounts };
}
}
function addSplitForUser(username) {
if (!splitAmounts[username]) {
splitAmounts[username] = 0;
splitAmounts = { ...splitAmounts };
}
}
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);
users.forEach(user => {
if (user === formData.paidBy) {
splitAmounts[user] = -amountNum;
} else {
splitAmounts[user] = 0;
}
});
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() {
if (formData.frequency !== 'custom') {
cronError = false;
return;
}
cronError = !validateCronExpression(formData.cronExpression);
}
function updateNextExecutionPreview() {
try {
if (formData.frequency && formData.startDate) {
const recurringPayment = {
...formData,
startDate: new Date(formData.startDate)
};
const nextDate = calculateNextExecutionDate(recurringPayment, new Date(formData.startDate));
nextExecutionPreview = nextDate.toLocaleString('de-CH', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
} catch (e) {
nextExecutionPreview = 'Invalid configuration';
}
}
async function handleSubmit() {
if (!formData.title.trim() || !formData.amount || parseFloat(formData.amount) <= 0) {
error = 'Please fill in all required fields with valid values';
return;
}
if (formData.frequency === 'custom' && cronError) {
error = 'Please enter a valid cron expression';
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) {
error = 'Please add at least one user to split with';
return;
}
loading = true;
error = null;
try {
const splits = users.map(user => ({
username: user,
amount: splitAmounts[user] || 0,
proportion: formData.splitMethod === 'proportional' ? (splitAmounts[user] || 0) / parseFloat(formData.amount) : undefined,
personalAmount: formData.splitMethod === 'personal_equal' ? (parseFloat(personalAmounts[user]) || 0) : undefined
}));
const payload = {
...formData,
amount: parseFloat(formData.amount),
startDate: formData.startDate ? new Date(formData.startDate).toISOString() : new Date().toISOString(),
endDate: formData.endDate ? new Date(formData.endDate).toISOString() : null,
cronExpression: formData.frequency === 'custom' ? formData.cronExpression : undefined,
splits
};
const response = await fetch('/api/cospend/recurring-payments', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || 'Failed to create recurring payment');
}
const result = await response.json();
await goto('/cospend/recurring');
} catch (err) {
error = err.message;
} finally {
loading = false;
}
}
$: if (formData.amount && formData.splitMethod && formData.paidBy) {
handleSplitMethodChange();
}
$: if (formData.splitMethod === 'personal_equal' && personalAmounts && formData.amount) {
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) {
validateCron();
}
$: if (formData.frequency || formData.cronExpression || formData.startDate) {
updateNextExecutionPreview();
}
</script>
<svelte:head>
<title>Add Recurring Payment - Cospend</title>
</svelte:head>
<main class="add-recurring-payment">
<div class="header">
<h1>Add Recurring Payment</h1>
<a href="/cospend" class="back-link">← Back to Cospend</a>
</div>
<form on:submit|preventDefault={handleSubmit} class="payment-form">
<div class="form-section">
<h2>Payment Details</h2>
<div class="form-group">
<label for="title">Title *</label>
<input
type="text"
id="title"
bind:value={formData.title}
required
placeholder="e.g., Monthly rent, Weekly groceries"
/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea
id="description"
bind:value={formData.description}
placeholder="Additional details about this recurring payment..."
rows="3"
></textarea>
</div>
<div class="form-group">
<label for="category">Category *</label>
<select id="category" bind:value={formData.category} required>
{#each categoryOptions as option}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</div>
<div class="form-row">
<div class="form-group">
<label for="amount">Amount (CHF) *</label>
<input
type="number"
id="amount"
bind:value={formData.amount}
required
min="0"
step="0.01"
placeholder="0.00"
/>
</div>
<div class="form-group">
<label for="paidBy">Paid by</label>
<select id="paidBy" bind:value={formData.paidBy} required>
{#each users as user}
<option value={user}>{user}</option>
{/each}
</select>
</div>
</div>
</div>
<div class="form-section">
<h2>Recurring Schedule</h2>
<div class="form-row">
<div class="form-group">
<label for="frequency">Frequency *</label>
<select id="frequency" bind:value={formData.frequency} required>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
<option value="custom">Custom (Cron)</option>
</select>
</div>
<div class="form-group">
<label for="startDate">Start Date *</label>
<input
type="date"
id="startDate"
bind:value={formData.startDate}
required
/>
</div>
</div>
{#if formData.frequency === 'custom'}
<div class="form-group">
<label for="cronExpression">Cron Expression *</label>
<input
type="text"
id="cronExpression"
bind:value={formData.cronExpression}
required
placeholder="0 9 * * 1 (Every Monday at 9:00 AM)"
class:error={cronError}
/>
<div class="help-text">
<p>Cron format: minute hour day-of-month month day-of-week</p>
<p>Examples:</p>
<ul>
<li><code>0 9 * * *</code> - Every day at 9:00 AM</li>
<li><code>0 9 1 * *</code> - Every 1st of the month at 9:00 AM</li>
<li><code>0 9 * * 1</code> - Every Monday at 9:00 AM</li>
<li><code>0 9 1,15 * *</code> - 1st and 15th of every month at 9:00 AM</li>
</ul>
</div>
{#if cronError}
<div class="field-error">Invalid cron expression</div>
{/if}
</div>
{/if}
<div class="form-group">
<label for="endDate">End Date (optional)</label>
<input
type="date"
id="endDate"
bind:value={formData.endDate}
/>
<div class="help-text">Leave blank for indefinite recurring payments</div>
</div>
{#if nextExecutionPreview}
<div class="execution-preview">
<h3>Next Execution</h3>
<p class="next-execution">{nextExecutionPreview}</p>
<p class="frequency-description">{getFrequencyDescription(formData)}</p>
</div>
{/if}
</div>
<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 === data.session?.user?.nickname}
<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 !== data.session.user.nickname}
<button type="button" class="remove-user" on:click={() => removeUser(user)}>
Remove
</button>
{/if}
</div>
{/each}
</div>
<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">
<h2>Split Method</h2>
<div class="split-method">
<label>
<input type="radio" bind:group={formData.splitMethod} value="equal" />
{predefinedMode && users.length === 2 ? 'Split 50/50' : 'Equal Split'}
</label>
<label>
<input type="radio" bind:group={formData.splitMethod} value="personal_equal" />
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}
even
{/if}
</span>
</div>
{/each}
</div>
{/if}
</div>
{#if error}
<div class="error">{error}</div>
{/if}
<div class="form-actions">
<button type="button" class="btn-secondary" on:click={() => goto('/cospend')}>
Cancel
</button>
<button type="submit" class="btn-primary" disabled={loading || cronError}>
{loading ? 'Creating...' : 'Create Recurring Payment'}
</button>
</div>
</form>
</main>
<style>
.add-recurring-payment {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.header h1 {
margin: 0;
color: #333;
}
.back-link {
color: #1976d2;
text-decoration: none;
}
.payment-form {
display: flex;
flex-direction: column;
gap: 2rem;
}
.form-section {
background: white;
padding: 1.5rem;
border-radius: 0.75rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.form-section h2 {
margin-top: 0;
margin-bottom: 1rem;
color: #333;
font-size: 1.25rem;
}
.form-group {
margin-bottom: 1rem;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: #555;
}
input, textarea, select {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 0.5rem;
font-size: 1rem;
box-sizing: border-box;
}
input:focus, textarea:focus, select:focus {
outline: none;
border-color: #1976d2;
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}
input.error {
border-color: #d32f2f;
}
.help-text {
margin-top: 0.5rem;
color: #666;
font-size: 0.9rem;
}
.help-text code {
background-color: #f5f5f5;
padding: 0.125rem 0.25rem;
border-radius: 0.25rem;
font-family: monospace;
}
.help-text ul {
margin: 0.5rem 0;
padding-left: 1rem;
}
.help-text li {
margin-bottom: 0.25rem;
}
.field-error {
color: #d32f2f;
font-size: 0.875rem;
margin-top: 0.25rem;
}
.execution-preview {
background-color: #e3f2fd;
border: 1px solid #2196f3;
border-radius: 0.5rem;
padding: 1rem;
margin-top: 1rem;
}
.execution-preview h3 {
margin: 0 0 0.5rem 0;
color: #1976d2;
font-size: 1rem;
}
.next-execution {
font-size: 1.1rem;
font-weight: 600;
color: #1976d2;
margin: 0.5rem 0;
}
.frequency-description {
color: #666;
font-size: 0.9rem;
margin: 0;
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;
}
.predefined-users {
background-color: #f8f9fa;
padding: 1rem;
border-radius: 0.5rem;
border: 1px solid #e9ecef;
}
.predefined-note {
margin: 0 0 1rem 0;
color: #666;
font-size: 0.9rem;
font-style: italic;
}
.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 {
background-color: #ffebee;
color: #d32f2f;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.form-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
}
.btn-primary, .btn-secondary {
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
font-size: 1rem;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background-color: #1976d2;
color: white;
border: none;
}
.btn-primary:hover:not(:disabled) {
background-color: #1565c0;
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary {
background-color: #f5f5f5;
color: #333;
border: 1px solid #ddd;
}
.btn-secondary:hover {
background-color: #e8e8e8;
}
@media (max-width: 600px) {
.add-recurring-payment {
padding: 1rem;
}
.form-row {
grid-template-columns: 1fr;
}
.form-actions {
flex-direction: column;
}
}
</style>

View File

@@ -0,0 +1,15 @@
import type { PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ locals, params }) => {
const session = await locals.auth();
if (!session) {
throw redirect(302, '/login');
}
return {
session,
recurringPaymentId: params.id
};
};

View File

@@ -0,0 +1,973 @@
<script>
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { getCategoryOptions } from '$lib/utils/categories';
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
import { validateCronExpression, getFrequencyDescription, calculateNextExecutionDate } from '$lib/utils/recurring';
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
export let data;
let formData = {
title: '',
description: '',
amount: '',
paidBy: data.session?.user?.nickname || '',
category: 'groceries',
splitMethod: 'equal',
splits: [],
frequency: 'monthly',
cronExpression: '',
startDate: '',
endDate: '',
isActive: true
};
let users = [];
let newUser = '';
let splitAmounts = {};
let personalAmounts = {};
let loading = false;
let loadingPayment = true;
let error = null;
let personalTotalError = false;
let predefinedMode = isPredefinedUsersMode();
let cronError = false;
let nextExecutionPreview = '';
$: categoryOptions = getCategoryOptions();
onMount(async () => {
await loadRecurringPayment();
});
async function loadRecurringPayment() {
try {
loadingPayment = true;
const response = await fetch(`/api/cospend/recurring-payments/${data.recurringPaymentId}`);
if (!response.ok) {
throw new Error('Failed to load recurring payment');
}
const result = await response.json();
const payment = result.recurringPayment;
// Populate form data
formData = {
title: payment.title,
description: payment.description || '',
amount: payment.amount.toString(),
paidBy: payment.paidBy,
category: payment.category,
splitMethod: payment.splitMethod,
frequency: payment.frequency,
cronExpression: payment.cronExpression || '',
startDate: new Date(payment.startDate).toISOString().split('T')[0],
endDate: payment.endDate ? new Date(payment.endDate).toISOString().split('T')[0] : '',
isActive: payment.isActive
};
// Set up users and splits
users = payment.splits.map(split => split.username);
users.forEach(user => {
const split = payment.splits.find(s => s.username === user);
splitAmounts[user] = split.amount;
if (split.personalAmount !== undefined) {
personalAmounts[user] = split.personalAmount;
}
});
updateNextExecutionPreview();
} catch (err) {
error = err.message;
} finally {
loadingPayment = false;
}
}
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) {
if (!splitAmounts[username]) {
splitAmounts[username] = 0;
splitAmounts = { ...splitAmounts };
}
}
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);
users.forEach(user => {
if (user === formData.paidBy) {
splitAmounts[user] = -amountNum;
} else {
splitAmounts[user] = 0;
}
});
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() {
if (formData.frequency !== 'custom') {
cronError = false;
return;
}
cronError = !validateCronExpression(formData.cronExpression);
}
function updateNextExecutionPreview() {
try {
if (formData.frequency && formData.startDate) {
const recurringPayment = {
...formData,
startDate: new Date(formData.startDate)
};
const nextDate = calculateNextExecutionDate(recurringPayment, new Date(formData.startDate));
nextExecutionPreview = nextDate.toLocaleString('de-CH', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
}
} catch (e) {
nextExecutionPreview = 'Invalid configuration';
}
}
async function handleSubmit() {
if (!formData.title.trim() || !formData.amount || parseFloat(formData.amount) <= 0) {
error = 'Please fill in all required fields with valid values';
return;
}
if (formData.frequency === 'custom' && cronError) {
error = 'Please enter a valid cron expression';
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) {
error = 'Please add at least one user to split with';
return;
}
loading = true;
error = null;
try {
const splits = users.map(user => ({
username: user,
amount: splitAmounts[user] || 0,
proportion: formData.splitMethod === 'proportional' ? (splitAmounts[user] || 0) / parseFloat(formData.amount) : undefined,
personalAmount: formData.splitMethod === 'personal_equal' ? (parseFloat(personalAmounts[user]) || 0) : undefined
}));
const payload = {
...formData,
amount: parseFloat(formData.amount),
startDate: formData.startDate ? new Date(formData.startDate).toISOString() : new Date().toISOString(),
endDate: formData.endDate ? new Date(formData.endDate).toISOString() : null,
cronExpression: formData.frequency === 'custom' ? formData.cronExpression : undefined,
splits
};
const response = await fetch(`/api/cospend/recurring-payments/${data.recurringPaymentId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || 'Failed to update recurring payment');
}
const result = await response.json();
await goto('/cospend/recurring');
} catch (err) {
error = err.message;
} finally {
loading = false;
}
}
$: 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) {
validateCron();
}
$: if (formData.frequency || formData.cronExpression || formData.startDate) {
updateNextExecutionPreview();
}
</script>
<svelte:head>
<title>Edit Recurring Payment - Cospend</title>
</svelte:head>
<main class="edit-recurring-payment">
<div class="header">
<h1>Edit Recurring Payment</h1>
<div class="header-actions">
<a href="/cospend/recurring" class="back-link">← Back to Recurring Payments</a>
</div>
</div>
{#if loadingPayment}
<div class="loading">Loading recurring payment...</div>
{:else if error && !formData.title}
<div class="error">Error: {error}</div>
{:else}
<form on:submit|preventDefault={handleSubmit} class="payment-form">
<div class="form-section">
<h2>Payment Details</h2>
<div class="form-group">
<label for="title">Title *</label>
<input
type="text"
id="title"
bind:value={formData.title}
required
placeholder="e.g., Monthly rent, Weekly groceries"
/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea
id="description"
bind:value={formData.description}
placeholder="Additional details about this recurring payment..."
rows="3"
></textarea>
</div>
<div class="form-group">
<label for="category">Category *</label>
<select id="category" bind:value={formData.category} required>
{#each categoryOptions as option}
<option value={option.value}>{option.label}</option>
{/each}
</select>
</div>
<div class="form-row">
<div class="form-group">
<label for="amount">Amount (CHF) *</label>
<input
type="number"
id="amount"
bind:value={formData.amount}
required
min="0"
step="0.01"
placeholder="0.00"
/>
</div>
<div class="form-group">
<label for="paidBy">Paid by</label>
<select id="paidBy" bind:value={formData.paidBy} required>
{#each users as user}
<option value={user}>{user}</option>
{/each}
</select>
</div>
</div>
<div class="form-group">
<label for="isActive">Status</label>
<select id="isActive" bind:value={formData.isActive}>
<option value={true}>Active</option>
<option value={false}>Inactive</option>
</select>
</div>
</div>
<div class="form-section">
<h2>Recurring Schedule</h2>
<div class="form-row">
<div class="form-group">
<label for="frequency">Frequency *</label>
<select id="frequency" bind:value={formData.frequency} required>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
<option value="custom">Custom (Cron)</option>
</select>
</div>
<div class="form-group">
<label for="startDate">Start Date *</label>
<input
type="date"
id="startDate"
bind:value={formData.startDate}
required
/>
</div>
</div>
{#if formData.frequency === 'custom'}
<div class="form-group">
<label for="cronExpression">Cron Expression *</label>
<input
type="text"
id="cronExpression"
bind:value={formData.cronExpression}
required
placeholder="0 9 * * 1 (Every Monday at 9:00 AM)"
class:error={cronError}
/>
<div class="help-text">
<p>Cron format: minute hour day-of-month month day-of-week</p>
<p>Examples:</p>
<ul>
<li><code>0 9 * * *</code> - Every day at 9:00 AM</li>
<li><code>0 9 1 * *</code> - Every 1st of the month at 9:00 AM</li>
<li><code>0 9 * * 1</code> - Every Monday at 9:00 AM</li>
<li><code>0 9 1,15 * *</code> - 1st and 15th of every month at 9:00 AM</li>
</ul>
</div>
{#if cronError}
<div class="field-error">Invalid cron expression</div>
{/if}
</div>
{/if}
<div class="form-group">
<label for="endDate">End Date (optional)</label>
<input
type="date"
id="endDate"
bind:value={formData.endDate}
/>
<div class="help-text">Leave blank for indefinite recurring payments</div>
</div>
{#if nextExecutionPreview}
<div class="execution-preview">
<h3>Next Execution</h3>
<p class="next-execution">{nextExecutionPreview}</p>
<p class="frequency-description">{getFrequencyDescription(formData)}</p>
</div>
{/if}
</div>
<div class="form-section">
<h2>Split Between Users</h2>
<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 === 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">
<h2>Split Method</h2>
<div class="split-method">
<label>
<input type="radio" bind:group={formData.splitMethod} value="equal" />
Equal Split
</label>
<label>
<input type="radio" bind:group={formData.splitMethod} value="personal_equal" />
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}
even
{/if}
</span>
</div>
{/each}
</div>
{/if}
</div>
{#if error}
<div class="error">{error}</div>
{/if}
<div class="form-actions">
<button type="button" class="btn-secondary" on:click={() => goto('/cospend/recurring')}>
Cancel
</button>
<button type="submit" class="btn-primary" disabled={loading || cronError}>
{loading ? 'Saving...' : 'Save Changes'}
</button>
</div>
</form>
{/if}
</main>
<style>
.edit-recurring-payment {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
}
.header h1 {
margin: 0;
color: #333;
}
.back-link {
color: #1976d2;
text-decoration: none;
}
.loading {
text-align: center;
padding: 2rem;
font-size: 1.1rem;
}
.payment-form {
display: flex;
flex-direction: column;
gap: 2rem;
}
.form-section {
background: white;
padding: 1.5rem;
border-radius: 0.75rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.form-section h2 {
margin-top: 0;
margin-bottom: 1rem;
color: #333;
font-size: 1.25rem;
}
.form-group {
margin-bottom: 1rem;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: #555;
}
input, textarea, select {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 0.5rem;
font-size: 1rem;
box-sizing: border-box;
}
input:focus, textarea:focus, select:focus {
outline: none;
border-color: #1976d2;
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
}
input.error {
border-color: #d32f2f;
}
.help-text {
margin-top: 0.5rem;
color: #666;
font-size: 0.9rem;
}
.help-text code {
background-color: #f5f5f5;
padding: 0.125rem 0.25rem;
border-radius: 0.25rem;
font-family: monospace;
}
.help-text ul {
margin: 0.5rem 0;
padding-left: 1rem;
}
.help-text li {
margin-bottom: 0.25rem;
}
.field-error {
color: #d32f2f;
font-size: 0.875rem;
margin-top: 0.25rem;
}
.execution-preview {
background-color: #e3f2fd;
border: 1px solid #2196f3;
border-radius: 0.5rem;
padding: 1rem;
margin-top: 1rem;
}
.execution-preview h3 {
margin: 0 0 0.5rem 0;
color: #1976d2;
font-size: 1rem;
}
.next-execution {
font-size: 1.1rem;
font-weight: 600;
color: #1976d2;
margin: 0.5rem 0;
}
.frequency-description {
color: #666;
font-size: 0.9rem;
margin: 0;
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 {
background-color: #ffebee;
color: #d32f2f;
padding: 1rem;
border-radius: 0.5rem;
margin-bottom: 1rem;
}
.form-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
}
.btn-primary, .btn-secondary {
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
font-size: 1rem;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background-color: #1976d2;
color: white;
border: none;
}
.btn-primary:hover:not(:disabled) {
background-color: #1565c0;
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary {
background-color: #f5f5f5;
color: #333;
border: 1px solid #ddd;
}
.btn-secondary:hover {
background-color: #e8e8e8;
}
@media (max-width: 600px) {
.edit-recurring-payment {
padding: 1rem;
}
.form-row {
grid-template-columns: 1fr;
}
.form-actions {
flex-direction: column;
}
}
</style>