Compare commits
40 Commits
master
...
b03ba61599
| Author | SHA1 | Date | |
|---|---|---|---|
|
b03ba61599
|
|||
|
db3de29e48
|
|||
|
e773a90f1d
|
|||
|
ac6845d38a
|
|||
|
915f27d275
|
|||
|
4cb2f6a958
|
|||
|
aa15a392f1
|
|||
|
cdc744282c
|
|||
|
6d46369eec
|
|||
|
6ab395e98a
|
|||
|
701434d532
|
|||
|
c53300d5a7
|
|||
|
73c7626c32
|
|||
|
098ccb8568
|
|||
|
fd4a25376b
|
|||
|
b67bb0b263
|
|||
|
b08bbbdab9
|
|||
|
712829ad8e
|
|||
|
815975dba0
|
|||
|
95b49ab6ce
|
|||
|
06cd7e7677
|
|||
|
d3a291b9f1
|
|||
|
04b138eed1
|
|||
|
e01ff9eb59
|
|||
|
6a8478f8a6
|
|||
|
be26769efb
|
|||
|
7bc51e3a0e
|
|||
|
75142aa5ee
|
|||
|
2dc871c50f
|
|||
|
88f9531a6f
|
|||
|
aeec3b4865
|
|||
|
55a4e6a262
|
|||
|
48b94e3aef
|
|||
|
15a72e73ca
|
|||
|
bda30eb42d
|
|||
|
9f53e331a7
|
|||
|
b534cd1ddc
|
|||
|
6a64a7ddd6
|
|||
|
fe46ab194e
|
|||
|
1d78b5439e
|
@@ -1,88 +0,0 @@
|
|||||||
# Development Authentication Bypass
|
|
||||||
|
|
||||||
This document explains how to safely disable authentication during development.
|
|
||||||
|
|
||||||
## 🔐 Security Overview
|
|
||||||
|
|
||||||
The authentication bypass is designed with multiple layers of security:
|
|
||||||
|
|
||||||
1. **Development Mode Only**: Only works when `vite dev` is running
|
|
||||||
2. **Explicit Opt-in**: Requires setting `DEV_DISABLE_AUTH=true`
|
|
||||||
3. **Production Protection**: Build fails if enabled in production mode
|
|
||||||
4. **Environment Isolation**: Uses local environment files (gitignored)
|
|
||||||
|
|
||||||
## 🚀 Usage
|
|
||||||
|
|
||||||
### 1. Create Local Environment File
|
|
||||||
|
|
||||||
Create `.env.local` (this file is gitignored):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Copy from example
|
|
||||||
cp .env.local.example .env.local
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Enable Development Bypass
|
|
||||||
|
|
||||||
Edit `.env.local` and set:
|
|
||||||
|
|
||||||
```env
|
|
||||||
DEV_DISABLE_AUTH=true
|
|
||||||
```
|
|
||||||
|
|
||||||
### 3. Start Development Server
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pnpm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
You'll see a warning in the console:
|
|
||||||
```
|
|
||||||
🚨 AUTH DISABLED: Development mode with DEV_DISABLE_AUTH=true
|
|
||||||
```
|
|
||||||
|
|
||||||
### 4. Access Protected Routes
|
|
||||||
|
|
||||||
Protected routes (`/rezepte/edit/*`, `/rezepte/add`) will now be accessible without authentication.
|
|
||||||
|
|
||||||
## 🛡️ Security Guarantees
|
|
||||||
|
|
||||||
### Production Safety
|
|
||||||
- **Build-time Check**: Production builds fail if `DEV_DISABLE_AUTH=true`
|
|
||||||
- **Runtime Check**: Double verification using `dev` flag from `$app/environment`
|
|
||||||
- **No Environment Leakage**: Uses `process.env` (server-only) not client environment
|
|
||||||
|
|
||||||
### Development Isolation
|
|
||||||
- **Gitignored Files**: `.env.local` is never committed
|
|
||||||
- **Example Template**: `.env.local.example` shows safe defaults
|
|
||||||
- **Clear Warnings**: Console warns when auth is disabled
|
|
||||||
|
|
||||||
## 🧪 Testing the Security
|
|
||||||
|
|
||||||
### Test Production Build Safety
|
|
||||||
```bash
|
|
||||||
# This should FAIL with security error
|
|
||||||
DEV_DISABLE_AUTH=true pnpm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
### Test Normal Production Build
|
|
||||||
```bash
|
|
||||||
# This should succeed
|
|
||||||
pnpm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🔄 Re-enabling Authentication
|
|
||||||
|
|
||||||
Set in `.env.local`:
|
|
||||||
```env
|
|
||||||
DEV_DISABLE_AUTH=false
|
|
||||||
```
|
|
||||||
|
|
||||||
Or simply delete/rename the `.env.local` file.
|
|
||||||
|
|
||||||
## ⚠️ Important Notes
|
|
||||||
|
|
||||||
- **Never** commit `.env.local` to git
|
|
||||||
- **Never** set `DEV_DISABLE_AUTH=true` in production environment
|
|
||||||
- The bypass provides a mock session with `rezepte_users` group access
|
|
||||||
- All other authentication flows (signin pages, etc.) remain unchanged
|
|
||||||
191
RECURRING_PAYMENTS_SETUP.md
Normal file
191
RECURRING_PAYMENTS_SETUP.md
Normal 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
|
||||||
3318
package-lock.json
generated
3318
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "sk-recipes-test",
|
"name": "homepage",
|
||||||
"version": "0.0.1",
|
"version": "1.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
"@sveltejs/kit": "^2.37.0",
|
"@sveltejs/kit": "^2.37.0",
|
||||||
"@sveltejs/vite-plugin-svelte": "^6.1.3",
|
"@sveltejs/vite-plugin-svelte": "^6.1.3",
|
||||||
"@types/node": "^22.12.0",
|
"@types/node": "^22.12.0",
|
||||||
|
"@types/node-cron": "^3.0.11",
|
||||||
"svelte": "^5.38.6",
|
"svelte": "^5.38.6",
|
||||||
"svelte-check": "^4.0.0",
|
"svelte-check": "^4.0.0",
|
||||||
"tslib": "^2.6.0",
|
"tslib": "^2.6.0",
|
||||||
@@ -26,8 +27,10 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@auth/sveltekit": "^1.10.0",
|
"@auth/sveltekit": "^1.10.0",
|
||||||
"@sveltejs/adapter-node": "^5.0.0",
|
"@sveltejs/adapter-node": "^5.0.0",
|
||||||
|
"chart.js": "^4.5.0",
|
||||||
"cheerio": "1.0.0-rc.12",
|
"cheerio": "1.0.0-rc.12",
|
||||||
"mongoose": "^8.0.0",
|
"mongoose": "^8.0.0",
|
||||||
|
"node-cron": "^4.2.1",
|
||||||
"sharp": "^0.33.0"
|
"sharp": "^0.33.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
33
pnpm-lock.yaml
generated
33
pnpm-lock.yaml
generated
@@ -14,12 +14,18 @@ importers:
|
|||||||
'@sveltejs/adapter-node':
|
'@sveltejs/adapter-node':
|
||||||
specifier: ^5.0.0
|
specifier: ^5.0.0
|
||||||
version: 5.3.1(@sveltejs/kit@2.37.0(@sveltejs/vite-plugin-svelte@6.1.3(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))
|
version: 5.3.1(@sveltejs/kit@2.37.0(@sveltejs/vite-plugin-svelte@6.1.3(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))(svelte@5.38.6)(vite@7.1.3(@types/node@22.18.0)))
|
||||||
|
chart.js:
|
||||||
|
specifier: ^4.5.0
|
||||||
|
version: 4.5.0
|
||||||
cheerio:
|
cheerio:
|
||||||
specifier: 1.0.0-rc.12
|
specifier: 1.0.0-rc.12
|
||||||
version: 1.0.0-rc.12
|
version: 1.0.0-rc.12
|
||||||
mongoose:
|
mongoose:
|
||||||
specifier: ^8.0.0
|
specifier: ^8.0.0
|
||||||
version: 8.18.0(socks@2.7.1)
|
version: 8.18.0(socks@2.7.1)
|
||||||
|
node-cron:
|
||||||
|
specifier: ^4.2.1
|
||||||
|
version: 4.2.1
|
||||||
sharp:
|
sharp:
|
||||||
specifier: ^0.33.0
|
specifier: ^0.33.0
|
||||||
version: 0.33.5
|
version: 0.33.5
|
||||||
@@ -39,6 +45,9 @@ importers:
|
|||||||
'@types/node':
|
'@types/node':
|
||||||
specifier: ^22.12.0
|
specifier: ^22.12.0
|
||||||
version: 22.18.0
|
version: 22.18.0
|
||||||
|
'@types/node-cron':
|
||||||
|
specifier: ^3.0.11
|
||||||
|
version: 3.0.11
|
||||||
svelte:
|
svelte:
|
||||||
specifier: ^5.38.6
|
specifier: ^5.38.6
|
||||||
version: 5.38.6
|
version: 5.38.6
|
||||||
@@ -370,6 +379,9 @@ packages:
|
|||||||
'@jridgewell/trace-mapping@0.3.30':
|
'@jridgewell/trace-mapping@0.3.30':
|
||||||
resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==}
|
resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==}
|
||||||
|
|
||||||
|
'@kurkle/color@0.3.4':
|
||||||
|
resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==}
|
||||||
|
|
||||||
'@mongodb-js/saslprep@1.3.0':
|
'@mongodb-js/saslprep@1.3.0':
|
||||||
resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==}
|
resolution: {integrity: sha512-zlayKCsIjYb7/IdfqxorK5+xUMyi4vOKcFy10wKJYc63NSdKI8mNME+uJqfatkPmOSMMUiojrL58IePKBm3gvQ==}
|
||||||
|
|
||||||
@@ -584,6 +596,9 @@ packages:
|
|||||||
'@types/estree@1.0.8':
|
'@types/estree@1.0.8':
|
||||||
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
|
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':
|
'@types/node@22.18.0':
|
||||||
resolution: {integrity: sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==}
|
resolution: {integrity: sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==}
|
||||||
|
|
||||||
@@ -616,6 +631,10 @@ packages:
|
|||||||
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
|
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
|
||||||
engines: {node: '>=16.20.1'}
|
engines: {node: '>=16.20.1'}
|
||||||
|
|
||||||
|
chart.js@4.5.0:
|
||||||
|
resolution: {integrity: sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==}
|
||||||
|
engines: {pnpm: '>=8'}
|
||||||
|
|
||||||
cheerio-select@2.1.0:
|
cheerio-select@2.1.0:
|
||||||
resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
|
resolution: {integrity: sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==}
|
||||||
|
|
||||||
@@ -842,6 +861,10 @@ packages:
|
|||||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
node-cron@4.2.1:
|
||||||
|
resolution: {integrity: sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==}
|
||||||
|
engines: {node: '>=6.0.0'}
|
||||||
|
|
||||||
nth-check@2.1.1:
|
nth-check@2.1.1:
|
||||||
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
|
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
|
||||||
|
|
||||||
@@ -1238,6 +1261,8 @@ snapshots:
|
|||||||
'@jridgewell/resolve-uri': 3.1.0
|
'@jridgewell/resolve-uri': 3.1.0
|
||||||
'@jridgewell/sourcemap-codec': 1.4.15
|
'@jridgewell/sourcemap-codec': 1.4.15
|
||||||
|
|
||||||
|
'@kurkle/color@0.3.4': {}
|
||||||
|
|
||||||
'@mongodb-js/saslprep@1.3.0':
|
'@mongodb-js/saslprep@1.3.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
sparse-bitfield: 3.0.3
|
sparse-bitfield: 3.0.3
|
||||||
@@ -1418,6 +1443,8 @@ snapshots:
|
|||||||
|
|
||||||
'@types/estree@1.0.8': {}
|
'@types/estree@1.0.8': {}
|
||||||
|
|
||||||
|
'@types/node-cron@3.0.11': {}
|
||||||
|
|
||||||
'@types/node@22.18.0':
|
'@types/node@22.18.0':
|
||||||
dependencies:
|
dependencies:
|
||||||
undici-types: 6.21.0
|
undici-types: 6.21.0
|
||||||
@@ -1440,6 +1467,10 @@ snapshots:
|
|||||||
|
|
||||||
bson@6.10.4: {}
|
bson@6.10.4: {}
|
||||||
|
|
||||||
|
chart.js@4.5.0:
|
||||||
|
dependencies:
|
||||||
|
'@kurkle/color': 0.3.4
|
||||||
|
|
||||||
cheerio-select@2.1.0:
|
cheerio-select@2.1.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
boolbase: 1.0.0
|
boolbase: 1.0.0
|
||||||
@@ -1669,6 +1700,8 @@ snapshots:
|
|||||||
|
|
||||||
nanoid@3.3.11: {}
|
nanoid@3.3.11: {}
|
||||||
|
|
||||||
|
node-cron@4.2.1: {}
|
||||||
|
|
||||||
nth-check@2.1.1:
|
nth-check@2.1.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
boolbase: 1.0.0
|
boolbase: 1.0.0
|
||||||
|
|||||||
@@ -25,5 +25,6 @@ export const { handle, signIn, signOut } = SvelteKitAuth({
|
|||||||
return session;
|
return session;
|
||||||
},
|
},
|
||||||
|
|
||||||
}
|
},
|
||||||
|
trustHost: true // needed for reverse proxy setups
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -6,6 +6,10 @@ import Authentik from "@auth/core/providers/authentik"
|
|||||||
import { AUTHENTIK_ID, AUTHENTIK_SECRET, AUTHENTIK_ISSUER } from "$env/static/private";
|
import { AUTHENTIK_ID, AUTHENTIK_SECRET, AUTHENTIK_ISSUER } from "$env/static/private";
|
||||||
import { sequence } from "@sveltejs/kit/hooks"
|
import { sequence } from "@sveltejs/kit/hooks"
|
||||||
import * as auth from "./auth"
|
import * as auth from "./auth"
|
||||||
|
import { initializeScheduler } from "./lib/server/scheduler"
|
||||||
|
|
||||||
|
// Initialize the recurring payment scheduler
|
||||||
|
initializeScheduler();
|
||||||
|
|
||||||
async function authorization({ event, resolve }) {
|
async function authorization({ event, resolve }) {
|
||||||
// Protect any routes under /authenticated
|
// Protect any routes under /authenticated
|
||||||
|
|||||||
33
src/lib/assets/icons/Heart.svelte
Normal file
33
src/lib/assets/icons/Heart.svelte
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<script>
|
||||||
|
</script>
|
||||||
|
<style>
|
||||||
|
@keyframes shake{
|
||||||
|
0%{
|
||||||
|
transform: rotate(0)
|
||||||
|
scale(1,1);
|
||||||
|
}
|
||||||
|
25%{
|
||||||
|
box-shadow: 0em 0em 1em 0.2em rgba(0, 0, 0, 0.6);
|
||||||
|
transform: rotate(30deg)
|
||||||
|
scale(1.2,1.2)
|
||||||
|
;
|
||||||
|
}
|
||||||
|
50%{
|
||||||
|
|
||||||
|
box-shadow: 0em 0em 1em 0.2em rgba(0, 0, 0, 0.6);
|
||||||
|
transform: rotate(-30deg)
|
||||||
|
scale(1.2,1.2);
|
||||||
|
}
|
||||||
|
74%{
|
||||||
|
|
||||||
|
box-shadow: 0em 0em 1em 0.2em rgba(0, 0, 0, 0.6);
|
||||||
|
transform: rotate(30deg)
|
||||||
|
scale(1.2, 1.2);
|
||||||
|
}
|
||||||
|
100%{
|
||||||
|
transform: rotate(0)
|
||||||
|
scale(1,1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512" {...$$restProps}><!--! Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path d="m47.6 300.4 180.7 168.7c7.5 7 17.4 10.9 27.7 10.9s20.2-3.9 27.7-10.9L464.4 300.4c30.4-28.3 47.6-68 47.6-109.5v-5.8c0-69.9-50.5-129.5-119.4-141C347 36.5 300.6 51.4 268 84L256 96 244 84c-32.6-32.6-79-47.5-124.6-39.9C50.5 55.6 0 115.2 0 185.1v5.8c0 41.5 17.2 81.2 47.6 109.5z"/></svg>
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
<script lang='ts'>
|
<script lang='ts'>
|
||||||
import ActionButton from "./ActionButton.svelte";
|
import ActionButton from "./ActionButton.svelte";
|
||||||
|
|
||||||
|
export let href: string;
|
||||||
</script>
|
</script>
|
||||||
<ActionButton href="/rezepte/add">
|
<ActionButton {href}>
|
||||||
<svg class=icon_svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512"><!--! Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path d="M256 80c0-17.7-14.3-32-32-32s-32 14.3-32 32V224H48c-17.7 0-32 14.3-32 32s14.3 32 32 32H192V432c0 17.7 14.3 32 32 32s32-14.3 32-32V288H400c17.7 0 32-14.3 32-32s-14.3-32-32-32H256V80z"/></svg>
|
<svg class=icon_svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512"><!--! Font Awesome Free 6.4.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path d="M256 80c0-17.7-14.3-32-32-32s-32 14.3-32 32V224H48c-17.7 0-32 14.3-32 32s14.3 32 32 32H192V432c0 17.7 14.3 32 32 32s32-14.3 32-32V288H400c17.7 0 32-14.3 32-32s-14.3-32-32-32H256V80z"/></svg>
|
||||||
</ActionButton>
|
</ActionButton>
|
||||||
|
|||||||
205
src/lib/components/BarChart.svelte
Normal file
205
src/lib/components/BarChart.svelte
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { Chart, registerables } from 'chart.js';
|
||||||
|
|
||||||
|
export let data = { labels: [], datasets: [] };
|
||||||
|
export let title = '';
|
||||||
|
export let height = '400px';
|
||||||
|
|
||||||
|
let canvas;
|
||||||
|
let chart;
|
||||||
|
|
||||||
|
// Register Chart.js components
|
||||||
|
Chart.register(...registerables);
|
||||||
|
|
||||||
|
// Nord theme colors for categories
|
||||||
|
const nordColors = [
|
||||||
|
'#5E81AC', // Nord Blue
|
||||||
|
'#88C0D0', // Nord Light Blue
|
||||||
|
'#81A1C1', // Nord Lighter Blue
|
||||||
|
'#A3BE8C', // Nord Green
|
||||||
|
'#EBCB8B', // Nord Yellow
|
||||||
|
'#D08770', // Nord Orange
|
||||||
|
'#BF616A', // Nord Red
|
||||||
|
'#B48EAD', // Nord Purple
|
||||||
|
'#8FBCBB', // Nord Cyan
|
||||||
|
'#ECEFF4', // Nord Light Gray
|
||||||
|
];
|
||||||
|
|
||||||
|
function getCategoryColor(category, index) {
|
||||||
|
const categoryColorMap = {
|
||||||
|
'groceries': '#A3BE8C', // Green
|
||||||
|
'restaurant': '#D08770', // Orange
|
||||||
|
'transport': '#5E81AC', // Blue
|
||||||
|
'entertainment': '#B48EAD', // Purple
|
||||||
|
'shopping': '#EBCB8B', // Yellow
|
||||||
|
'utilities': '#81A1C1', // Light Blue
|
||||||
|
'healthcare': '#BF616A', // Red
|
||||||
|
'education': '#88C0D0', // Cyan
|
||||||
|
'travel': '#8FBCBB', // Light Cyan
|
||||||
|
'other': '#4C566A' // Dark Gray
|
||||||
|
};
|
||||||
|
|
||||||
|
return categoryColorMap[category] || nordColors[index % nordColors.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
function createChart() {
|
||||||
|
if (!canvas || !data.datasets) return;
|
||||||
|
|
||||||
|
// Destroy existing chart
|
||||||
|
if (chart) {
|
||||||
|
chart.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
|
||||||
|
// Process datasets with colors
|
||||||
|
const processedDatasets = data.datasets.map((dataset, index) => ({
|
||||||
|
...dataset,
|
||||||
|
backgroundColor: getCategoryColor(dataset.label, index),
|
||||||
|
borderColor: getCategoryColor(dataset.label, index),
|
||||||
|
borderWidth: 1
|
||||||
|
}));
|
||||||
|
|
||||||
|
chart = new Chart(ctx, {
|
||||||
|
type: 'bar',
|
||||||
|
data: {
|
||||||
|
labels: data.labels,
|
||||||
|
datasets: processedDatasets
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: false,
|
||||||
|
scales: {
|
||||||
|
x: {
|
||||||
|
stacked: true,
|
||||||
|
grid: {
|
||||||
|
display: false
|
||||||
|
},
|
||||||
|
ticks: {
|
||||||
|
color: 'var(--nord3)',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
y: {
|
||||||
|
stacked: true,
|
||||||
|
beginAtZero: true,
|
||||||
|
grid: {
|
||||||
|
color: 'var(--nord4)',
|
||||||
|
borderDash: [2, 2]
|
||||||
|
},
|
||||||
|
ticks: {
|
||||||
|
color: 'var(--nord3)',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif'
|
||||||
|
},
|
||||||
|
callback: function(value) {
|
||||||
|
return 'CHF ' + value.toFixed(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
legend: {
|
||||||
|
position: 'bottom',
|
||||||
|
labels: {
|
||||||
|
padding: 20,
|
||||||
|
usePointStyle: true,
|
||||||
|
color: 'var(--nord1)',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif',
|
||||||
|
size: 12
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
title: {
|
||||||
|
display: !!title,
|
||||||
|
text: title,
|
||||||
|
color: 'var(--nord0)',
|
||||||
|
font: {
|
||||||
|
family: 'Inter, system-ui, sans-serif',
|
||||||
|
size: 16,
|
||||||
|
weight: 'bold'
|
||||||
|
},
|
||||||
|
padding: 20
|
||||||
|
},
|
||||||
|
tooltip: {
|
||||||
|
backgroundColor: 'var(--nord1)',
|
||||||
|
titleColor: 'var(--nord6)',
|
||||||
|
bodyColor: 'var(--nord6)',
|
||||||
|
borderColor: 'var(--nord3)',
|
||||||
|
borderWidth: 1,
|
||||||
|
cornerRadius: 8,
|
||||||
|
titleFont: {
|
||||||
|
family: 'Inter, system-ui, sans-serif'
|
||||||
|
},
|
||||||
|
bodyFont: {
|
||||||
|
family: 'Inter, system-ui, sans-serif'
|
||||||
|
},
|
||||||
|
callbacks: {
|
||||||
|
label: function(context) {
|
||||||
|
return context.dataset.label + ': CHF ' + context.parsed.y.toFixed(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
interaction: {
|
||||||
|
intersect: false,
|
||||||
|
mode: 'index'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
createChart();
|
||||||
|
|
||||||
|
// Watch for theme changes
|
||||||
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
const handleThemeChange = () => {
|
||||||
|
setTimeout(createChart, 100); // Small delay to let CSS variables update
|
||||||
|
};
|
||||||
|
|
||||||
|
mediaQuery.addEventListener('change', handleThemeChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
mediaQuery.removeEventListener('change', handleThemeChange);
|
||||||
|
if (chart) {
|
||||||
|
chart.destroy();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Recreate chart when data changes
|
||||||
|
$: if (canvas && data) {
|
||||||
|
createChart();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="chart-container" style="height: {height}">
|
||||||
|
<canvas bind:this={canvas}></canvas>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.chart-container {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
padding: 1.5rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.chart-container {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas {
|
||||||
|
max-width: 100%;
|
||||||
|
height: 100% !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -7,6 +7,8 @@ import "$lib/css/nordtheme.css";
|
|||||||
import "$lib/css/shake.css";
|
import "$lib/css/shake.css";
|
||||||
import "$lib/css/icon.css";
|
import "$lib/css/icon.css";
|
||||||
export let do_margin_right = false;
|
export let do_margin_right = false;
|
||||||
|
export let isFavorite = false;
|
||||||
|
export let showFavoriteIndicator = false;
|
||||||
// to manually override lazy loading for top cards
|
// to manually override lazy loading for top cards
|
||||||
export let loading_strat : "lazy" | "eager" | undefined;
|
export let loading_strat : "lazy" | "eager" | undefined;
|
||||||
if(loading_strat === undefined){
|
if(loading_strat === undefined){
|
||||||
@@ -69,7 +71,7 @@ const img_name=recipe.short_name + ".webp?v=" + recipe.dateModified
|
|||||||
font-size: 1.5em;
|
font-size: 1.5em;
|
||||||
box-shadow: 0em 0em 1em 0.1em rgba(0, 0, 0, 0.6);
|
box-shadow: 0em 0em 1em 0.1em rgba(0, 0, 0, 0.6);
|
||||||
transition: 100ms;
|
transition: 100ms;
|
||||||
z-index: 10;
|
z-index: 5;
|
||||||
}
|
}
|
||||||
#image{
|
#image{
|
||||||
width: 300px;
|
width: 300px;
|
||||||
@@ -192,6 +194,14 @@ const img_name=recipe.short_name + ".webp?v=" + recipe.dateModified
|
|||||||
scale: 0.9 0.9;
|
scale: 0.9 0.9;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.favorite-indicator{
|
||||||
|
position: absolute;
|
||||||
|
font-size: 2rem;
|
||||||
|
top: 0.1em;
|
||||||
|
left: 0.1em;
|
||||||
|
filter: drop-shadow(0 0 3px rgba(0, 0, 0, 0.8));
|
||||||
|
}
|
||||||
|
|
||||||
.icon:hover,
|
.icon:hover,
|
||||||
.icon:focus-visible
|
.icon:focus-visible
|
||||||
{
|
{
|
||||||
@@ -224,6 +234,9 @@ const img_name=recipe.short_name + ".webp?v=" + recipe.dateModified
|
|||||||
<img class:blur={!isloaded} id=image class="backdrop_blur" src={'https://bocken.org/static/rezepte/thumb/' + recipe.short_name + '.webp'} loading={loading_strat} alt="{recipe.alt}" on:load={() => isloaded=true}/>
|
<img class:blur={!isloaded} id=image class="backdrop_blur" src={'https://bocken.org/static/rezepte/thumb/' + recipe.short_name + '.webp'} loading={loading_strat} alt="{recipe.alt}" on:load={() => isloaded=true}/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{#if showFavoriteIndicator && isFavorite}
|
||||||
|
<div class="favorite-indicator">❤️</div>
|
||||||
|
{/if}
|
||||||
{#if icon_override || recipe.season.includes(current_month)}
|
{#if icon_override || recipe.season.includes(current_month)}
|
||||||
<button class=icon on:click={(e) => {e.stopPropagation(); window.location.href = `/rezepte/icon/${recipe.icon}`}}>{recipe.icon}</button>
|
<button class=icon on:click={(e) => {e.stopPropagation(); window.location.href = `/rezepte/icon/${recipe.icon}`}}>{recipe.icon}</button>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -378,7 +378,7 @@ input::placeholder{
|
|||||||
<div class=tags>
|
<div class=tags>
|
||||||
{#each card_data.tags as tag}
|
{#each card_data.tags as tag}
|
||||||
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
|
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
|
||||||
<div class="tag" tabindex="0" on:keydown={remove_on_enter(event ,tag)} on:click='{remove_from_tags(tag)}'>{tag}</div>
|
<div class="tag" role="button" tabindex="0" on:keydown={remove_on_enter(event ,tag)} on:click='{remove_from_tags(tag)}' aria-label="Tag {tag} entfernen">{tag}</div>
|
||||||
{/each}
|
{/each}
|
||||||
<div class="tag input_wrapper"><span class=input>+</span><input class="tag_input" type="text" on:keydown={add_on_enter} on:focusout={add_to_tags} size="1" bind:value={new_tag} placeholder=Stichwort...></div>
|
<div class="tag input_wrapper"><span class=input>+</span><input class="tag_input" type="text" on:keydown={add_on_enter} on:focusout={add_to_tags} size="1" bind:value={new_tag} placeholder=Stichwort...></div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -411,6 +411,25 @@ h3{
|
|||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Styling for converted div-to-button elements */
|
||||||
|
.subheading-button {
|
||||||
|
all: unset;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ingredient-amount-button, .ingredient-name-button {
|
||||||
|
all: unset;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<div class=list_wrapper >
|
<div class=list_wrapper >
|
||||||
@@ -422,49 +441,47 @@ h3{
|
|||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
<h3>
|
<h3>
|
||||||
<div class=move_buttons_container>
|
<div class=move_buttons_container>
|
||||||
<button on:click="{() => update_list_position(list_index, 1)}">
|
<button on:click="{() => update_list_position(list_index, 1)}" aria-label="Liste nach oben verschieben">
|
||||||
<svg class="button_arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
<svg class="button_arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button on:click="{() => update_list_position(list_index, -1)}">
|
<button on:click="{() => update_list_position(list_index, -1)}" aria-label="Liste nach unten verschieben">
|
||||||
<svg class="button_arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
<svg class="button_arrow" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div on:click="{() => show_modal_edit_subheading_ingredient(list_index)}">
|
<button on:click="{() => show_modal_edit_subheading_ingredient(list_index)}" class="subheading-button">
|
||||||
{#if list.name }
|
{#if list.name }
|
||||||
{list.name}
|
{list.name}
|
||||||
{:else}
|
{:else}
|
||||||
Leer
|
Leer
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</button>
|
||||||
<div class=mod_icons>
|
<div class=mod_icons>
|
||||||
<button class="action_button button_subtle" on:click="{() => show_modal_edit_subheading_ingredient(list_index)}">
|
<button class="action_button button_subtle" on:click="{() => show_modal_edit_subheading_ingredient(list_index)}" aria-label="Überschrift bearbeiten">
|
||||||
<Pen fill=var(--nord1)></Pen> </button>
|
<Pen fill=var(--nord1)></Pen> </button>
|
||||||
<button class="action_button button_subtle" on:click="{() => remove_list(list_index)}">
|
<button class="action_button button_subtle" on:click="{() => remove_list(list_index)}" aria-label="Liste entfernen">
|
||||||
<Cross fill=var(--nord1)></Cross></button>
|
<Cross fill=var(--nord1)></Cross></button>
|
||||||
</div>
|
</div>
|
||||||
</h3>
|
</h3>
|
||||||
<div class=ingredients_grid>
|
<div class=ingredients_grid>
|
||||||
{#each list.list as ingredient, ingredient_index (ingredient_index)}
|
{#each list.list as ingredient, ingredient_index (ingredient_index)}
|
||||||
<div class=move_buttons_container>
|
<div class=move_buttons_container>
|
||||||
<button on:click="{() => update_ingredient_position(list_index, ingredient_index, 1)}">
|
<button on:click="{() => update_ingredient_position(list_index, ingredient_index, 1)}" aria-label="Zutat nach oben verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button on:click="{() => update_ingredient_position(list_index, ingredient_index, -1)}">
|
<button on:click="{() => update_ingredient_position(list_index, ingredient_index, -1)}" aria-label="Zutat nach unten verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<button on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)} class="ingredient-amount-button">
|
||||||
<div on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)} >
|
|
||||||
{ingredient.amount} {ingredient.unit}
|
{ingredient.amount} {ingredient.unit}
|
||||||
</div>
|
</button>
|
||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<button class="force_wrap ingredient-name-button" on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)}>
|
||||||
<div class=force_wrap on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)} >
|
|
||||||
{@html ingredient.name}
|
{@html ingredient.name}
|
||||||
</div>
|
</button>
|
||||||
<div class=mod_icons><button class="action_button button_subtle" on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)}>
|
<div class=mod_icons><button class="action_button button_subtle" on:click={() => show_modal_edit_ingredient(list_index, ingredient_index)} aria-label="Zutat bearbeiten">
|
||||||
<Pen fill=var(--nord1) height=1em width=1em></Pen></button>
|
<Pen fill=var(--nord1) height=1em width=1em></Pen></button>
|
||||||
<button class="action_button button_subtle" on:click="{() => remove_ingredient(list_index, ingredient_index)}"><Cross fill=var(--nord1) height=1em width=1em></Cross></button></div>
|
<button class="action_button button_subtle" on:click="{() => remove_ingredient(list_index, ingredient_index)}" aria-label="Zutat entfernen"><Cross fill=var(--nord1) height=1em width=1em></Cross></button></div>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
@@ -485,7 +502,7 @@ h3{
|
|||||||
<h2>Zutat verändern</h2>
|
<h2>Zutat verändern</h2>
|
||||||
<div class=adder>
|
<div class=adder>
|
||||||
<input class=category type="text" bind:value={edit_ingredient.sublist} placeholder="Kategorie (optional)">
|
<input class=category type="text" bind:value={edit_ingredient.sublist} placeholder="Kategorie (optional)">
|
||||||
<div class=add_ingredient on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
<div class=add_ingredient role="group" on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
||||||
<input type="text" placeholder="250..." bind:value={edit_ingredient.amount} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
<input type="text" placeholder="250..." bind:value={edit_ingredient.amount} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
||||||
<input type="text" placeholder="mL..." bind:value={edit_ingredient.unit} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
<input type="text" placeholder="mL..." bind:value={edit_ingredient.unit} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
||||||
<input type="text" placeholder="Milch..." bind:value={edit_ingredient.name} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
<input type="text" placeholder="Milch..." bind:value={edit_ingredient.name} on:keydown={(event) => do_on_key(event, 'Enter', false, edit_ingredient_and_close_modal)}>
|
||||||
|
|||||||
@@ -441,6 +441,16 @@ h3{
|
|||||||
fill: var(--nord4);
|
fill: var(--nord4);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Styling for converted div-to-button elements */
|
||||||
|
.subheading-button, .step-button {
|
||||||
|
all: unset;
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<div class=instructions>
|
<div class=instructions>
|
||||||
@@ -476,23 +486,23 @@ h3{
|
|||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
<h3>
|
<h3>
|
||||||
<div class=move_buttons_container>
|
<div class=move_buttons_container>
|
||||||
<button on:click="{() => update_list_position(list_index, 1)}">
|
<button on:click="{() => update_list_position(list_index, 1)}" aria-label="Liste nach oben verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button on:click="{() => update_list_position(list_index, -1)}">
|
<button on:click="{() => update_list_position(list_index, -1)}" aria-label="Liste nach unten verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div on:click={() => show_modal_edit_subheading_step(list_index)}>
|
<button on:click={() => show_modal_edit_subheading_step(list_index)} class="subheading-button">
|
||||||
{#if list.name}
|
{#if list.name}
|
||||||
{list.name}
|
{list.name}
|
||||||
{:else}
|
{:else}
|
||||||
Leer
|
Leer
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</button>
|
||||||
<button class="action_button button_subtle" on:click="{() => show_modal_edit_subheading_step(list_index)}">
|
<button class="action_button button_subtle" on:click="{() => show_modal_edit_subheading_step(list_index)}" aria-label="Überschrift bearbeiten">
|
||||||
<Pen fill=var(--nord1)></Pen> </button>
|
<Pen fill=var(--nord1)></Pen> </button>
|
||||||
<button class="action_button button_subtle" on:click="{() => remove_list(list_index)}">
|
<button class="action_button button_subtle" on:click="{() => remove_list(list_index)}" aria-label="Liste entfernen">
|
||||||
<Cross fill=var(--nord1)></Cross>
|
<Cross fill=var(--nord1)></Cross>
|
||||||
</button>
|
</button>
|
||||||
</h3>
|
</h3>
|
||||||
@@ -501,17 +511,17 @@ h3{
|
|||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
<li>
|
<li>
|
||||||
<div class="move_buttons_container step_move_buttons">
|
<div class="move_buttons_container step_move_buttons">
|
||||||
<button on:click="{() => update_step_position(list_index, step_index, 1)}">
|
<button on:click="{() => update_step_position(list_index, step_index, 1)}" aria-label="Schritt nach oben verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6 1.41 1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
<button on:click="{() => update_step_position(list_index, step_index, -1)}">
|
<button on:click="{() => update_step_position(list_index, step_index, -1)}" aria-label="Schritt nach unten verschieben">
|
||||||
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
<svg class=button_arrow xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16px" height="16px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div on:click={() => show_modal_edit_step(list_index, step_index)}>
|
<button on:click={() => show_modal_edit_step(list_index, step_index)} class="step-button">
|
||||||
{@html step}
|
{@html step}
|
||||||
</div>
|
</button>
|
||||||
<div><button class="action_button button_subtle" on:click={() => show_modal_edit_step(list_index, step_index)}>
|
<div><button class="action_button button_subtle" on:click={() => show_modal_edit_step(list_index, step_index)}>
|
||||||
<Pen fill=var(--nord1)></Pen>
|
<Pen fill=var(--nord1)></Pen>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
251
src/lib/components/DebtBreakdown.svelte
Normal file
251
src/lib/components/DebtBreakdown.svelte
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
let debtData = {
|
||||||
|
whoOwesMe: [],
|
||||||
|
whoIOwe: [],
|
||||||
|
totalOwedToMe: 0,
|
||||||
|
totalIOwe: 0
|
||||||
|
};
|
||||||
|
let loading = true;
|
||||||
|
let error = null;
|
||||||
|
|
||||||
|
$: shouldHide = getShouldHide();
|
||||||
|
|
||||||
|
function getShouldHide() {
|
||||||
|
const totalUsers = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
||||||
|
return totalUsers <= 1; // Hide if 0 or 1 user (1 user is handled by enhanced balance)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
await fetchDebtBreakdown();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchDebtBreakdown() {
|
||||||
|
try {
|
||||||
|
loading = true;
|
||||||
|
const response = await fetch('/api/cospend/debts');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch debt breakdown');
|
||||||
|
}
|
||||||
|
debtData = await response.json();
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCurrency(amount) {
|
||||||
|
return new Intl.NumberFormat('de-CH', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'CHF'
|
||||||
|
}).format(amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export refresh method for parent components to call
|
||||||
|
export async function refresh() {
|
||||||
|
await fetchDebtBreakdown();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if !shouldHide}
|
||||||
|
<div class="debt-breakdown">
|
||||||
|
<h2>Debt Overview</h2>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading debt breakdown...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else}
|
||||||
|
<div class="debt-sections">
|
||||||
|
{#if debtData.whoOwesMe.length > 0}
|
||||||
|
<div class="debt-section owed-to-me">
|
||||||
|
<h3>Who owes you</h3>
|
||||||
|
<div class="total-amount positive">
|
||||||
|
Total: {formatCurrency(debtData.totalOwedToMe)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="debt-list">
|
||||||
|
{#each debtData.whoOwesMe as debt}
|
||||||
|
<div class="debt-item">
|
||||||
|
<div class="debt-user">
|
||||||
|
<ProfilePicture username={debt.username} size={40} />
|
||||||
|
<div class="user-details">
|
||||||
|
<span class="username">{debt.username}</span>
|
||||||
|
<span class="amount positive">{formatCurrency(debt.netAmount)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="transaction-count">
|
||||||
|
{debt.transactions.length} transaction{debt.transactions.length !== 1 ? 's' : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if debtData.whoIOwe.length > 0}
|
||||||
|
<div class="debt-section owe-to-others">
|
||||||
|
<h3>You owe</h3>
|
||||||
|
<div class="total-amount negative">
|
||||||
|
Total: {formatCurrency(debtData.totalIOwe)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="debt-list">
|
||||||
|
{#each debtData.whoIOwe as debt}
|
||||||
|
<div class="debt-item">
|
||||||
|
<div class="debt-user">
|
||||||
|
<ProfilePicture username={debt.username} size={40} />
|
||||||
|
<div class="user-details">
|
||||||
|
<span class="username">{debt.username}</span>
|
||||||
|
<span class="amount negative">{formatCurrency(debt.netAmount)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="transaction-count">
|
||||||
|
{debt.transactions.length} transaction{debt.transactions.length !== 1 ? 's' : ''}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.debt-breakdown {
|
||||||
|
background: white;
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-breakdown h2 {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
color: #333;
|
||||||
|
font-size: 1.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #d32f2f;
|
||||||
|
background-color: #ffebee;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-debts {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
color: #666;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-sections {
|
||||||
|
display: grid;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.debt-sections {
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-section {
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-section.owed-to-me {
|
||||||
|
background: linear-gradient(135deg, #e8f5e8, #f0f8f0);
|
||||||
|
border: 1px solid #c8e6c9;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-section.owe-to-others {
|
||||||
|
background: linear-gradient(135deg, #ffeaea, #fff5f5);
|
||||||
|
border: 1px solid #ffcdd2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-section h3 {
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.total-amount {
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.total-amount.positive {
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.total-amount.negative {
|
||||||
|
color: #d32f2f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: white;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-details {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount {
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.positive {
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.negative {
|
||||||
|
color: #d32f2f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.transaction-count {
|
||||||
|
color: #666;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
354
src/lib/components/EnhancedBalance.svelte
Normal file
354
src/lib/components/EnhancedBalance.svelte
Normal file
@@ -0,0 +1,354 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
export let initialBalance = null;
|
||||||
|
export let initialDebtData = null;
|
||||||
|
|
||||||
|
let balance = initialBalance || {
|
||||||
|
netBalance: 0,
|
||||||
|
recentSplits: []
|
||||||
|
};
|
||||||
|
let debtData = initialDebtData || {
|
||||||
|
whoOwesMe: [],
|
||||||
|
whoIOwe: [],
|
||||||
|
totalOwedToMe: 0,
|
||||||
|
totalIOwe: 0
|
||||||
|
};
|
||||||
|
let loading = !initialBalance || !initialDebtData; // Only show loading if we don't have initial data
|
||||||
|
let error = null;
|
||||||
|
let singleDebtUser = null;
|
||||||
|
let shouldShowIntegratedView = false;
|
||||||
|
|
||||||
|
function getSingleDebtUser() {
|
||||||
|
const totalUsers = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
||||||
|
|
||||||
|
if (totalUsers === 1) {
|
||||||
|
if (debtData.whoOwesMe.length === 1) {
|
||||||
|
return {
|
||||||
|
type: 'owesMe',
|
||||||
|
user: debtData.whoOwesMe[0],
|
||||||
|
amount: debtData.whoOwesMe[0].netAmount
|
||||||
|
};
|
||||||
|
} else if (debtData.whoIOwe.length === 1) {
|
||||||
|
return {
|
||||||
|
type: 'iOwe',
|
||||||
|
user: debtData.whoIOwe[0],
|
||||||
|
amount: debtData.whoIOwe[0].netAmount
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$: {
|
||||||
|
// Recalculate when debtData changes - trigger on the arrays specifically
|
||||||
|
const totalUsers = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
||||||
|
singleDebtUser = getSingleDebtUser();
|
||||||
|
shouldShowIntegratedView = singleDebtUser !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/cospend/balance');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch balance');
|
||||||
|
}
|
||||||
|
const newBalance = await response.json();
|
||||||
|
// Force reactivity by creating new object with spread arrays
|
||||||
|
balance = {
|
||||||
|
netBalance: newBalance.netBalance || 0,
|
||||||
|
recentSplits: [...(newBalance.recentSplits || [])]
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchDebtBreakdown() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/cospend/debts');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch debt breakdown');
|
||||||
|
}
|
||||||
|
const newDebtData = await response.json();
|
||||||
|
// Force reactivity by creating new object with spread arrays
|
||||||
|
debtData = {
|
||||||
|
whoOwesMe: [...(newDebtData.whoOwesMe || [])],
|
||||||
|
whoIOwe: [...(newDebtData.whoIOwe || [])],
|
||||||
|
totalOwedToMe: newDebtData.totalOwedToMe || 0,
|
||||||
|
totalIOwe: newDebtData.totalIOwe || 0
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCurrency(amount) {
|
||||||
|
return new Intl.NumberFormat('de-CH', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'CHF'
|
||||||
|
}).format(Math.abs(amount));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export refresh method for parent components to call
|
||||||
|
export async function refresh() {
|
||||||
|
loading = true;
|
||||||
|
await Promise.all([fetchBalance(), fetchDebtBreakdown()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="balance-cards">
|
||||||
|
<div class="balance-card net-balance"
|
||||||
|
class:positive={balance.netBalance <= 0}
|
||||||
|
class:negative={balance.netBalance > 0}
|
||||||
|
class:enhanced={shouldShowIntegratedView}>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading-content">
|
||||||
|
<h3>Your Balance</h3>
|
||||||
|
<div class="loading">Loading...</div>
|
||||||
|
</div>
|
||||||
|
{:else if error}
|
||||||
|
<h3>Your Balance</h3>
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if shouldShowIntegratedView}
|
||||||
|
<!-- Enhanced view with single user debt -->
|
||||||
|
<h3>Your Balance</h3>
|
||||||
|
<div class="enhanced-balance">
|
||||||
|
<div class="main-amount">
|
||||||
|
{#if balance.netBalance < 0}
|
||||||
|
<span class="positive">+{formatCurrency(balance.netBalance)}</span>
|
||||||
|
<small>You are owed</small>
|
||||||
|
{:else if balance.netBalance > 0}
|
||||||
|
<span class="negative">-{formatCurrency(balance.netBalance)}</span>
|
||||||
|
<small>You owe</small>
|
||||||
|
{:else}
|
||||||
|
<span class="even">CHF 0.00</span>
|
||||||
|
<small>You're all even</small>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="debt-details">
|
||||||
|
<div class="debt-user">
|
||||||
|
{#if singleDebtUser && singleDebtUser.user}
|
||||||
|
<!-- Debug: ProfilePicture with username: {singleDebtUser.user.username} -->
|
||||||
|
<ProfilePicture username={singleDebtUser.user.username} size={40} />
|
||||||
|
<div class="user-info">
|
||||||
|
<span class="username">{singleDebtUser.user.username}</span>
|
||||||
|
<span class="debt-description">
|
||||||
|
{#if singleDebtUser.type === 'owesMe'}
|
||||||
|
owes you {formatCurrency(singleDebtUser.amount)}
|
||||||
|
{:else}
|
||||||
|
you owe {formatCurrency(singleDebtUser.amount)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div>Debug: No singleDebtUser data</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="transaction-count">
|
||||||
|
{#if singleDebtUser && singleDebtUser.user && singleDebtUser.user.transactions}
|
||||||
|
{singleDebtUser.user.transactions.length} transaction{singleDebtUser.user.transactions.length !== 1 ? 's' : ''}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<!-- Standard balance view -->
|
||||||
|
<h3>Your Balance</h3>
|
||||||
|
<div class="amount">
|
||||||
|
{#if balance.netBalance < 0}
|
||||||
|
<span class="positive">+{formatCurrency(balance.netBalance)}</span>
|
||||||
|
<small>You are owed</small>
|
||||||
|
{:else if balance.netBalance > 0}
|
||||||
|
<span class="negative">-{formatCurrency(balance.netBalance)}</span>
|
||||||
|
<small>You owe</small>
|
||||||
|
{:else}
|
||||||
|
<span class="even">CHF 0.00</span>
|
||||||
|
<small>You're all even</small>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.balance-cards {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card {
|
||||||
|
background: white;
|
||||||
|
padding: 2rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
text-align: center;
|
||||||
|
min-width: 300px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card.enhanced {
|
||||||
|
min-width: 400px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card.net-balance {
|
||||||
|
background: linear-gradient(135deg, #f5f5f5, #e8e8e8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card.net-balance.positive {
|
||||||
|
background: linear-gradient(135deg, #e8f5e8, #d4edda);
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card.net-balance.negative {
|
||||||
|
background: linear-gradient(135deg, #ffeaea, #f8d7da);
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card h3 {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: #555;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-content {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: #d32f2f;
|
||||||
|
background-color: #ffebee;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount {
|
||||||
|
font-size: 2rem;
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount small {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: normal;
|
||||||
|
color: #666;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.enhanced-balance {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-amount {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 1.8rem;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-amount small {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: normal;
|
||||||
|
color: #666;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-details {
|
||||||
|
background: rgba(255, 255, 255, 0.5);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-info {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 600;
|
||||||
|
color: #333;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-description {
|
||||||
|
color: #666;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.transaction-count {
|
||||||
|
color: #666;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.positive {
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.negative {
|
||||||
|
color: #d32f2f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.even {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.balance-card {
|
||||||
|
min-width: unset;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.balance-card.enhanced {
|
||||||
|
min-width: unset;
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-details {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.transaction-count {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
80
src/lib/components/FavoriteButton.svelte
Normal file
80
src/lib/components/FavoriteButton.svelte
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { browser } from '$app/environment';
|
||||||
|
import { enhance } from '$app/forms';
|
||||||
|
|
||||||
|
export let recipeId: string;
|
||||||
|
export let isFavorite: boolean = false;
|
||||||
|
export let isLoggedIn: boolean = false;
|
||||||
|
|
||||||
|
let isLoading = false;
|
||||||
|
|
||||||
|
async function toggleFavorite(event: Event) {
|
||||||
|
// If JavaScript is available, prevent form submission and handle client-side
|
||||||
|
if (browser) {
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
if (!isLoggedIn || isLoading) return;
|
||||||
|
|
||||||
|
isLoading = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const method = isFavorite ? 'DELETE' : 'POST';
|
||||||
|
const response = await fetch('/api/rezepte/favorites', {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ recipeId }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
isFavorite = !isFavorite;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to toggle favorite:', error);
|
||||||
|
} finally {
|
||||||
|
isLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If no JS, form will submit normally
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.favorite-button {
|
||||||
|
all: unset;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: 100ms;
|
||||||
|
filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.5));
|
||||||
|
position: absolute;
|
||||||
|
bottom: 0.5em;
|
||||||
|
right: 0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.favorite-button:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.favorite-button:hover,
|
||||||
|
.favorite-button:focus-visible {
|
||||||
|
transform: scale(1.2);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
{#if isLoggedIn}
|
||||||
|
<form method="post" action="?/toggleFavorite" style="display: inline;" use:enhance>
|
||||||
|
<input type="hidden" name="recipeId" value={recipeId} />
|
||||||
|
<input type="hidden" name="isFavorite" value={isFavorite} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="favorite-button"
|
||||||
|
disabled={isLoading}
|
||||||
|
on:click={toggleFavorite}
|
||||||
|
title={isFavorite ? 'Favorit entfernen' : 'Als Favorit speichern'}
|
||||||
|
>
|
||||||
|
{isFavorite ? '❤️' : '🖤'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
38
src/lib/components/FormSection.svelte
Normal file
38
src/lib/components/FormSection.svelte
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
<script>
|
||||||
|
export let title = '';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
{#if title}
|
||||||
|
<h2>{title}</h2>
|
||||||
|
{/if}
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,19 +1,39 @@
|
|||||||
<script>
|
<script>
|
||||||
// get ingredients_store from IngredientsPage.svelte
|
import { createEventDispatcher } from 'svelte';
|
||||||
import ingredients_store from './IngredientsPage.svelte';
|
import { browser } from '$app/environment';
|
||||||
let ingredients = [];
|
import { enhance } from '$app/forms';
|
||||||
ingredients_store.subscribe(value => {
|
import { page } from '$app/stores';
|
||||||
ingredients = value;
|
|
||||||
});
|
export let item;
|
||||||
function toggleHefe(){
|
export let multiplier = 1;
|
||||||
if(data.ingredients[i].list[j].name == "Frischhefe"){
|
export let yeastId = 0;
|
||||||
data.ingredients[i].list[j].name = "Trockenhefe"
|
|
||||||
data.ingredients[i].list[j].amount = item.amount / 3
|
const dispatch = createEventDispatcher();
|
||||||
}
|
|
||||||
else{
|
// Get all current URL parameters to preserve state
|
||||||
item.name = "Frischhefe"
|
$: currentParams = browser ? new URLSearchParams(window.location.search) : $page.url.searchParams;
|
||||||
item.amount = item.amount * 3
|
|
||||||
|
function toggleHefe(event) {
|
||||||
|
// If JavaScript is available, prevent form submission and handle client-side
|
||||||
|
if (browser) {
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
// Simply toggle the yeast flag in the URL
|
||||||
|
const url = new URL(window.location);
|
||||||
|
const yeastParam = `y${yeastId}`;
|
||||||
|
|
||||||
|
if (url.searchParams.has(yeastParam)) {
|
||||||
|
url.searchParams.delete(yeastParam);
|
||||||
|
} else {
|
||||||
|
url.searchParams.set(yeastParam, '1');
|
||||||
|
}
|
||||||
|
|
||||||
|
window.history.replaceState({}, '', url);
|
||||||
|
|
||||||
|
// Trigger page reload to recalculate ingredients server-side
|
||||||
|
window.location.reload();
|
||||||
}
|
}
|
||||||
|
// If no JS, form will submit normally
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
<style>
|
<style>
|
||||||
@@ -28,7 +48,13 @@
|
|||||||
fill: var(--blue);
|
fill: var(--blue);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<button onclick={toggleHefe}>
|
<form method="post" action="?/swapYeast" style="display: inline;" use:enhance>
|
||||||
{item.amount} {item.unit} {item.name}
|
<input type="hidden" name="yeastId" value={yeastId} />
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.6.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"/></svg>
|
<!-- Include all current URL parameters to preserve state -->
|
||||||
</button>
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
|
<input type="hidden" name="currentParam_{key}" value={value} />
|
||||||
|
{/each}
|
||||||
|
<button type="submit" on:click={toggleHefe} title="Zwischen Frischhefe und Trockenhefe wechseln">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--!Font Awesome Free 6.6.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"/></svg>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|||||||
@@ -72,7 +72,7 @@
|
|||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
<section>
|
<section>
|
||||||
<Search></Search>
|
<Search icon={active_icon}></Search>
|
||||||
</section>
|
</section>
|
||||||
<section>
|
<section>
|
||||||
<slot name=recipes></slot>
|
<slot name=recipes></slot>
|
||||||
|
|||||||
247
src/lib/components/ImageUpload.svelte
Normal file
247
src/lib/components/ImageUpload.svelte
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
<script>
|
||||||
|
export let imagePreview = '';
|
||||||
|
export let imageFile = null;
|
||||||
|
export let uploading = false;
|
||||||
|
export let currentImage = null; // For edit mode
|
||||||
|
export let title = 'Receipt Image';
|
||||||
|
|
||||||
|
// Events
|
||||||
|
import { createEventDispatcher } from 'svelte';
|
||||||
|
const dispatch = createEventDispatcher();
|
||||||
|
|
||||||
|
function handleImageChange(event) {
|
||||||
|
const file = event.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
|
dispatch('error', 'File size must be less than 5MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
dispatch('error', 'Please select a valid image file (JPEG, PNG, WebP)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
imageFile = file;
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (e) => {
|
||||||
|
imagePreview = e.target.result;
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
|
||||||
|
dispatch('imageSelected', file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeImage() {
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
currentImage = null;
|
||||||
|
dispatch('imageRemoved');
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeCurrentImage() {
|
||||||
|
currentImage = null;
|
||||||
|
dispatch('currentImageRemoved');
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>{title}</h2>
|
||||||
|
|
||||||
|
{#if currentImage}
|
||||||
|
<div class="current-image">
|
||||||
|
<img src={currentImage} alt="Receipt" class="receipt-preview" />
|
||||||
|
<div class="image-actions">
|
||||||
|
<button type="button" class="btn-remove" on:click={removeCurrentImage}>
|
||||||
|
Remove Image
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if imagePreview}
|
||||||
|
<div class="image-preview">
|
||||||
|
<img src={imagePreview} alt="Receipt preview" />
|
||||||
|
<button type="button" class="remove-image" on:click={removeImage}>
|
||||||
|
Remove Image
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="image-upload">
|
||||||
|
<label for="image" class="upload-label">
|
||||||
|
<div class="upload-content">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/>
|
||||||
|
<line x1="16" y1="5" x2="22" y2="5"/>
|
||||||
|
<line x1="19" y1="2" x2="19" y2="8"/>
|
||||||
|
</svg>
|
||||||
|
<p>{currentImage ? 'Replace Image' : 'Upload Receipt Image'}</p>
|
||||||
|
<small>JPEG, PNG, WebP (max 5MB)</small>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
id="image"
|
||||||
|
accept="image/jpeg,image/jpg,image/png,image/webp"
|
||||||
|
on:change={handleImageChange}
|
||||||
|
disabled={uploading}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if uploading}
|
||||||
|
<div class="upload-status">Uploading image...</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload {
|
||||||
|
border: 2px dashed var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload:hover {
|
||||||
|
border-color: var(--blue);
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.image-upload {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-label {
|
||||||
|
cursor: pointer;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content svg {
|
||||||
|
color: var(--nord3);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content p {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content small {
|
||||||
|
color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.upload-content svg {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content p {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-content small {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview img {
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 300px;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-image, .btn-remove {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-image:hover, .btn-remove:hover {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.current-image {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-preview {
|
||||||
|
max-width: 200px;
|
||||||
|
max-height: 200px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
display: block;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.receipt-preview {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.upload-status {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,20 +1,94 @@
|
|||||||
<script>
|
<script>
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { onNavigate } from "$app/navigation";
|
import { onNavigate } from "$app/navigation";
|
||||||
|
import { browser } from '$app/environment';
|
||||||
|
import { page } from '$app/stores';
|
||||||
|
import HefeSwapper from './HefeSwapper.svelte';
|
||||||
export let data
|
export let data
|
||||||
let multiplier;
|
let multiplier = data.multiplier || 1;
|
||||||
let custom_mul = "…"
|
|
||||||
|
|
||||||
|
// Calculate yeast IDs for each yeast ingredient
|
||||||
|
let yeastIds = {};
|
||||||
|
$: {
|
||||||
|
yeastIds = {};
|
||||||
|
let yeastCounter = 0;
|
||||||
|
if (data.ingredients) {
|
||||||
|
for (let listIndex = 0; listIndex < data.ingredients.length; listIndex++) {
|
||||||
|
const list = data.ingredients[listIndex];
|
||||||
|
if (list.list) {
|
||||||
|
for (let ingredientIndex = 0; ingredientIndex < list.list.length; ingredientIndex++) {
|
||||||
|
const ingredient = list.list[ingredientIndex];
|
||||||
|
if (ingredient.name === "Frischhefe" || ingredient.name === "Trockenhefe") {
|
||||||
|
yeastIds[`${listIndex}-${ingredientIndex}`] = yeastCounter++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all current URL parameters to preserve state in multiplier forms
|
||||||
|
$: currentParams = browser ? new URLSearchParams(window.location.search) : $page.url.searchParams;
|
||||||
|
|
||||||
|
// Progressive enhancement - use JS if available
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
// Apply multiplier from URL
|
if (browser) {
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
multiplier = urlParams.get('multiplier') || 1;
|
multiplier = parseFloat(urlParams.get('multiplier')) || 1;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
onNavigate(() => {
|
onNavigate(() => {
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
if (browser) {
|
||||||
multiplier = urlParams.get('multiplier') || 1;
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
multiplier = parseFloat(urlParams.get('multiplier')) || 1;
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function handleMultiplierClick(event, value) {
|
||||||
|
if (browser) {
|
||||||
|
event.preventDefault();
|
||||||
|
multiplier = value;
|
||||||
|
|
||||||
|
// Update URL without reloading
|
||||||
|
const url = new URL(window.location);
|
||||||
|
if (value === 1) {
|
||||||
|
url.searchParams.delete('multiplier');
|
||||||
|
} else {
|
||||||
|
url.searchParams.set('multiplier', value);
|
||||||
|
}
|
||||||
|
window.history.replaceState({}, '', url);
|
||||||
|
}
|
||||||
|
// If no JS, form will submit normally
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCustomInput(event) {
|
||||||
|
if (browser) {
|
||||||
|
const value = parseFloat(event.target.value);
|
||||||
|
if (!isNaN(value) && value > 0) {
|
||||||
|
multiplier = value;
|
||||||
|
|
||||||
|
// Update URL without reloading
|
||||||
|
const url = new URL(window.location);
|
||||||
|
if (value === 1) {
|
||||||
|
url.searchParams.delete('multiplier');
|
||||||
|
} else {
|
||||||
|
url.searchParams.set('multiplier', value);
|
||||||
|
}
|
||||||
|
window.history.replaceState({}, '', url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCustomSubmit(event) {
|
||||||
|
if (browser) {
|
||||||
|
event.preventDefault();
|
||||||
|
// Value already updated by handleCustomInput
|
||||||
|
}
|
||||||
|
// If no JS, form will submit normally
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function convertFloatsToFractions(inputString) {
|
function convertFloatsToFractions(inputString) {
|
||||||
// Split the input string into individual words
|
// Split the input string into individual words
|
||||||
const words = inputString.split(' ');
|
const words = inputString.split(' ');
|
||||||
@@ -103,22 +177,8 @@ function adjust_amount(string, multiplier){
|
|||||||
return temp
|
return temp
|
||||||
}
|
}
|
||||||
|
|
||||||
function apply_if_not_NaN(custom){
|
|
||||||
const multipliers = [0.5, 1, 1.5, 2, 3]
|
// No need for complex yeast toggle handling - everything is calculated server-side now
|
||||||
if((!isNaN(custom * 1)) && custom != ""){
|
|
||||||
if(multipliers.includes(parseFloat(custom))){
|
|
||||||
multiplier = custom
|
|
||||||
custom_mul = "…"
|
|
||||||
}
|
|
||||||
else{
|
|
||||||
custom_mul = convertFloatsToFractions(custom)
|
|
||||||
multiplier = custom
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else{
|
|
||||||
custom_mul = "…"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
<style>
|
<style>
|
||||||
*{
|
*{
|
||||||
@@ -192,9 +252,67 @@ span
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
.multipliers button:last-child{
|
.custom-multiplier {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
min-width: 2em;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
border-radius: 0.3rem;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: 100ms;
|
||||||
|
color: var(--nord0);
|
||||||
|
background-color: var(--nord5);
|
||||||
|
box-shadow: 0px 0px 0.4em 0.05em rgba(0,0,0, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-input {
|
||||||
|
width: 3em;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
text-align: center;
|
||||||
|
color: inherit;
|
||||||
|
font-size: inherit;
|
||||||
|
outline: none;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Remove number input arrows */
|
||||||
|
.custom-input::-webkit-outer-spin-button,
|
||||||
|
.custom-input::-webkit-inner-spin-button {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-input[type=number] {
|
||||||
|
-moz-appearance: textfield;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-button {
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font-size: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark){
|
||||||
|
.custom-multiplier {
|
||||||
|
color: var(--tag-font);
|
||||||
|
background-color: var(--nord6-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-multiplier:hover,
|
||||||
|
.custom-multiplier:focus-within {
|
||||||
|
scale: 1.2;
|
||||||
|
background-color: var(--orange);
|
||||||
|
box-shadow: 0px 0px 0.5em 0.1em rgba(0,0,0, 0.3);
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
{#if data.ingredients}
|
{#if data.ingredients}
|
||||||
@@ -206,33 +324,86 @@ span
|
|||||||
|
|
||||||
<h3>Menge anpassen:</h3>
|
<h3>Menge anpassen:</h3>
|
||||||
<div class=multipliers>
|
<div class=multipliers>
|
||||||
<button class:selected={multiplier==0.5} on:click={() => multiplier=0.5}><sup>1</sup>⁄<sub>2</sub>x</button>
|
<form method="get" style="display: inline;">
|
||||||
<button class:selected={multiplier==1} on:click={() => {multiplier=1; custom_mul="…"}}>1x</button>
|
<input type="hidden" name="multiplier" value="0.5" />
|
||||||
<button class:selected={multiplier==1.5} on:click={() => {multiplier=1.5; custom_mul="…"}}><sup>3</sup>⁄<sub>2</sub>x</button>
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
<button class:selected={multiplier==2} on:click="{() => {multiplier=2; custom_mul="…"}}">2x</button>
|
{#if key !== 'multiplier'}
|
||||||
<button class:selected={multiplier==3} on:click="{() => {multiplier=3; custom_mul="…"}}">3x</button>
|
<input type="hidden" name={key} value={value} />
|
||||||
<button class:selected={multiplier==custom_mul} on:click={(e) => { const el = e.composedPath()[0].children[0]; if(el){ el.focus()}}}>
|
{/if}
|
||||||
<span class:selected={multiplier==custom_mul}
|
{/each}
|
||||||
on:focus={() => { custom_mul="" }
|
<button type="submit" class:selected={multiplier==0.5} on:click={(e) => handleMultiplierClick(e, 0.5)}>{@html "<sup>1</sup>/<sub>2</sub>x"}</button>
|
||||||
}
|
</form>
|
||||||
on:blur="{() => { apply_if_not_NaN(custom_mul);
|
<form method="get" style="display: inline;">
|
||||||
if(custom_mul == "")
|
<input type="hidden" name="multiplier" value="1" />
|
||||||
{custom_mul = "…"}
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
}}"
|
{#if key !== 'multiplier'}
|
||||||
bind:innerHTML={custom_mul}
|
<input type="hidden" name={key} value={value} />
|
||||||
contenteditable > </span>
|
{/if}
|
||||||
x
|
{/each}
|
||||||
</button>
|
<button type="submit" class:selected={multiplier==1} on:click={(e) => handleMultiplierClick(e, 1)}>1x</button>
|
||||||
|
</form>
|
||||||
|
<form method="get" style="display: inline;">
|
||||||
|
<input type="hidden" name="multiplier" value="1.5" />
|
||||||
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
|
{#if key !== 'multiplier'}
|
||||||
|
<input type="hidden" name={key} value={value} />
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
<button type="submit" class:selected={multiplier==1.5} on:click={(e) => handleMultiplierClick(e, 1.5)}>{@html "<sup>3</sup>/<sub>2</sub>x"}</button>
|
||||||
|
</form>
|
||||||
|
<form method="get" style="display: inline;">
|
||||||
|
<input type="hidden" name="multiplier" value="2" />
|
||||||
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
|
{#if key !== 'multiplier'}
|
||||||
|
<input type="hidden" name={key} value={value} />
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
<button type="submit" class:selected={multiplier==2} on:click={(e) => handleMultiplierClick(e, 2)}>2x</button>
|
||||||
|
</form>
|
||||||
|
<form method="get" style="display: inline;">
|
||||||
|
<input type="hidden" name="multiplier" value="3" />
|
||||||
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
|
{#if key !== 'multiplier'}
|
||||||
|
<input type="hidden" name={key} value={value} />
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
<button type="submit" class:selected={multiplier==3} on:click={(e) => handleMultiplierClick(e, 3)}>3x</button>
|
||||||
|
</form>
|
||||||
|
<form method="get" style="display: inline;" class="custom-multiplier" on:submit={handleCustomSubmit}>
|
||||||
|
{#each Array.from(currentParams.entries()) as [key, value]}
|
||||||
|
{#if key !== 'multiplier'}
|
||||||
|
<input type="hidden" name={key} value={value} />
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
name="multiplier"
|
||||||
|
pattern="[0-9]+(\.[0-9]*)?"
|
||||||
|
title="Enter a positive number (e.g., 2.5, 0.75, 3.14)"
|
||||||
|
placeholder="…"
|
||||||
|
class="custom-input"
|
||||||
|
value={multiplier != 0.5 && multiplier != 1 && multiplier != 1.5 && multiplier != 2 && multiplier != 3 ? multiplier : ''}
|
||||||
|
on:input={handleCustomInput}
|
||||||
|
/>
|
||||||
|
<button type="submit" class="custom-button">x</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2>Zutaten</h2>
|
<h2>Zutaten</h2>
|
||||||
{#each data.ingredients as list}
|
{#each data.ingredients as list, listIndex}
|
||||||
{#if list.name}
|
{#if list.name}
|
||||||
<h3>{list.name}</h3>
|
<h3>{list.name}</h3>
|
||||||
{/if}
|
{/if}
|
||||||
<div class=ingredients_grid>
|
<div class=ingredients_grid>
|
||||||
{#each list.list as item}
|
{#each list.list as item, ingredientIndex}
|
||||||
<div class=amount>{@html adjust_amount(item.amount, multiplier)} {item.unit}</div><div class=name>{@html item.name.replace("{{multiplier}}", multiplier * item.amount)}</div>
|
<div class=amount>{@html adjust_amount(item.amount, multiplier)} {item.unit}</div>
|
||||||
|
<div class=name>
|
||||||
|
{@html item.name.replace("{{multiplier}}", isNaN(parseFloat(item.amount)) ? multiplier : multiplier * parseFloat(item.amount))}
|
||||||
|
{#if item.name === "Frischhefe" || item.name === "Trockenhefe"}
|
||||||
|
{@const yeastId = yeastIds[`${listIndex}-${ingredientIndex}`] ?? 0}
|
||||||
|
<HefeSwapper {item} {multiplier} {yeastId} />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
|
|||||||
644
src/lib/components/PaymentModal.svelte
Normal file
644
src/lib/components/PaymentModal.svelte
Normal file
@@ -0,0 +1,644 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount, createEventDispatcher } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import { page } from '$app/stores';
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
import EditButton from './EditButton.svelte';
|
||||||
|
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||||
|
|
||||||
|
export let paymentId;
|
||||||
|
|
||||||
|
// Get session from page store
|
||||||
|
$: session = $page.data?.session;
|
||||||
|
|
||||||
|
const dispatch = createEventDispatcher();
|
||||||
|
|
||||||
|
let payment = null;
|
||||||
|
let loading = true;
|
||||||
|
let error = null;
|
||||||
|
let modal;
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
await loadPayment();
|
||||||
|
|
||||||
|
// Handle escape key to close modal
|
||||||
|
function handleKeydown(event) {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleKeydown);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('keydown', handleKeydown);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadPayment() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/cospend/payments/${paymentId}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to load payment');
|
||||||
|
}
|
||||||
|
const result = await response.json();
|
||||||
|
payment = result.payment;
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
// Use shallow routing to go back to dashboard without full navigation
|
||||||
|
goto('/cospend', { replaceState: true, noScroll: true, keepFocus: true });
|
||||||
|
dispatch('close');
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleBackdropClick(event) {
|
||||||
|
if (event.target === event.currentTarget) {
|
||||||
|
closeModal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSplitDescription(payment) {
|
||||||
|
if (!payment.splits || payment.splits.length === 0) return 'No splits';
|
||||||
|
|
||||||
|
if (payment.splitMethod === 'equal') {
|
||||||
|
return `Split equally among ${payment.splits.length} people`;
|
||||||
|
} else if (payment.splitMethod === 'full') {
|
||||||
|
return `Paid in full by ${payment.paidBy}`;
|
||||||
|
} else if (payment.splitMethod === 'personal_equal') {
|
||||||
|
return `Personal amounts + equal split among ${payment.splits.length} people`;
|
||||||
|
} else {
|
||||||
|
return `Custom split among ${payment.splits.length} people`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let deleting = false;
|
||||||
|
|
||||||
|
async function deletePayment() {
|
||||||
|
if (!confirm('Are you sure you want to delete this payment? This action cannot be undone.')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
deleting = true;
|
||||||
|
const response = await fetch(`/api/cospend/payments/${paymentId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close modal and dispatch event to refresh data
|
||||||
|
dispatch('paymentDeleted', paymentId);
|
||||||
|
closeModal();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
deleting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="panel-content" bind:this={modal}>
|
||||||
|
<div class="panel-header">
|
||||||
|
<h2>Payment Details</h2>
|
||||||
|
<button class="close-button" on:click={closeModal} aria-label="Close modal">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel-body">
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading payment...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if payment}
|
||||||
|
<div class="payment-details">
|
||||||
|
<div class="payment-header">
|
||||||
|
<div class="title-section">
|
||||||
|
<div class="title-with-category">
|
||||||
|
<span class="category-emoji">{getCategoryEmoji(payment.category || 'groceries')}</span>
|
||||||
|
<h1>{payment.title}</h1>
|
||||||
|
</div>
|
||||||
|
<div class="payment-amount">
|
||||||
|
{formatCurrency(payment.amount)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if payment.image}
|
||||||
|
<div class="receipt-image">
|
||||||
|
<img src={payment.image} alt="Receipt" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="payment-info">
|
||||||
|
<div class="info-grid">
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Date:</span>
|
||||||
|
<span class="value">{formatDate(payment.date)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Paid by:</span>
|
||||||
|
<span class="value">{payment.paidBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Created by:</span>
|
||||||
|
<span class="value">{payment.createdBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Category:</span>
|
||||||
|
<span class="value">{getCategoryName(payment.category || 'groceries')}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Split method:</span>
|
||||||
|
<span class="value">{getSplitDescription(payment)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.description}
|
||||||
|
<div class="description">
|
||||||
|
<h3>Description</h3>
|
||||||
|
<p>{payment.description}</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.splits && payment.splits.length > 0}
|
||||||
|
<div class="splits-section">
|
||||||
|
<h3>Split Details</h3>
|
||||||
|
<div class="splits-list">
|
||||||
|
{#each payment.splits as split}
|
||||||
|
<div class="split-item" class:current-user={split.username === session?.user?.nickname}>
|
||||||
|
<div class="split-user">
|
||||||
|
<ProfilePicture username={split.username} size={24} />
|
||||||
|
<div class="user-info">
|
||||||
|
<span class="username">{split.username}</span>
|
||||||
|
{#if split.username === session?.user?.nickname}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div 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}
|
||||||
|
owed {formatCurrency(split.amount)}
|
||||||
|
{:else}
|
||||||
|
even
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="panel-actions">
|
||||||
|
{#if payment && payment.createdBy === session?.user?.nickname}
|
||||||
|
<button
|
||||||
|
class="btn-danger"
|
||||||
|
on:click={deletePayment}
|
||||||
|
disabled={deleting}
|
||||||
|
>
|
||||||
|
{deleting ? 'Deleting...' : 'Delete Payment'}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
<button class="btn-secondary" on:click={closeModal}>Close</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment && payment.createdBy === session?.user?.nickname}
|
||||||
|
<EditButton href="/cospend/payments/edit/{paymentId}" />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.panel-content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
background: var(--nord6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--nord4);
|
||||||
|
background: var(--nord5);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.close-button {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.5rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.close-button:hover {
|
||||||
|
background: var(--nord4);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-body {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-details {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 1.5rem;
|
||||||
|
background: linear-gradient(135deg, var(--nord5), var(--nord4));
|
||||||
|
border-bottom: 1px solid var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category .category-emoji {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-section h1 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-amount {
|
||||||
|
font-size: 1.25rem;
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-left: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image img {
|
||||||
|
max-width: 100px;
|
||||||
|
max-height: 100px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-info {
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-item {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
padding-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description h3 {
|
||||||
|
margin: 0 0 0.75rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord2);
|
||||||
|
line-height: 1.5;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section {
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section h3 {
|
||||||
|
margin: 0 0 1rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item.current-user {
|
||||||
|
background: var(--nord8);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user .user-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.375rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-actions {
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
background: var(--nord5);
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary, .btn-secondary, .btn-danger {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover:not(:disabled) {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.panel-content {
|
||||||
|
background: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-header {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-bottom-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-header h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.close-button {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.close-button:hover {
|
||||||
|
background: var(--nord3);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-header {
|
||||||
|
background: linear-gradient(135deg, var(--nord2), var(--nord3));
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-section h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image img {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
|
border-top-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.description h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.description p {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section {
|
||||||
|
border-top-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item.current-user {
|
||||||
|
background: var(--nord3);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-actions {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-top-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.payment-header {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
66
src/lib/components/ProfilePicture.svelte
Normal file
66
src/lib/components/ProfilePicture.svelte
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
<script>
|
||||||
|
export let username;
|
||||||
|
export let size = 40; // Default size in pixels
|
||||||
|
export let alt = '';
|
||||||
|
|
||||||
|
let imageError = false;
|
||||||
|
|
||||||
|
$: profileUrl = `https://bocken.org/static/user/full/${username}.webp`;
|
||||||
|
$: altText = alt || `${username}'s profile picture`;
|
||||||
|
|
||||||
|
function handleError() {
|
||||||
|
imageError = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getInitials(name) {
|
||||||
|
if (!name) return '?';
|
||||||
|
return name.split(' ')
|
||||||
|
.map(word => word.charAt(0))
|
||||||
|
.join('')
|
||||||
|
.toUpperCase()
|
||||||
|
.substring(0, 2);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="profile-picture" style="width: {size}px; height: {size}px;">
|
||||||
|
{#if !imageError}
|
||||||
|
<img
|
||||||
|
src={profileUrl}
|
||||||
|
alt={altText}
|
||||||
|
on:error={handleError}
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="fallback">
|
||||||
|
{getInitials(username)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.profile-picture {
|
||||||
|
border-radius: 50%;
|
||||||
|
overflow: hidden;
|
||||||
|
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fallback {
|
||||||
|
color: white;
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 0.75em;
|
||||||
|
text-align: center;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,81 +1,128 @@
|
|||||||
<script>
|
<script>
|
||||||
import {onMount} from "svelte";
|
import {onMount} from "svelte";
|
||||||
|
import { browser } from '$app/environment';
|
||||||
import "$lib/css/nordtheme.css";
|
import "$lib/css/nordtheme.css";
|
||||||
|
|
||||||
|
// Filter props for different contexts
|
||||||
|
export let category = null;
|
||||||
|
export let tag = null;
|
||||||
|
export let icon = null;
|
||||||
|
export let season = null;
|
||||||
|
export let favoritesOnly = false;
|
||||||
|
export let searchResultsUrl = '/rezepte/search';
|
||||||
|
|
||||||
|
let searchQuery = '';
|
||||||
|
|
||||||
|
// Build search URL with current filters
|
||||||
|
function buildSearchUrl(query) {
|
||||||
|
if (browser) {
|
||||||
|
const url = new URL(searchResultsUrl, window.location.origin);
|
||||||
|
if (query) url.searchParams.set('q', query);
|
||||||
|
if (category) url.searchParams.set('category', category);
|
||||||
|
if (tag) url.searchParams.set('tag', tag);
|
||||||
|
if (icon) url.searchParams.set('icon', icon);
|
||||||
|
if (season) url.searchParams.set('season', season);
|
||||||
|
if (favoritesOnly) url.searchParams.set('favorites', 'true');
|
||||||
|
return url.toString();
|
||||||
|
} else {
|
||||||
|
// Server-side fallback - return just the base path
|
||||||
|
return searchResultsUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSubmit(event) {
|
||||||
|
if (browser) {
|
||||||
|
// For JS-enabled browsers, prevent default and navigate programmatically
|
||||||
|
// This allows for future enhancements like instant search
|
||||||
|
const url = buildSearchUrl(searchQuery);
|
||||||
|
window.location.href = url;
|
||||||
|
}
|
||||||
|
// If no JS, form will submit normally
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSearch() {
|
||||||
|
searchQuery = '';
|
||||||
|
if (browser) {
|
||||||
|
// Reset any client-side filtering if present
|
||||||
|
const recipes = document.querySelectorAll(".search_me");
|
||||||
|
recipes.forEach(recipe => {
|
||||||
|
recipe.style.display = 'flex';
|
||||||
|
recipe.classList.remove("matched-recipe");
|
||||||
|
});
|
||||||
|
document.querySelectorAll(".media_scroller_wrapper").forEach( scroller => {
|
||||||
|
scroller.style.display= 'block'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const recipes = document.querySelectorAll(".search_me");
|
// Swap buttons for JS-enabled experience
|
||||||
const search = document.getElementById("search");
|
const submitButton = document.getElementById('submit-search');
|
||||||
const clearSearch = document.getElementById("clear-search");
|
const clearButton = document.getElementById('clear-search');
|
||||||
|
|
||||||
|
if (submitButton && clearButton) {
|
||||||
|
submitButton.style.display = 'none';
|
||||||
|
clearButton.style.display = 'flex';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get initial search value from URL if present
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const urlQuery = urlParams.get('q');
|
||||||
|
if (urlQuery) {
|
||||||
|
searchQuery = urlQuery;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enhanced client-side filtering (existing functionality)
|
||||||
|
const recipes = document.querySelectorAll(".search_me");
|
||||||
|
const search = document.getElementById("search");
|
||||||
|
|
||||||
|
if (recipes.length > 0 && search) {
|
||||||
|
function do_search(click_only_result=false){
|
||||||
|
const searchText = search.value.toLowerCase().trim().normalize('NFD').replace(/\p{Diacritic}/gu, "");
|
||||||
|
const searchTerms = searchText.split(" ");
|
||||||
|
const hasFilter = searchText.length > 0;
|
||||||
|
|
||||||
function do_search(click_only_result=false){
|
let scrollers_with_results = [];
|
||||||
// grab search input value
|
let scrollers = [];
|
||||||
const searchText = search.value.toLowerCase().trim().normalize('NFD').replace(/\p{Diacritic}/gu, "");
|
|
||||||
const searchTerms = searchText.split(" ");
|
recipes.forEach(recipe => {
|
||||||
const hasFilter = searchText.length > 0;
|
const searchString = `${recipe.textContent} ${recipe.dataset.tags}`.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, "").replace(/­|/g, '');
|
||||||
|
const isMatch = searchTerms.every(term => searchString.includes(term));
|
||||||
|
|
||||||
let scrollers_with_results = [];
|
recipe.style.display = (isMatch ? 'flex' : 'none');
|
||||||
let scrollers = [];
|
recipe.classList.toggle("matched-recipe", hasFilter && isMatch);
|
||||||
// for each recipe hide all but matched
|
if(!scrollers.includes(recipe.parentNode)){
|
||||||
recipes.forEach(recipe => {
|
scrollers.push(recipe.parentNode)
|
||||||
const searchString = `${recipe.textContent} ${recipe.dataset.tags}`.toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, "").replace(/­|/g, '');
|
}
|
||||||
const isMatch = searchTerms.every(term => searchString.includes(term));
|
if(!scrollers_with_results.includes(recipe.parentNode) && isMatch){
|
||||||
|
scrollers_with_results.push(recipe.parentNode)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
scrollers_with_results.forEach( scroller => {
|
||||||
|
scroller.parentNode.style.display= 'block'
|
||||||
|
})
|
||||||
|
scrollers.filter(item => !scrollers_with_results.includes(item)).forEach( scroller => {
|
||||||
|
scroller.parentNode.style.display= 'none'
|
||||||
|
})
|
||||||
|
|
||||||
|
let items = document.querySelectorAll(".matched-recipe");
|
||||||
|
items = [...new Set(items)]
|
||||||
|
if(click_only_result && scrollers_with_results.length == 1 && items.length == 1){
|
||||||
|
items[0].click();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
recipe.style.display = (isMatch ? 'flex' : 'none');
|
search.addEventListener("input", () => {
|
||||||
recipe.classList.toggle("matched-recipe", hasFilter && isMatch);
|
searchQuery = search.value;
|
||||||
if(!scrollers.includes(recipe.parentNode)){
|
do_search();
|
||||||
scrollers.push(recipe.parentNode)
|
})
|
||||||
}
|
|
||||||
if(!scrollers_with_results.includes(recipe.parentNode) && isMatch){
|
// Initial search if URL had query
|
||||||
scrollers_with_results.push(recipe.parentNode)
|
if (urlQuery) {
|
||||||
}
|
do_search(true);
|
||||||
})
|
}
|
||||||
scrollers_with_results.forEach( scroller => {
|
}
|
||||||
scroller.parentNode.style.display= 'block'
|
});
|
||||||
})
|
|
||||||
scrollers.filter(item => !scrollers_with_results.includes(item)).forEach( scroller => {
|
|
||||||
scroller.parentNode.style.display= 'none'
|
|
||||||
})
|
|
||||||
scroll
|
|
||||||
let items = document.querySelectorAll(".matched-recipe");
|
|
||||||
items = [...new Set(items)] // make unique as seasonal mediascroller can lead to duplicates
|
|
||||||
// if only one result and click_only_result is true, click it
|
|
||||||
if(click_only_result && scrollers_with_results.length == 1 && items.length == 1){
|
|
||||||
// add '/rezepte' to history to not force-redirect back to recipe if going back
|
|
||||||
items[0].click();
|
|
||||||
}
|
|
||||||
// if scrollers with results are presenet scroll first result into view
|
|
||||||
/*if(scrollers_with_results.length > 0){
|
|
||||||
scrollers_with_results[0].scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
|
|
||||||
}*/ // For now disabled because it is annoying on mobile
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
search.addEventListener("input", () => {
|
|
||||||
do_search();
|
|
||||||
})
|
|
||||||
|
|
||||||
clearSearch.addEventListener("click", () => {
|
|
||||||
search.value = "";
|
|
||||||
recipes.forEach(recipe => {
|
|
||||||
recipe.style.display = 'flex';
|
|
||||||
recipe.classList.remove("matched-recipe");
|
|
||||||
})
|
|
||||||
document.querySelectorAll(".media_scroller_wrapper").forEach( scroller => {
|
|
||||||
scroller.style.display= 'block'
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
let paramString = window.location.href.split('?')[1];
|
|
||||||
let queryString = new URLSearchParams(paramString);
|
|
||||||
|
|
||||||
for (let pair of queryString.entries()) {
|
|
||||||
if(pair[0] == 'q'){
|
|
||||||
const search = document.getElementById("search");
|
|
||||||
search.value=pair[1];
|
|
||||||
do_search(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
<style>
|
<style>
|
||||||
@@ -110,7 +157,7 @@ input::placeholder{
|
|||||||
scale: 1.02 1.02;
|
scale: 1.02 1.02;
|
||||||
filter: drop-shadow(0.4em 0.5em 1em rgba(0,0,0,0.6))
|
filter: drop-shadow(0.4em 0.5em 1em rgba(0,0,0,0.6))
|
||||||
}
|
}
|
||||||
button#clear-search {
|
.search-button {
|
||||||
all: unset;
|
all: unset;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
@@ -123,17 +170,35 @@ button#clear-search {
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: color 180ms ease-in-out;
|
transition: color 180ms ease-in-out;
|
||||||
}
|
}
|
||||||
button#clear-search:hover {
|
.search-button:hover {
|
||||||
color: white;
|
color: white;
|
||||||
scale: 1.1 1.1;
|
scale: 1.1 1.1;
|
||||||
}
|
}
|
||||||
button#clear-search:active{
|
.search-button:active{
|
||||||
transition: 50ms;
|
transition: 50ms;
|
||||||
scale: 0.8 0.8;
|
scale: 0.8 0.8;
|
||||||
}
|
}
|
||||||
|
.search-button svg {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
<div class="search js-only">
|
<form class="search" method="get" action={buildSearchUrl('')} on:submit|preventDefault={handleSubmit}>
|
||||||
<input type="text" id="search" placeholder="Suche...">
|
{#if category}<input type="hidden" name="category" value={category} />{/if}
|
||||||
<button id="clear-search">
|
{#if tag}<input type="hidden" name="tag" value={tag} />{/if}
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Sucheintrag löschen</title><path d="M135.19 390.14a28.79 28.79 0 0021.68 9.86h246.26A29 29 0 00432 371.13V140.87A29 29 0 00403.13 112H156.87a28.84 28.84 0 00-21.67 9.84v0L46.33 256l88.86 134.11z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"></path><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M336.67 192.33L206.66 322.34M336.67 322.34L206.66 192.33M336.67 192.33L206.66 322.34M336.67 322.34L206.66 192.33"></path></svg></button>
|
{#if icon}<input type="hidden" name="icon" value={icon} />{/if}
|
||||||
</div>
|
{#if season}<input type="hidden" name="season" value={season} />{/if}
|
||||||
|
{#if favoritesOnly}<input type="hidden" name="favorites" value="true" />{/if}
|
||||||
|
|
||||||
|
<input type="text" id="search" name="q" placeholder="Suche..." bind:value={searchQuery}>
|
||||||
|
|
||||||
|
<!-- Submit button (visible by default, hidden when JS loads) -->
|
||||||
|
<button type="submit" id="submit-search" class="search-button" style="display: flex;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512" style="width: 100%; height: 100%;"><title>Suchen</title><path d="M221.09 64a157.09 157.09 0 10157.09 157.09A157.1 157.1 0 00221.09 64z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"></path><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32" d="m338.29 338.29 105.25 105.25"></path></svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Clear button (hidden by default, shown when JS loads) -->
|
||||||
|
<button type="button" id="clear-search" class="search-button js-only" style="display: none;" on:click={clearSearch}>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Sucheintrag löschen</title><path d="M135.19 390.14a28.79 28.79 0 0021.68 9.86h246.26A29 29 0 00432 371.13V140.87A29 29 0 00403.13 112H156.87a28.84 28.84 0 00-21.67 9.84v0L46.33 256l88.86 134.11z" fill="none" stroke="currentColor" stroke-linejoin="round" stroke-width="32"></path><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32" d="M336.67 192.33L206.66 322.34M336.67 322.34L206.66 192.33M336.67 192.33L206.66 322.34M336.67 322.34L206.66 192.33"></path></svg>
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ a.month:hover,
|
|||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
<section>
|
<section>
|
||||||
<Search></Search>
|
<Search season={active_index + 1}></Search>
|
||||||
</section>
|
</section>
|
||||||
<section>
|
<section>
|
||||||
<slot name=recipes></slot>
|
<slot name=recipes></slot>
|
||||||
|
|||||||
456
src/lib/components/SplitMethodSelector.svelte
Normal file
456
src/lib/components/SplitMethodSelector.svelte
Normal file
@@ -0,0 +1,456 @@
|
|||||||
|
<script>
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
export let splitMethod = 'equal';
|
||||||
|
export let users = [];
|
||||||
|
export let amount = 0;
|
||||||
|
export let paidBy = '';
|
||||||
|
export let splitAmounts = {};
|
||||||
|
export let personalAmounts = {};
|
||||||
|
export let currentUser = '';
|
||||||
|
export let predefinedMode = false;
|
||||||
|
|
||||||
|
let personalTotalError = false;
|
||||||
|
|
||||||
|
// Reactive text for "Paid in Full" option
|
||||||
|
$: paidInFullText = (() => {
|
||||||
|
if (!paidBy) {
|
||||||
|
return 'Paid in Full';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special handling for 2-user predefined setup
|
||||||
|
if (predefinedMode && users.length === 2) {
|
||||||
|
const otherUser = users.find(user => user !== paidBy);
|
||||||
|
return otherUser ? `Paid in Full for ${otherUser}` : 'Paid in Full';
|
||||||
|
}
|
||||||
|
|
||||||
|
// General case
|
||||||
|
if (paidBy === currentUser) {
|
||||||
|
return 'Paid in Full by You';
|
||||||
|
} else {
|
||||||
|
return `Paid in Full by ${paidBy}`;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
function calculateEqualSplits() {
|
||||||
|
if (!amount || users.length === 0) return;
|
||||||
|
|
||||||
|
const amountNum = parseFloat(amount);
|
||||||
|
const splitAmount = amountNum / users.length;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = splitAmount - amountNum;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = splitAmount;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculateFullPayment() {
|
||||||
|
if (!amount) return;
|
||||||
|
|
||||||
|
const amountNum = parseFloat(amount);
|
||||||
|
const otherUsers = users.filter(user => user !== paidBy);
|
||||||
|
const amountPerOtherUser = otherUsers.length > 0 ? amountNum / otherUsers.length : 0;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = -amountNum;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = amountPerOtherUser;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculatePersonalEqualSplit() {
|
||||||
|
if (!amount || users.length === 0) return;
|
||||||
|
|
||||||
|
const totalAmount = parseFloat(amount);
|
||||||
|
|
||||||
|
const totalPersonal = users.reduce((sum, user) => {
|
||||||
|
return sum + (parseFloat(personalAmounts[user]) || 0);
|
||||||
|
}, 0);
|
||||||
|
|
||||||
|
const remainder = Math.max(0, totalAmount - totalPersonal);
|
||||||
|
const equalShare = remainder / users.length;
|
||||||
|
|
||||||
|
users.forEach(user => {
|
||||||
|
const personalAmount = parseFloat(personalAmounts[user]) || 0;
|
||||||
|
const totalOwed = personalAmount + equalShare;
|
||||||
|
|
||||||
|
if (user === paidBy) {
|
||||||
|
splitAmounts[user] = totalOwed - totalAmount;
|
||||||
|
} else {
|
||||||
|
splitAmounts[user] = totalOwed;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSplitMethodChange() {
|
||||||
|
if (splitMethod === 'equal') {
|
||||||
|
calculateEqualSplits();
|
||||||
|
} else if (splitMethod === 'full') {
|
||||||
|
calculateFullPayment();
|
||||||
|
} else if (splitMethod === 'personal_equal') {
|
||||||
|
calculatePersonalEqualSplit();
|
||||||
|
} else if (splitMethod === 'proportional') {
|
||||||
|
users.forEach(user => {
|
||||||
|
if (!(user in splitAmounts)) {
|
||||||
|
splitAmounts[user] = 0;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate and recalculate when personal amounts change
|
||||||
|
$: if (splitMethod === 'personal_equal' && personalAmounts && amount) {
|
||||||
|
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
||||||
|
const totalAmount = parseFloat(amount);
|
||||||
|
personalTotalError = totalPersonal > totalAmount;
|
||||||
|
|
||||||
|
if (!personalTotalError) {
|
||||||
|
calculatePersonalEqualSplit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$: if (amount && splitMethod && paidBy) {
|
||||||
|
handleSplitMethodChange();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>Split Method</h2>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="splitMethod">How should this payment be split?</label>
|
||||||
|
<select id="splitMethod" name="splitMethod" bind:value={splitMethod} required>
|
||||||
|
<option value="equal">{predefinedMode && users.length === 2 ? 'Split 50/50' : 'Equal Split'}</option>
|
||||||
|
<option value="personal_equal">Personal + Equal Split</option>
|
||||||
|
<option value="full">{paidInFullText}</option>
|
||||||
|
<option value="proportional">Custom Proportions</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if splitMethod === 'proportional'}
|
||||||
|
<div class="proportional-splits">
|
||||||
|
<h3>Custom Split Amounts</h3>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-input">
|
||||||
|
<label>{user}</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
name="split_{user}"
|
||||||
|
bind:value={splitAmounts[user]}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if splitMethod === 'personal_equal'}
|
||||||
|
<div class="personal-splits">
|
||||||
|
<h3>Personal Amounts</h3>
|
||||||
|
<p class="description">Enter personal amounts for each user. The remainder will be split equally.</p>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-input">
|
||||||
|
<label>{user}</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0"
|
||||||
|
name="personal_{user}"
|
||||||
|
bind:value={personalAmounts[user]}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if amount}
|
||||||
|
<div class="remainder-info" class:error={personalTotalError}>
|
||||||
|
<span>Total Personal: CHF {Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0).toFixed(2)}</span>
|
||||||
|
<span>Remainder to Split: CHF {Math.max(0, parseFloat(amount) - Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0)).toFixed(2)}</span>
|
||||||
|
{#if personalTotalError}
|
||||||
|
<div class="error-message">⚠️ Personal amounts exceed total payment amount!</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if Object.keys(splitAmounts).length > 0}
|
||||||
|
<div class="split-preview">
|
||||||
|
<h3>Split Preview</h3>
|
||||||
|
{#each users as user}
|
||||||
|
<div class="split-item">
|
||||||
|
<div class="split-user">
|
||||||
|
<ProfilePicture username={user} size={24} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
</div>
|
||||||
|
<span class="amount" class:positive={splitAmounts[user] < 0} class:negative={splitAmounts[user] > 0}>
|
||||||
|
{#if splitAmounts[user] > 0}
|
||||||
|
owes CHF {splitAmounts[user].toFixed(2)}
|
||||||
|
{:else if splitAmounts[user] < 0}
|
||||||
|
is owed CHF {Math.abs(splitAmounts[user]).toFixed(2)}
|
||||||
|
{:else}
|
||||||
|
owes CHF {splitAmounts[user].toFixed(2)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
label {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
select {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits, .personal-splits {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits {
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.proportional-splits {
|
||||||
|
border-color: var(--nord3);
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.proportional-splits h3, .personal-splits h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.proportional-splits h3, .personal-splits h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.personal-splits .description {
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.personal-splits .description {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input label {
|
||||||
|
min-width: 100px;
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input input {
|
||||||
|
max-width: 120px;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-input input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-input input {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info {
|
||||||
|
margin-top: 1rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info.error {
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.remainder-info {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
border-color: var(--red);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remainder-info span {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 600;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-preview {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-preview h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-preview h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -173,6 +173,7 @@ dialog button{
|
|||||||
<section class="section">
|
<section class="section">
|
||||||
<figure class="image-container">
|
<figure class="image-container">
|
||||||
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
<!-- svelte-ignore a11y-click-events-have-key-events -->
|
||||||
|
<!-- svelte-ignore a11y-no-static-element-interactions -->
|
||||||
<div class:zoom-in={isloaded && !isredirected} on:click={show_dialog_img}>
|
<div class:zoom-in={isloaded && !isredirected} on:click={show_dialog_img}>
|
||||||
<div class=placeholder style="background-image:url({placeholder_src})" >
|
<div class=placeholder style="background-image:url({placeholder_src})" >
|
||||||
<div class=placeholder_blur>
|
<div class=placeholder_blur>
|
||||||
|
|||||||
239
src/lib/components/UsersList.svelte
Normal file
239
src/lib/components/UsersList.svelte
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
<script>
|
||||||
|
import ProfilePicture from './ProfilePicture.svelte';
|
||||||
|
|
||||||
|
export let users = [];
|
||||||
|
export let currentUser = '';
|
||||||
|
export let predefinedMode = false;
|
||||||
|
export let canRemoveUsers = true;
|
||||||
|
export let newUser = '';
|
||||||
|
|
||||||
|
function addUser() {
|
||||||
|
if (predefinedMode) return;
|
||||||
|
|
||||||
|
if (newUser.trim() && !users.includes(newUser.trim())) {
|
||||||
|
users = [...users, newUser.trim()];
|
||||||
|
newUser = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeUser(userToRemove) {
|
||||||
|
if (predefinedMode) return;
|
||||||
|
if (!canRemoveUsers) return;
|
||||||
|
|
||||||
|
if (users.length > 1 && userToRemove !== currentUser) {
|
||||||
|
users = users.filter(u => u !== userToRemove);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>Split Between Users</h2>
|
||||||
|
|
||||||
|
{#if predefinedMode}
|
||||||
|
<div class="predefined-users">
|
||||||
|
<p class="predefined-note">Splitting between predefined users:</p>
|
||||||
|
<div class="users-list">
|
||||||
|
{#each users as user}
|
||||||
|
<div class="user-item with-profile">
|
||||||
|
<ProfilePicture username={user} size={32} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
{#if user === currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="users-list">
|
||||||
|
{#each users as user}
|
||||||
|
<div class="user-item with-profile">
|
||||||
|
<ProfilePicture username={user} size={32} />
|
||||||
|
<span class="username">{user}</span>
|
||||||
|
{#if user === currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
{#if canRemoveUsers && user !== currentUser}
|
||||||
|
<button type="button" class="remove-user" on:click={() => removeUser(user)}>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="add-user js-enhanced" style="display: none;">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
bind:value={newUser}
|
||||||
|
placeholder="Add user..."
|
||||||
|
on:keydown={(e) => e.key === 'Enter' && (e.preventDefault(), addUser())}
|
||||||
|
/>
|
||||||
|
<button type="button" on:click={addUser}>Add User</button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.users-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.user-item {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item.with-profile {
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-item .username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.user-item .username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.predefined-users {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.predefined-users {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.predefined-note {
|
||||||
|
margin: 0 0 1rem 0;
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.predefined-note {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-user {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remove-user:hover {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user input {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.add-user input {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user button {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.add-user button:hover {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
16
src/lib/config/users.ts
Normal file
16
src/lib/config/users.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
// Predefined users configuration for Cospend
|
||||||
|
// When this array has exactly 2 users, the system will always split between them
|
||||||
|
// For more users, manual selection is allowed
|
||||||
|
|
||||||
|
export const PREDEFINED_USERS = [
|
||||||
|
'alexander',
|
||||||
|
'anna'
|
||||||
|
];
|
||||||
|
|
||||||
|
export function isPredefinedUsersMode(): boolean {
|
||||||
|
return PREDEFINED_USERS.length === 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAvailableUsers(): string[] {
|
||||||
|
return [...PREDEFINED_USERS];
|
||||||
|
}
|
||||||
@@ -12,6 +12,6 @@ export function rand_array(array){
|
|||||||
let time = new Date()
|
let time = new Date()
|
||||||
const seed = Math.floor(time.getTime()/MS_PER_DAY)
|
const seed = Math.floor(time.getTime()/MS_PER_DAY)
|
||||||
let rand = mulberry32(seed)
|
let rand = mulberry32(seed)
|
||||||
array.sort((a,b) => 0.5 - rand())
|
// Create a copy to avoid mutating the original array
|
||||||
return array
|
return [...array].sort((a,b) => 0.5 - rand())
|
||||||
}
|
}
|
||||||
|
|||||||
126
src/lib/js/recipeJsonLd.ts
Normal file
126
src/lib/js/recipeJsonLd.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
function parseTimeToISO8601(timeString: string): string | undefined {
|
||||||
|
if (!timeString) return undefined;
|
||||||
|
|
||||||
|
// Handle common German time formats
|
||||||
|
const cleanTime = timeString.toLowerCase().trim();
|
||||||
|
|
||||||
|
// Match patterns like "30 min", "2 h", "1.5 h", "90 min"
|
||||||
|
const minMatch = cleanTime.match(/(\d+(?:[.,]\d+)?)\s*(?:min|minuten?)/);
|
||||||
|
const hourMatch = cleanTime.match(/(\d+(?:[.,]\d+)?)\s*(?:h|stunden?|std)/);
|
||||||
|
|
||||||
|
if (minMatch) {
|
||||||
|
const minutes = Math.round(parseFloat(minMatch[1].replace(',', '.')));
|
||||||
|
return `PT${minutes}M`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hourMatch) {
|
||||||
|
const hours = parseFloat(hourMatch[1].replace(',', '.'));
|
||||||
|
if (hours % 1 === 0) {
|
||||||
|
return `PT${Math.round(hours)}H`;
|
||||||
|
} else {
|
||||||
|
const totalMinutes = Math.round(hours * 60);
|
||||||
|
return `PT${totalMinutes}M`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateRecipeJsonLd(data: any) {
|
||||||
|
const jsonLd: any = {
|
||||||
|
"@context": "https://schema.org",
|
||||||
|
"@type": "Recipe",
|
||||||
|
"name": data.name?.replace(/<[^>]*>/g, ''), // Strip HTML tags
|
||||||
|
"description": data.description,
|
||||||
|
"author": {
|
||||||
|
"@type": "Person",
|
||||||
|
"name": "Alexander Bocken"
|
||||||
|
},
|
||||||
|
"datePublished": data.dateCreated ? new Date(data.dateCreated).toISOString() : undefined,
|
||||||
|
"dateModified": data.dateModified || data.updatedAt ? new Date(data.dateModified || data.updatedAt).toISOString() : undefined,
|
||||||
|
"recipeCategory": data.category,
|
||||||
|
"keywords": data.tags?.join(', '),
|
||||||
|
"image": {
|
||||||
|
"@type": "ImageObject",
|
||||||
|
"url": `https://bocken.org/static/rezepte/full/${data.short_name}.webp`,
|
||||||
|
"width": 1200,
|
||||||
|
"height": 800
|
||||||
|
},
|
||||||
|
"recipeIngredient": [] as string[],
|
||||||
|
"recipeInstructions": [] as any[],
|
||||||
|
"url": `https://bocken.org/rezepte/${data.short_name}`
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add optional fields if they exist
|
||||||
|
if (data.portions) {
|
||||||
|
jsonLd.recipeYield = data.portions;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse times properly for ISO 8601
|
||||||
|
const prepTime = parseTimeToISO8601(data.preparation);
|
||||||
|
if (prepTime) jsonLd.prepTime = prepTime;
|
||||||
|
|
||||||
|
const cookTime = parseTimeToISO8601(data.cooking);
|
||||||
|
if (cookTime) jsonLd.cookTime = cookTime;
|
||||||
|
|
||||||
|
const totalTime = parseTimeToISO8601(data.total_time);
|
||||||
|
if (totalTime) jsonLd.totalTime = totalTime;
|
||||||
|
|
||||||
|
// Extract ingredients
|
||||||
|
if (data.ingredients) {
|
||||||
|
for (const ingredientGroup of data.ingredients) {
|
||||||
|
if (ingredientGroup.list) {
|
||||||
|
for (const ingredient of ingredientGroup.list) {
|
||||||
|
if (ingredient.name) {
|
||||||
|
let ingredientText = ingredient.name;
|
||||||
|
if (ingredient.amount) {
|
||||||
|
ingredientText = `${ingredient.amount} ${ingredient.unit || ''} ${ingredient.name}`.trim();
|
||||||
|
}
|
||||||
|
jsonLd.recipeIngredient.push(ingredientText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract instructions
|
||||||
|
if (data.instructions) {
|
||||||
|
for (const instructionGroup of data.instructions) {
|
||||||
|
if (instructionGroup.steps) {
|
||||||
|
for (let i = 0; i < instructionGroup.steps.length; i++) {
|
||||||
|
jsonLd.recipeInstructions.push({
|
||||||
|
"@type": "HowToStep",
|
||||||
|
"name": `Schritt ${i + 1}`,
|
||||||
|
"text": instructionGroup.steps[i]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add baking instructions if available
|
||||||
|
if (data.baking?.temperature || data.baking?.length) {
|
||||||
|
const bakingText = [
|
||||||
|
data.baking.temperature ? `bei ${data.baking.temperature}` : '',
|
||||||
|
data.baking.length ? `für ${data.baking.length}` : '',
|
||||||
|
data.baking.mode || ''
|
||||||
|
].filter(Boolean).join(' ');
|
||||||
|
|
||||||
|
if (bakingText) {
|
||||||
|
jsonLd.recipeInstructions.push({
|
||||||
|
"@type": "HowToStep",
|
||||||
|
"name": "Backen",
|
||||||
|
"text": `Backen ${bakingText}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up undefined values
|
||||||
|
Object.keys(jsonLd).forEach(key => {
|
||||||
|
if (jsonLd[key] === undefined) {
|
||||||
|
delete jsonLd[key];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return jsonLd;
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
import mongoose from 'mongoose';
|
|
||||||
|
|
||||||
const paymentSchema = new mongoose.Schema({
|
|
||||||
paid_by: { type: String, required: true },
|
|
||||||
total_amount: { type: Number, required: true },
|
|
||||||
for_self: { type: Number, default: 0 },
|
|
||||||
for_other: { type: Number, default: 0 },
|
|
||||||
currency: { type: String, default: 'CHF' },
|
|
||||||
description: String,
|
|
||||||
date: { type: Date, default: Date.now },
|
|
||||||
receipt_image: String
|
|
||||||
});
|
|
||||||
|
|
||||||
export const Payment = mongoose.models.Payment || mongoose.model('Payment', paymentSchema);
|
|
||||||
48
src/lib/server/favorites.ts
Normal file
48
src/lib/server/favorites.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Utility functions for handling user favorites on the server side
|
||||||
|
*/
|
||||||
|
|
||||||
|
export async function getUserFavorites(fetch: any, locals: any): Promise<string[]> {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const favRes = await fetch('/api/rezepte/favorites');
|
||||||
|
if (favRes.ok) {
|
||||||
|
const favData = await favRes.json();
|
||||||
|
return favData.favorites || [];
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Silently fail if favorites can't be loaded
|
||||||
|
console.error('Error loading user favorites:', e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addFavoriteStatusToRecipes(recipes: any[], userFavorites: string[]): any[] {
|
||||||
|
return recipes.map(recipe => ({
|
||||||
|
...recipe,
|
||||||
|
isFavorite: userFavorites.some(favId => favId.toString() === recipe._id.toString())
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadRecipesWithFavorites(
|
||||||
|
fetch: any,
|
||||||
|
locals: any,
|
||||||
|
recipeLoader: () => Promise<any>
|
||||||
|
): Promise<{ recipes: any[], session: any }> {
|
||||||
|
const [recipes, userFavorites, session] = await Promise.all([
|
||||||
|
recipeLoader(),
|
||||||
|
getUserFavorites(fetch, locals),
|
||||||
|
locals.auth()
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
recipes: addFavoriteStatusToRecipes(recipes, userFavorites),
|
||||||
|
session
|
||||||
|
};
|
||||||
|
}
|
||||||
184
src/lib/server/scheduler.ts
Normal file
184
src/lib/server/scheduler.ts
Normal 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
53
src/lib/utils/categories.ts
Normal file
53
src/lib/utils/categories.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
export const PAYMENT_CATEGORIES = {
|
||||||
|
groceries: {
|
||||||
|
name: 'Groceries',
|
||||||
|
emoji: '🛒'
|
||||||
|
},
|
||||||
|
shopping: {
|
||||||
|
name: 'Shopping',
|
||||||
|
emoji: '🛍️'
|
||||||
|
},
|
||||||
|
travel: {
|
||||||
|
name: 'Travel',
|
||||||
|
emoji: '🚆'
|
||||||
|
},
|
||||||
|
restaurant: {
|
||||||
|
name: 'Restaurant',
|
||||||
|
emoji: '🍽️'
|
||||||
|
},
|
||||||
|
utilities: {
|
||||||
|
name: 'Utilities',
|
||||||
|
emoji: '⚡'
|
||||||
|
},
|
||||||
|
fun: {
|
||||||
|
name: 'Fun',
|
||||||
|
emoji: '🎉'
|
||||||
|
},
|
||||||
|
settlement: {
|
||||||
|
name: 'Settlement',
|
||||||
|
emoji: '🤝'
|
||||||
|
}
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type PaymentCategory = keyof typeof PAYMENT_CATEGORIES;
|
||||||
|
|
||||||
|
export function getCategoryInfo(category: PaymentCategory) {
|
||||||
|
return PAYMENT_CATEGORIES[category] || PAYMENT_CATEGORIES.groceries;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCategoryEmoji(category: PaymentCategory) {
|
||||||
|
return getCategoryInfo(category).emoji;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCategoryName(category: PaymentCategory) {
|
||||||
|
return getCategoryInfo(category).name;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCategoryOptions() {
|
||||||
|
return Object.entries(PAYMENT_CATEGORIES).map(([key, value]) => ({
|
||||||
|
value: key as PaymentCategory,
|
||||||
|
label: `${value.emoji} ${value.name}`,
|
||||||
|
emoji: value.emoji,
|
||||||
|
name: value.name
|
||||||
|
}));
|
||||||
|
}
|
||||||
230
src/lib/utils/recurring.ts
Normal file
230
src/lib/utils/recurring.ts
Normal 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'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
63
src/lib/utils/settlements.ts
Normal file
63
src/lib/utils/settlements.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
// Utility functions for identifying and handling settlement payments
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identifies if a payment is a settlement payment based on category
|
||||||
|
*/
|
||||||
|
export function isSettlementPayment(payment: any): boolean {
|
||||||
|
if (!payment) return false;
|
||||||
|
|
||||||
|
// Check if category is settlement
|
||||||
|
return payment.category === 'settlement';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the settlement icon for settlement payments
|
||||||
|
*/
|
||||||
|
export function getSettlementIcon(): string {
|
||||||
|
return '🤝'; // Handshake emoji for settlements
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets appropriate styling classes for settlement payments
|
||||||
|
*/
|
||||||
|
export function getSettlementClasses(payment: any): string[] {
|
||||||
|
if (!isSettlementPayment(payment)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['settlement-payment'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets settlement-specific display text
|
||||||
|
*/
|
||||||
|
export function getSettlementDisplayText(payment: any): string {
|
||||||
|
if (!isSettlementPayment(payment)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Settlement';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the other user in a settlement (the one who didn't pay)
|
||||||
|
*/
|
||||||
|
export function getSettlementReceiver(payment: any): string {
|
||||||
|
if (!isSettlementPayment(payment) || !payment.splits) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find the user who has a positive amount (the receiver)
|
||||||
|
const receiver = payment.splits.find(split => split.amount > 0);
|
||||||
|
if (receiver && receiver.username) {
|
||||||
|
return receiver.username;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: find the user who is not the payer
|
||||||
|
const otherUser = payment.splits.find(split => split.username !== payment.paidBy);
|
||||||
|
if (otherUser && otherUser.username) {
|
||||||
|
return otherUser.username;
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
86
src/models/Payment.ts
Normal file
86
src/models/Payment.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
|
export interface IPayment {
|
||||||
|
_id?: string;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
paidBy: string; // username/nickname of the person who paid
|
||||||
|
date: Date;
|
||||||
|
image?: string; // path to uploaded image
|
||||||
|
category: 'groceries' | 'shopping' | 'travel' | 'restaurant' | 'utilities' | 'fun' | 'settlement';
|
||||||
|
splitMethod: 'equal' | 'full' | 'proportional' | 'personal_equal';
|
||||||
|
createdBy: string; // username/nickname of the person who created the payment
|
||||||
|
createdAt?: Date;
|
||||||
|
updatedAt?: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PaymentSchema = 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'] // For now only CHF as requested
|
||||||
|
},
|
||||||
|
paidBy: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
trim: true
|
||||||
|
},
|
||||||
|
date: {
|
||||||
|
type: Date,
|
||||||
|
required: true,
|
||||||
|
default: Date.now
|
||||||
|
},
|
||||||
|
image: {
|
||||||
|
type: String,
|
||||||
|
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'
|
||||||
|
},
|
||||||
|
createdBy: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
trim: true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamps: true,
|
||||||
|
toJSON: { virtuals: true },
|
||||||
|
toObject: { virtuals: true }
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
PaymentSchema.virtual('splits', {
|
||||||
|
ref: 'PaymentSplit',
|
||||||
|
localField: '_id',
|
||||||
|
foreignField: 'paymentId'
|
||||||
|
});
|
||||||
|
|
||||||
|
export const Payment = mongoose.model<IPayment>("Payment", PaymentSchema);
|
||||||
56
src/models/PaymentSplit.ts
Normal file
56
src/models/PaymentSplit.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
|
export interface IPaymentSplit {
|
||||||
|
_id?: string;
|
||||||
|
paymentId: mongoose.Schema.Types.ObjectId;
|
||||||
|
username: string; // username/nickname of the person who owes/is owed
|
||||||
|
amount: number; // amount this person owes (positive) or is owed (negative)
|
||||||
|
proportion?: number; // for proportional splits, the proportion (e.g., 0.5 for 50%)
|
||||||
|
personalAmount?: number; // for personal_equal splits, the personal portion for this user
|
||||||
|
settled: boolean; // whether this split has been settled
|
||||||
|
settledAt?: Date;
|
||||||
|
createdAt?: Date;
|
||||||
|
updatedAt?: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PaymentSplitSchema = new mongoose.Schema(
|
||||||
|
{
|
||||||
|
paymentId: {
|
||||||
|
type: mongoose.Schema.Types.ObjectId,
|
||||||
|
ref: 'Payment',
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
username: {
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
trim: true
|
||||||
|
},
|
||||||
|
amount: {
|
||||||
|
type: Number,
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
proportion: {
|
||||||
|
type: Number,
|
||||||
|
min: 0,
|
||||||
|
max: 1
|
||||||
|
},
|
||||||
|
personalAmount: {
|
||||||
|
type: Number,
|
||||||
|
min: 0
|
||||||
|
},
|
||||||
|
settled: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false
|
||||||
|
},
|
||||||
|
settledAt: {
|
||||||
|
type: Date
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamps: true
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
PaymentSplitSchema.index({ paymentId: 1, username: 1 }, { unique: true });
|
||||||
|
|
||||||
|
export const PaymentSplit = mongoose.model<IPaymentSplit>("PaymentSplit", PaymentSplitSchema);
|
||||||
141
src/models/RecurringPayment.ts
Normal file
141
src/models/RecurringPayment.ts
Normal 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);
|
||||||
11
src/models/UserFavorites.ts
Normal file
11
src/models/UserFavorites.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
|
const UserFavoritesSchema = new mongoose.Schema(
|
||||||
|
{
|
||||||
|
username: { type: String, required: true, unique: true },
|
||||||
|
favorites: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' }] // Recipe MongoDB ObjectIds
|
||||||
|
},
|
||||||
|
{ timestamps: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
export const UserFavorites = mongoose.model("UserFavorites", UserFavoritesSchema);
|
||||||
@@ -114,7 +114,7 @@ section h2{
|
|||||||
<h3>Suchmaschine</h3>
|
<h3>Suchmaschine</h3>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<a href="https://cloud.bocken.org/apps/cospend/">
|
<a href="cospend">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M0 24C0 10.7 10.7 0 24 0H69.5c22 0 41.5 12.8 50.6 32h411c26.3 0 45.5 25 38.6 50.4l-41 152.3c-8.5 31.4-37 53.3-69.5 53.3H170.7l5.4 28.5c2.2 11.3 12.1 19.5 23.6 19.5H488c13.3 0 24 10.7 24 24s-10.7 24-24 24H199.7c-34.6 0-64.3-24.6-70.7-58.5L77.4 54.5c-.7-3.8-4-6.5-7.9-6.5H24C10.7 48 0 37.3 0 24zM128 464a48 48 0 1 1 96 0 48 48 0 1 1 -96 0zm336-48a48 48 0 1 1 0 96 48 48 0 1 1 0-96z"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M0 24C0 10.7 10.7 0 24 0H69.5c22 0 41.5 12.8 50.6 32h411c26.3 0 45.5 25 38.6 50.4l-41 152.3c-8.5 31.4-37 53.3-69.5 53.3H170.7l5.4 28.5c2.2 11.3 12.1 19.5 23.6 19.5H488c13.3 0 24 10.7 24 24s-10.7 24-24 24H199.7c-34.6 0-64.3-24.6-70.7-58.5L77.4 54.5c-.7-3.8-4-6.5-7.9-6.5H24C10.7 48 0 37.3 0 24zM128 464a48 48 0 1 1 96 0 48 48 0 1 1 -96 0zm336-48a48 48 0 1 1 0 96 48 48 0 1 1 0-96z"/></svg>
|
||||||
<h3>Einkauf</h3>
|
<h3>Einkauf</h3>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
|
||||||
import fs from 'fs';
|
|
||||||
import path from 'path';
|
|
||||||
import { mkdir } from 'fs/promises';
|
|
||||||
import { Payment } from '$lib/models/Payment'; // adjust path as needed
|
|
||||||
import { dbConnect, dbDisconnect } from '$lib/db/db';
|
|
||||||
import { error } from '@sveltejs/kit';
|
|
||||||
|
|
||||||
const UPLOAD_DIR = './static/cospend';
|
|
||||||
const BASE_CURRENCY = 'CHF'; // Default currency
|
|
||||||
|
|
||||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
|
||||||
let auth = await locals.auth();
|
|
||||||
if(!auth){
|
|
||||||
throw error(401, "Not logged in")
|
|
||||||
}
|
|
||||||
|
|
||||||
const formData = await request.formData();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const name = formData.get('name') as string;
|
|
||||||
const category = formData.get('category') as string;
|
|
||||||
const transaction_date= new Date(formData.get('transaction_date') as string);
|
|
||||||
const description = formData.get('description') as string;
|
|
||||||
const note = formData.get('note') as string;
|
|
||||||
const tags = JSON.parse(formData.get('tags') as string) as string[];
|
|
||||||
const paid_by = formData.get('paid_by') as string
|
|
||||||
const type = formData.get('type') as string
|
|
||||||
|
|
||||||
let currency = formData.get('currency') as string;
|
|
||||||
let original_amount = parseFloat(formData.get('original_amount') as string);
|
|
||||||
let total_amount = NaN;
|
|
||||||
|
|
||||||
let for_self = parseFloat(formData.get('for_self') as string);
|
|
||||||
let for_other = parseFloat(formData.get('for_other') as string);
|
|
||||||
let conversion_rate = 1.0; // Default conversion rate
|
|
||||||
|
|
||||||
// if currency is not BASE_CURRENCY, fetch current conversion rate using frankfurter API and date in YYYY-MM-DD format
|
|
||||||
if (!currency || currency === BASE_CURRENCY) {
|
|
||||||
currency = BASE_CURRENCY;
|
|
||||||
total_amount = original_amount;
|
|
||||||
} else {
|
|
||||||
console.log(transaction_date);
|
|
||||||
const date_fmt = transaction_date.toISOString().split('T')[0]; // Convert date to YYYY-MM-DD format
|
|
||||||
// Fetch conversion rate logic here (not implemented in this example)
|
|
||||||
console.log(`Fetching conversion rate for ${currency} to ${BASE_CURRENCY} on ${date_fmt}`);
|
|
||||||
const res = await fetch(`https://api.frankfurter.app/${date_fmt}?from=${currency}&to=${BASE_CURRENCY}`)
|
|
||||||
console.log(res);
|
|
||||||
const result = await res.json();
|
|
||||||
console.log(result);
|
|
||||||
if (!result || !result.rates[BASE_CURRENCY]) {
|
|
||||||
return new Response(JSON.stringify({ message: 'Currency conversion failed.' }), { status: 400 });
|
|
||||||
}
|
|
||||||
// Assuming you want to convert the total amount to BASE_CURRENCY
|
|
||||||
conversion_rate = parseFloat(result.rates[BASE_CURRENCY]);
|
|
||||||
console.log(`Conversion rate from ${currency} to ${BASE_CURRENCY} on ${date_fmt}: ${conversion_rate}`);
|
|
||||||
total_amount = original_amount * conversion_rate;
|
|
||||||
for_self = for_self * conversion_rate;
|
|
||||||
for_other = for_other * conversion_rate;
|
|
||||||
}
|
|
||||||
|
|
||||||
//const personal_amounts = JSON.parse(formData.get('personal_amounts') as string) as { user: string, amount: number }[];
|
|
||||||
|
|
||||||
if (!name || isNaN(total_amount)) {
|
|
||||||
return new Response(JSON.stringify({ message: 'Invalid required fields.' }), { status: 400 });
|
|
||||||
}
|
|
||||||
|
|
||||||
await mkdir(UPLOAD_DIR, { recursive: true });
|
|
||||||
|
|
||||||
const images: { mediapath: string }[] = [];
|
|
||||||
const imageFiles = formData.getAll('images') as File[];
|
|
||||||
|
|
||||||
for (const file of imageFiles) {
|
|
||||||
const arrayBuffer = await file.arrayBuffer();
|
|
||||||
const buffer = Buffer.from(arrayBuffer);
|
|
||||||
const safeName = `${Date.now()}_${file.name.replace(/[^a-zA-Z0-9_.-]/g, '_')}`;
|
|
||||||
const fullPath = path.join(UPLOAD_DIR, safeName);
|
|
||||||
fs.writeFileSync(fullPath, buffer);
|
|
||||||
images.push({ mediapath: `/static/test/${safeName}` });
|
|
||||||
}
|
|
||||||
|
|
||||||
await dbConnect();
|
|
||||||
const payment = new Payment({
|
|
||||||
type,
|
|
||||||
name,
|
|
||||||
category,
|
|
||||||
transaction_date,
|
|
||||||
images,
|
|
||||||
description,
|
|
||||||
note,
|
|
||||||
tags,
|
|
||||||
original_amount,
|
|
||||||
total_amount,
|
|
||||||
paid_by,
|
|
||||||
for_self,
|
|
||||||
for_other,
|
|
||||||
conversion_rate,
|
|
||||||
currency,
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try{
|
|
||||||
await Payment.create(payment);
|
|
||||||
} catch(e){
|
|
||||||
|
|
||||||
return new Response(JSON.stringify({ message: `Error creating payment event. ${e}` }), { status: 500 });
|
|
||||||
}
|
|
||||||
await dbDisconnect();
|
|
||||||
return new Response(JSON.stringify({ message: 'Payment event created successfully.' }), { status: 201 });
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
return new Response(JSON.stringify({ message: 'Error processing request.' }), { status: 500 });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,38 +1,100 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
import { json } from '@sveltejs/kit';
|
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||||
import { Payment } from '$lib/models/Payment'; // adjust path as needed
|
import { Payment } from '../../../../models/Payment'; // Need to import Payment for populate to work
|
||||||
import { dbConnect, dbDisconnect } from '$lib/db/db';
|
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
const UPLOAD_DIR = '/var/lib/www/static/test';
|
export const GET: RequestHandler = async ({ locals, url }) => {
|
||||||
const BASE_CURRENCY = 'CHF'; // Default currency
|
const auth = await locals.auth();
|
||||||
|
if (!auth || !auth.user?.nickname) {
|
||||||
export const GET: RequestHandler = async ({ request, locals }) => {
|
throw error(401, 'Not logged in');
|
||||||
await dbConnect();
|
|
||||||
|
|
||||||
const result = await Payment.aggregate([
|
|
||||||
{
|
|
||||||
$group: {
|
|
||||||
_id: "$paid_by",
|
|
||||||
totalPaid: { $sum: "$total_amount" },
|
|
||||||
totalForSelf: { $sum: { $ifNull: ["$for_self", 0] } },
|
|
||||||
totalForOther: { $sum: { $ifNull: ["$for_other", 0] } }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
$project: {
|
|
||||||
_id: 0,
|
|
||||||
paid_by: "$_id",
|
|
||||||
netTotal: {
|
|
||||||
$multiply: [
|
|
||||||
{ $add: [
|
|
||||||
{ $subtract: ["$totalPaid", "$totalForSelf"] },
|
|
||||||
"$totalForOther"
|
|
||||||
] },
|
|
||||||
0.5]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]);
|
|
||||||
|
const username = auth.user.nickname;
|
||||||
|
const includeAll = url.searchParams.get('all') === 'true';
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (includeAll) {
|
||||||
|
const allSplits = await PaymentSplit.aggregate([
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: '$username',
|
||||||
|
totalOwed: { $sum: { $cond: [{ $gt: ['$amount', 0] }, '$amount', 0] } },
|
||||||
|
totalOwing: { $sum: { $cond: [{ $lt: ['$amount', 0] }, { $abs: '$amount' }, 0] } },
|
||||||
|
netBalance: { $sum: '$amount' }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
username: '$_id',
|
||||||
|
totalOwed: 1,
|
||||||
|
totalOwing: 1,
|
||||||
|
netBalance: 1,
|
||||||
|
_id: 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const currentUserBalance = allSplits.find(balance => balance.username === username) || {
|
||||||
|
username,
|
||||||
|
totalOwed: 0,
|
||||||
|
totalOwing: 0,
|
||||||
|
netBalance: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
return json({
|
||||||
|
currentUser: currentUserBalance,
|
||||||
|
allBalances: allSplits
|
||||||
|
});
|
||||||
|
|
||||||
|
} else {
|
||||||
|
const userSplits = await PaymentSplit.find({ username }).lean();
|
||||||
|
|
||||||
|
// Calculate net balance: negative = you are owed money, positive = you owe money
|
||||||
|
const netBalance = userSplits.reduce((sum, split) => sum + split.amount, 0);
|
||||||
|
|
||||||
|
const recentSplits = await PaymentSplit.aggregate([
|
||||||
|
{ $match: { username } },
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'payments',
|
||||||
|
localField: 'paymentId',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'paymentId'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $unwind: '$paymentId' },
|
||||||
|
{ $sort: { 'paymentId.date': -1, 'paymentId.createdAt': -1 } },
|
||||||
|
{ $limit: 10 }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// For settlements, fetch the other user's split info
|
||||||
|
for (const split of recentSplits) {
|
||||||
|
if (split.paymentId && split.paymentId.category === 'settlement') {
|
||||||
|
// This is a settlement, find the other user
|
||||||
|
const otherSplit = await PaymentSplit.findOne({
|
||||||
|
paymentId: split.paymentId._id,
|
||||||
|
username: { $ne: username }
|
||||||
|
}).lean();
|
||||||
|
|
||||||
|
if (otherSplit) {
|
||||||
|
split.otherUser = otherSplit.username;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({
|
||||||
|
netBalance,
|
||||||
|
recentSplits
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error calculating balance:', e);
|
||||||
|
throw error(500, 'Failed to calculate balance');
|
||||||
|
} finally {
|
||||||
await dbDisconnect();
|
await dbDisconnect();
|
||||||
return json(result);
|
}
|
||||||
};
|
};
|
||||||
110
src/routes/api/cospend/debts/+server.ts
Normal file
110
src/routes/api/cospend/debts/+server.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||||
|
import { Payment } from '../../../../models/Payment';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
interface DebtSummary {
|
||||||
|
username: string;
|
||||||
|
netAmount: number; // positive = you owe them, negative = they owe you
|
||||||
|
transactions: {
|
||||||
|
paymentId: string;
|
||||||
|
title: string;
|
||||||
|
amount: number;
|
||||||
|
date: Date;
|
||||||
|
category: string;
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals }) => {
|
||||||
|
const auth = await locals.auth();
|
||||||
|
if (!auth || !auth.user?.nickname) {
|
||||||
|
throw error(401, 'Not logged in');
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentUser = auth.user.nickname;
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get all splits for the current user
|
||||||
|
const userSplits = await PaymentSplit.find({ username: currentUser })
|
||||||
|
.populate('paymentId')
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
// Get all other users who have splits with payments involving the current user
|
||||||
|
const paymentIds = userSplits.map(split => split.paymentId._id);
|
||||||
|
const allRelatedSplits = await PaymentSplit.find({
|
||||||
|
paymentId: { $in: paymentIds },
|
||||||
|
username: { $ne: currentUser }
|
||||||
|
})
|
||||||
|
.populate('paymentId')
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
// Group debts by user
|
||||||
|
const debtsByUser = new Map<string, DebtSummary>();
|
||||||
|
|
||||||
|
// Process current user's splits to understand what they owe/are owed
|
||||||
|
for (const split of userSplits) {
|
||||||
|
const payment = split.paymentId as any;
|
||||||
|
if (!payment) continue;
|
||||||
|
|
||||||
|
// Find other participants in this payment
|
||||||
|
const otherSplits = allRelatedSplits.filter(s =>
|
||||||
|
s.paymentId._id.toString() === split.paymentId._id.toString()
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const otherSplit of otherSplits) {
|
||||||
|
const otherUser = otherSplit.username;
|
||||||
|
|
||||||
|
if (!debtsByUser.has(otherUser)) {
|
||||||
|
debtsByUser.set(otherUser, {
|
||||||
|
username: otherUser,
|
||||||
|
netAmount: 0,
|
||||||
|
transactions: []
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const debt = debtsByUser.get(otherUser)!;
|
||||||
|
|
||||||
|
// Current user's amount: positive = they owe, negative = they are owed
|
||||||
|
// We want to show net between the two users
|
||||||
|
debt.netAmount += split.amount;
|
||||||
|
|
||||||
|
debt.transactions.push({
|
||||||
|
paymentId: payment._id.toString(),
|
||||||
|
title: payment.title,
|
||||||
|
amount: split.amount,
|
||||||
|
date: payment.date,
|
||||||
|
category: payment.category
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert map to array and sort by absolute amount (largest debts first)
|
||||||
|
const debtSummaries = Array.from(debtsByUser.values())
|
||||||
|
.filter(debt => Math.abs(debt.netAmount) > 0.01) // Filter out tiny amounts
|
||||||
|
.sort((a, b) => Math.abs(b.netAmount) - Math.abs(a.netAmount));
|
||||||
|
|
||||||
|
// Separate into who owes you vs who you owe
|
||||||
|
const whoOwesMe = debtSummaries.filter(debt => debt.netAmount < 0).map(debt => ({
|
||||||
|
...debt,
|
||||||
|
netAmount: Math.abs(debt.netAmount) // Make positive for display
|
||||||
|
}));
|
||||||
|
|
||||||
|
const whoIOwe = debtSummaries.filter(debt => debt.netAmount > 0);
|
||||||
|
|
||||||
|
return json({
|
||||||
|
whoOwesMe,
|
||||||
|
whoIOwe,
|
||||||
|
totalOwedToMe: whoOwesMe.reduce((sum, debt) => sum + debt.netAmount, 0),
|
||||||
|
totalIOwe: whoIOwe.reduce((sum, debt) => sum + debt.netAmount, 0)
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error calculating debt breakdown:', e);
|
||||||
|
throw error(500, 'Failed to calculate debt breakdown');
|
||||||
|
} finally {
|
||||||
|
await dbDisconnect();
|
||||||
|
}
|
||||||
|
};
|
||||||
131
src/routes/api/cospend/monthly-expenses/+server.ts
Normal file
131
src/routes/api/cospend/monthly-expenses/+server.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import { json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { Payment } from '../../../../models/Payment';
|
||||||
|
import { dbConnect } from '../../../../utils/db';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ url, locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session || !session.user?.nickname) {
|
||||||
|
return json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
|
||||||
|
// Get query parameters for date range (default to last 12 months)
|
||||||
|
const monthsBack = parseInt(url.searchParams.get('months') || '12');
|
||||||
|
const endDate = new Date();
|
||||||
|
const startDate = new Date();
|
||||||
|
startDate.setMonth(startDate.getMonth() - monthsBack);
|
||||||
|
|
||||||
|
const totalPayments = await Payment.countDocuments();
|
||||||
|
const paymentsInRange = await Payment.countDocuments({
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const expensePayments = await Payment.countDocuments({
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
},
|
||||||
|
category: { $ne: 'settlement' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Aggregate payments by month and category
|
||||||
|
const pipeline = [
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
date: {
|
||||||
|
$gte: startDate,
|
||||||
|
$lte: endDate
|
||||||
|
},
|
||||||
|
// Exclude settlements - only show actual expenses
|
||||||
|
category: { $ne: 'settlement' },
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$addFields: {
|
||||||
|
// Extract year-month from date
|
||||||
|
yearMonth: {
|
||||||
|
$dateToString: {
|
||||||
|
format: '%Y-%m',
|
||||||
|
date: '$date'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: {
|
||||||
|
yearMonth: '$yearMonth',
|
||||||
|
category: '$category'
|
||||||
|
},
|
||||||
|
totalAmount: { $sum: '$amount' },
|
||||||
|
count: { $sum: 1 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$sort: {
|
||||||
|
'_id.yearMonth': 1,
|
||||||
|
'_id.category': 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const results = await Payment.aggregate(pipeline);
|
||||||
|
console.log('Aggregation results:', results);
|
||||||
|
|
||||||
|
// Transform data into chart-friendly format
|
||||||
|
const monthsMap = new Map();
|
||||||
|
const categories = new Set();
|
||||||
|
|
||||||
|
// Initialize months
|
||||||
|
for (let i = 0; i < monthsBack; i++) {
|
||||||
|
const date = new Date();
|
||||||
|
date.setMonth(date.getMonth() - monthsBack + i + 1);
|
||||||
|
const yearMonth = date.toISOString().substring(0, 7);
|
||||||
|
monthsMap.set(yearMonth, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Populate data
|
||||||
|
results.forEach((result: any) => {
|
||||||
|
const { yearMonth, category } = result._id;
|
||||||
|
const amount = result.totalAmount;
|
||||||
|
|
||||||
|
categories.add(category);
|
||||||
|
|
||||||
|
if (!monthsMap.has(yearMonth)) {
|
||||||
|
monthsMap.set(yearMonth, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
monthsMap.get(yearMonth)[category] = amount;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Convert to arrays for Chart.js
|
||||||
|
const months = Array.from(monthsMap.keys()).sort();
|
||||||
|
const categoryList = Array.from(categories).sort();
|
||||||
|
|
||||||
|
const datasets = categoryList.map((category: string) => ({
|
||||||
|
label: category,
|
||||||
|
data: months.map(month => monthsMap.get(month)[category] || 0)
|
||||||
|
}));
|
||||||
|
|
||||||
|
return json({
|
||||||
|
labels: months.map(month => {
|
||||||
|
const [year, monthNum] = month.split('-');
|
||||||
|
const date = new Date(parseInt(year), parseInt(monthNum) - 1);
|
||||||
|
return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
|
||||||
|
}),
|
||||||
|
datasets,
|
||||||
|
categories: categoryList
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching monthly expenses:', error);
|
||||||
|
return json({ error: 'Failed to fetch monthly expenses' }, { status: 500 });
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
import { json, type RequestHandler } from '@sveltejs/kit';
|
|
||||||
import { Payment } from '$lib/models/Payment';
|
|
||||||
import { dbConnect, dbDisconnect } from '$lib/db/db';
|
|
||||||
import { error } from '@sveltejs/kit';
|
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({params}) => {
|
|
||||||
await dbConnect();
|
|
||||||
const number_payments = 10;
|
|
||||||
const number_skip = params.pageno ? (parseInt(params.pageno) - 1 ) * number_payments : 0;
|
|
||||||
let payments = await Payment.find()
|
|
||||||
.sort({ transaction_date: -1 })
|
|
||||||
.skip(number_skip)
|
|
||||||
.limit(number_payments);
|
|
||||||
await dbDisconnect();
|
|
||||||
|
|
||||||
if(payments == null){
|
|
||||||
throw error(404, "No more payments found");
|
|
||||||
}
|
|
||||||
return json(payments);
|
|
||||||
};
|
|
||||||
109
src/routes/api/cospend/payments/+server.ts
Normal file
109
src/routes/api/cospend/payments/+server.ts
Normal file
@@ -0,0 +1,109 @@
|
|||||||
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { Payment } from '../../../../models/Payment';
|
||||||
|
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals, url }) => {
|
||||||
|
const auth = await locals.auth();
|
||||||
|
if (!auth || !auth.user?.nickname) {
|
||||||
|
throw error(401, 'Not logged in');
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = parseInt(url.searchParams.get('limit') || '20');
|
||||||
|
const offset = parseInt(url.searchParams.get('offset') || '0');
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payments = await Payment.find()
|
||||||
|
.populate('splits')
|
||||||
|
.sort({ date: -1, createdAt: -1 })
|
||||||
|
.limit(limit)
|
||||||
|
.skip(offset)
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
return json({ payments });
|
||||||
|
} catch (e) {
|
||||||
|
throw error(500, 'Failed to fetch 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, date, image, category, splitMethod, splits } = data;
|
||||||
|
|
||||||
|
if (!title || !amount || !paidBy || !splitMethod || !splits) {
|
||||||
|
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 (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 payment = await Payment.create({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
amount,
|
||||||
|
currency: 'CHF',
|
||||||
|
paidBy,
|
||||||
|
date: date ? new Date(date) : new Date(),
|
||||||
|
image,
|
||||||
|
category: category || 'groceries',
|
||||||
|
splitMethod,
|
||||||
|
createdBy: auth.user.nickname
|
||||||
|
});
|
||||||
|
|
||||||
|
const splitPromises = splits.map((split: any) => {
|
||||||
|
return PaymentSplit.create({
|
||||||
|
paymentId: payment._id,
|
||||||
|
username: split.username,
|
||||||
|
amount: split.amount,
|
||||||
|
proportion: split.proportion,
|
||||||
|
personalAmount: split.personalAmount
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.all(splitPromises);
|
||||||
|
|
||||||
|
return json({
|
||||||
|
success: true,
|
||||||
|
payment: payment._id
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error creating payment:', e);
|
||||||
|
throw error(500, 'Failed to create payment');
|
||||||
|
} finally {
|
||||||
|
await dbDisconnect();
|
||||||
|
}
|
||||||
|
};
|
||||||
126
src/routes/api/cospend/payments/[id]/+server.ts
Normal file
126
src/routes/api/cospend/payments/[id]/+server.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { Payment } from '../../../../../models/Payment';
|
||||||
|
import { PaymentSplit } from '../../../../../models/PaymentSplit';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payment = await Payment.findById(id).populate('splits').lean();
|
||||||
|
|
||||||
|
if (!payment) {
|
||||||
|
throw error(404, 'Payment not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({ payment });
|
||||||
|
} catch (e) {
|
||||||
|
if (e.status === 404) throw e;
|
||||||
|
throw error(500, 'Failed to fetch 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;
|
||||||
|
const data = await request.json();
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payment = await Payment.findById(id);
|
||||||
|
|
||||||
|
if (!payment) {
|
||||||
|
throw error(404, 'Payment not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payment.createdBy !== auth.user.nickname) {
|
||||||
|
throw error(403, 'Not authorized to edit this payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedPayment = await Payment.findByIdAndUpdate(
|
||||||
|
id,
|
||||||
|
{
|
||||||
|
title: data.title,
|
||||||
|
description: data.description,
|
||||||
|
amount: data.amount,
|
||||||
|
paidBy: data.paidBy,
|
||||||
|
date: data.date ? new Date(data.date) : payment.date,
|
||||||
|
image: data.image,
|
||||||
|
category: data.category || payment.category,
|
||||||
|
splitMethod: data.splitMethod
|
||||||
|
},
|
||||||
|
{ new: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (data.splits) {
|
||||||
|
await PaymentSplit.deleteMany({ paymentId: id });
|
||||||
|
|
||||||
|
const splitPromises = data.splits.map((split: any) => {
|
||||||
|
return PaymentSplit.create({
|
||||||
|
paymentId: id,
|
||||||
|
username: split.username,
|
||||||
|
amount: split.amount,
|
||||||
|
proportion: split.proportion,
|
||||||
|
personalAmount: split.personalAmount
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await Promise.all(splitPromises);
|
||||||
|
}
|
||||||
|
|
||||||
|
return json({ success: true, payment: updatedPayment });
|
||||||
|
} catch (e) {
|
||||||
|
if (e.status) throw e;
|
||||||
|
throw error(500, 'Failed to update 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;
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payment = await Payment.findById(id);
|
||||||
|
|
||||||
|
if (!payment) {
|
||||||
|
throw error(404, 'Payment not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payment.createdBy !== auth.user.nickname) {
|
||||||
|
throw error(403, 'Not authorized to delete this payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
await PaymentSplit.deleteMany({ paymentId: id });
|
||||||
|
await Payment.findByIdAndDelete(id);
|
||||||
|
|
||||||
|
return json({ success: true });
|
||||||
|
} catch (e) {
|
||||||
|
if (e.status) throw e;
|
||||||
|
throw error(500, 'Failed to delete payment');
|
||||||
|
} finally {
|
||||||
|
await dbDisconnect();
|
||||||
|
}
|
||||||
|
};
|
||||||
139
src/routes/api/cospend/recurring-payments/+server.ts
Normal file
139
src/routes/api/cospend/recurring-payments/+server.ts
Normal 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();
|
||||||
|
}
|
||||||
|
};
|
||||||
184
src/routes/api/cospend/recurring-payments/[id]/+server.ts
Normal file
184
src/routes/api/cospend/recurring-payments/[id]/+server.ts
Normal 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();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
};
|
||||||
104
src/routes/api/cospend/recurring-payments/execute/+server.ts
Normal file
104
src/routes/api/cospend/recurring-payments/execute/+server.ts
Normal 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();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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');
|
||||||
|
}
|
||||||
|
};
|
||||||
63
src/routes/api/cospend/upload/+server.ts
Normal file
63
src/routes/api/cospend/upload/+server.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
import { writeFileSync, mkdirSync } from 'fs';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
|
import { IMAGE_DIR } from '$env/static/private';
|
||||||
|
|
||||||
|
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 formData = await request.formData();
|
||||||
|
const image = formData.get('image') as File;
|
||||||
|
|
||||||
|
if (!image) {
|
||||||
|
throw error(400, 'No image provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
|
||||||
|
if (!allowedTypes.includes(image.type)) {
|
||||||
|
throw error(400, 'Invalid file type. Only JPEG, PNG, and WebP are allowed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (image.size > 5 * 1024 * 1024) {
|
||||||
|
throw error(400, 'File too large. Maximum size is 5MB.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const extension = image.type.split('/')[1];
|
||||||
|
const filename = `${randomUUID()}.${extension}`;
|
||||||
|
|
||||||
|
if (!IMAGE_DIR) {
|
||||||
|
throw error(500, 'IMAGE_DIR environment variable not configured');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure cospend directory exists in IMAGE_DIR
|
||||||
|
const uploadsDir = join(IMAGE_DIR, 'cospend');
|
||||||
|
try {
|
||||||
|
mkdirSync(uploadsDir, { recursive: true });
|
||||||
|
} catch (err) {
|
||||||
|
// Directory might already exist
|
||||||
|
}
|
||||||
|
|
||||||
|
const filepath = join(uploadsDir, filename);
|
||||||
|
const buffer = await image.arrayBuffer();
|
||||||
|
|
||||||
|
writeFileSync(filepath, new Uint8Array(buffer));
|
||||||
|
|
||||||
|
const publicPath = `/cospend/${filename}`;
|
||||||
|
|
||||||
|
return json({
|
||||||
|
success: true,
|
||||||
|
path: publicPath
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
if (err.status) throw err;
|
||||||
|
console.error('Upload error:', err);
|
||||||
|
throw error(500, 'Failed to upload file');
|
||||||
|
}
|
||||||
|
};
|
||||||
112
src/routes/api/rezepte/favorites/+server.ts
Normal file
112
src/routes/api/rezepte/favorites/+server.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { UserFavorites } from '../../../../models/UserFavorites';
|
||||||
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw error(401, 'Authentication required');
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userFavorites = await UserFavorites.findOne({
|
||||||
|
username: session.user.nickname
|
||||||
|
}).lean();
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
return json({
|
||||||
|
favorites: userFavorites?.favorites || []
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
await dbDisconnect();
|
||||||
|
throw error(500, 'Failed to fetch favorites');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw error(401, 'Authentication required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { recipeId } = await request.json();
|
||||||
|
|
||||||
|
if (!recipeId) {
|
||||||
|
throw error(400, 'Recipe ID required');
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Validate that the recipe exists and get its ObjectId
|
||||||
|
const recipe = await Recipe.findOne({ short_name: recipeId });
|
||||||
|
if (!recipe) {
|
||||||
|
await dbDisconnect();
|
||||||
|
throw error(404, 'Recipe not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
await UserFavorites.findOneAndUpdate(
|
||||||
|
{ username: session.user.nickname },
|
||||||
|
{ $addToSet: { favorites: recipe._id } },
|
||||||
|
{ upsert: true, new: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
return json({ success: true });
|
||||||
|
} catch (e) {
|
||||||
|
await dbDisconnect();
|
||||||
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
throw error(500, 'Failed to add favorite');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DELETE: RequestHandler = async ({ request, locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw error(401, 'Authentication required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { recipeId } = await request.json();
|
||||||
|
|
||||||
|
if (!recipeId) {
|
||||||
|
throw error(400, 'Recipe ID required');
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Find the recipe's ObjectId
|
||||||
|
const recipe = await Recipe.findOne({ short_name: recipeId });
|
||||||
|
if (!recipe) {
|
||||||
|
await dbDisconnect();
|
||||||
|
throw error(404, 'Recipe not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
await UserFavorites.findOneAndUpdate(
|
||||||
|
{ username: session.user.nickname },
|
||||||
|
{ $pull: { favorites: recipe._id } }
|
||||||
|
);
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
return json({ success: true });
|
||||||
|
} catch (e) {
|
||||||
|
await dbDisconnect();
|
||||||
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
throw error(500, 'Failed to remove favorite');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { UserFavorites } from '../../../../../../models/UserFavorites';
|
||||||
|
import { Recipe } from '../../../../../../models/Recipe';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../../../utils/db';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals, params }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
return json({ isFavorite: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Find the recipe by short_name to get its ObjectId
|
||||||
|
const recipe = await Recipe.findOne({ short_name: params.shortName });
|
||||||
|
if (!recipe) {
|
||||||
|
await dbDisconnect();
|
||||||
|
throw error(404, 'Recipe not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if this recipe is in the user's favorites
|
||||||
|
const userFavorites = await UserFavorites.findOne({
|
||||||
|
username: session.user.nickname,
|
||||||
|
favorites: recipe._id
|
||||||
|
}).lean();
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
return json({
|
||||||
|
isFavorite: !!userFavorites
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
await dbDisconnect();
|
||||||
|
if (e instanceof Error && e.message.includes('404')) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
throw error(500, 'Failed to check favorite status');
|
||||||
|
}
|
||||||
|
};
|
||||||
40
src/routes/api/rezepte/favorites/recipes/+server.ts
Normal file
40
src/routes/api/rezepte/favorites/recipes/+server.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { UserFavorites } from '../../../../../models/UserFavorites';
|
||||||
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
||||||
|
import type { RecipeModelType } from '../../../../../types/types';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw error(401, 'Authentication required');
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const userFavorites = await UserFavorites.findOne({
|
||||||
|
username: session.user.nickname
|
||||||
|
}).lean();
|
||||||
|
|
||||||
|
if (!userFavorites?.favorites?.length) {
|
||||||
|
await dbDisconnect();
|
||||||
|
return json([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let recipes = await Recipe.find({
|
||||||
|
_id: { $in: userFavorites.favorites }
|
||||||
|
}).lean() as RecipeModelType[];
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
recipes = JSON.parse(JSON.stringify(recipes));
|
||||||
|
|
||||||
|
return json(recipes);
|
||||||
|
} catch (e) {
|
||||||
|
await dbDisconnect();
|
||||||
|
throw error(500, 'Failed to fetch favorite recipes');
|
||||||
|
}
|
||||||
|
};
|
||||||
32
src/routes/api/rezepte/json-ld/[name]/+server.ts
Normal file
32
src/routes/api/rezepte/json-ld/[name]/+server.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { Recipe } from '../../../../../models/Recipe';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../../utils/db';
|
||||||
|
import { generateRecipeJsonLd } from '$lib/js/recipeJsonLd';
|
||||||
|
import type { RecipeModelType } from '../../../../../types/types';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ params, setHeaders }) => {
|
||||||
|
await dbConnect();
|
||||||
|
let recipe = (await Recipe.findOne({ short_name: params.name }).lean()) as RecipeModelType;
|
||||||
|
await dbDisconnect();
|
||||||
|
|
||||||
|
recipe = JSON.parse(JSON.stringify(recipe));
|
||||||
|
if (recipe == null) {
|
||||||
|
throw error(404, "Recipe not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
const jsonLd = generateRecipeJsonLd(recipe);
|
||||||
|
|
||||||
|
// Set appropriate headers for JSON-LD
|
||||||
|
setHeaders({
|
||||||
|
'Content-Type': 'application/ld+json',
|
||||||
|
'Cache-Control': 'public, max-age=3600' // Cache for 1 hour
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Response(JSON.stringify(jsonLd, null, 2), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/ld+json',
|
||||||
|
'Cache-Control': 'public, max-age=3600'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
74
src/routes/api/rezepte/search/+server.ts
Normal file
74
src/routes/api/rezepte/search/+server.ts
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
import { json, type RequestHandler } from '@sveltejs/kit';
|
||||||
|
import type { BriefRecipeType } from '../../../../types/types';
|
||||||
|
import { Recipe } from '../../../../models/Recipe';
|
||||||
|
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ url, locals }) => {
|
||||||
|
await dbConnect();
|
||||||
|
|
||||||
|
const query = url.searchParams.get('q')?.toLowerCase().trim() || '';
|
||||||
|
const category = url.searchParams.get('category');
|
||||||
|
const tag = url.searchParams.get('tag');
|
||||||
|
const icon = url.searchParams.get('icon');
|
||||||
|
const season = url.searchParams.get('season');
|
||||||
|
const favoritesOnly = url.searchParams.get('favorites') === 'true';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Build base query
|
||||||
|
let dbQuery: any = {};
|
||||||
|
|
||||||
|
// Apply filters based on context
|
||||||
|
if (category) {
|
||||||
|
dbQuery.category = category;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tag) {
|
||||||
|
dbQuery.tags = { $in: [tag] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (icon) {
|
||||||
|
dbQuery.icon = icon;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (season) {
|
||||||
|
const seasonNum = parseInt(season);
|
||||||
|
if (!isNaN(seasonNum)) {
|
||||||
|
dbQuery.season = { $in: [seasonNum] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all recipes matching base filters
|
||||||
|
let recipes = await Recipe.find(dbQuery, 'name short_name tags category icon description season dateModified').lean() as BriefRecipeType[];
|
||||||
|
|
||||||
|
// Handle favorites filter
|
||||||
|
if (favoritesOnly && locals.session?.user) {
|
||||||
|
const { UserFavorites } = await import('../../../../models/UserFavorites');
|
||||||
|
const userFavorites = await UserFavorites.findOne({ username: locals.session.user.username });
|
||||||
|
if (userFavorites && userFavorites.favorites) {
|
||||||
|
const favoriteIds = userFavorites.favorites;
|
||||||
|
recipes = recipes.filter(recipe => favoriteIds.some(id => id.toString() === recipe._id?.toString()));
|
||||||
|
} else {
|
||||||
|
recipes = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply text search if query provided
|
||||||
|
if (query) {
|
||||||
|
const searchTerms = query.normalize('NFD').replace(/\p{Diacritic}/gu, "").split(" ");
|
||||||
|
|
||||||
|
recipes = recipes.filter(recipe => {
|
||||||
|
const searchString = `${recipe.name} ${recipe.description || ''} ${recipe.tags?.join(' ') || ''}`.toLowerCase()
|
||||||
|
.normalize('NFD').replace(/\p{Diacritic}/gu, "").replace(/­|/g, '');
|
||||||
|
|
||||||
|
return searchTerms.every(term => searchString.includes(term));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await dbDisconnect();
|
||||||
|
return json(JSON.parse(JSON.stringify(recipes)));
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
await dbDisconnect();
|
||||||
|
return json({ error: 'Search failed' }, { status: 500 });
|
||||||
|
}
|
||||||
|
};
|
||||||
7
src/routes/cospend/+layout.server.ts
Normal file
7
src/routes/cospend/+layout.server.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { LayoutServerLoad } from "./$types"
|
||||||
|
|
||||||
|
export const load : LayoutServerLoad = async ({locals}) => {
|
||||||
|
return {
|
||||||
|
session: await locals.auth()
|
||||||
|
}
|
||||||
|
};
|
||||||
160
src/routes/cospend/+layout.svelte
Normal file
160
src/routes/cospend/+layout.svelte
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
<script>
|
||||||
|
import { page } from '$app/stores';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import { fly } from 'svelte/transition';
|
||||||
|
import { quintOut } from 'svelte/easing';
|
||||||
|
import PaymentModal from '$lib/components/PaymentModal.svelte';
|
||||||
|
import Header from '$lib/components/Header.svelte';
|
||||||
|
import UserHeader from '$lib/components/UserHeader.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
let showModal = false;
|
||||||
|
let paymentId = null;
|
||||||
|
let user;
|
||||||
|
|
||||||
|
if (data.session) {
|
||||||
|
user = data.session.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
$: {
|
||||||
|
// Check if URL contains payment view route OR if we have paymentId in state
|
||||||
|
const match = $page.url.pathname.match(/\/cospend\/payments\/view\/([^\/]+)/);
|
||||||
|
const statePaymentId = $page.state?.paymentId;
|
||||||
|
const isOnDashboard = $page.route.id === '/cospend';
|
||||||
|
|
||||||
|
// Only show modal if we're on the dashboard AND have a payment to show
|
||||||
|
if (isOnDashboard && (match || statePaymentId)) {
|
||||||
|
showModal = true;
|
||||||
|
paymentId = match ? match[1] : statePaymentId;
|
||||||
|
} else {
|
||||||
|
showModal = false;
|
||||||
|
paymentId = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handlePaymentDeleted() {
|
||||||
|
// Close the modal
|
||||||
|
showModal = false;
|
||||||
|
paymentId = null;
|
||||||
|
|
||||||
|
// Dispatch a custom event to trigger dashboard refresh
|
||||||
|
if ($page.route.id === '/cospend') {
|
||||||
|
window.dispatchEvent(new CustomEvent('dashboardRefresh'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Header>
|
||||||
|
<ul class="site_header" slot="links">
|
||||||
|
<li><a href="/cospend">Dashboard</a></li>
|
||||||
|
<li><a href="/cospend/payments">All Payments</a></li>
|
||||||
|
<li><a href="/cospend/recurring">Recurring Payments</a></li>
|
||||||
|
</ul>
|
||||||
|
<UserHeader slot="right_side" {user}></UserHeader>
|
||||||
|
|
||||||
|
<div class="layout-container" class:has-modal={showModal}>
|
||||||
|
<div class="main-content">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="side-panel">
|
||||||
|
{#if showModal}
|
||||||
|
<div class="modal-content">
|
||||||
|
{#key paymentId}
|
||||||
|
<div in:fly={{x: 50, duration: 300, easing: quintOut}} out:fly={{x: -50, duration: 300, easing: quintOut}}>
|
||||||
|
<PaymentModal {paymentId} on:close={() => showModal = false} on:paymentDeleted={handlePaymentDeleted} />
|
||||||
|
</div>
|
||||||
|
{/key}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Header>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.layout-container {
|
||||||
|
display: flex;
|
||||||
|
min-height: calc(100vh - 4rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-content {
|
||||||
|
flex: 1;
|
||||||
|
transition: margin-right 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layout-container.has-modal .main-content {
|
||||||
|
margin-right: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.side-panel {
|
||||||
|
position: fixed;
|
||||||
|
top: 4rem;
|
||||||
|
right: 0;
|
||||||
|
width: 400px;
|
||||||
|
height: calc(100vh - 4rem);
|
||||||
|
background: #fbf9f3;
|
||||||
|
border-left: 1px solid #dee2e6;
|
||||||
|
box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);
|
||||||
|
z-index: 100;
|
||||||
|
overflow-y: auto;
|
||||||
|
transform: translateX(100%);
|
||||||
|
transition: transform 0.3s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layout-container.has-modal .side-panel {
|
||||||
|
transform: translateX(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
position: relative;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content > div {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.side-panel {
|
||||||
|
background: var(--background-dark);
|
||||||
|
border-left-color: #434C5E;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.layout-container.has-modal {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layout-container.has-modal .main-content {
|
||||||
|
flex: none;
|
||||||
|
height: 50vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.side-panel {
|
||||||
|
flex: none;
|
||||||
|
height: 50vh;
|
||||||
|
min-width: unset;
|
||||||
|
max-width: unset;
|
||||||
|
border-left: none;
|
||||||
|
border-top: 1px solid #dee2e6;
|
||||||
|
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
|
||||||
|
top: auto;
|
||||||
|
bottom: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) and (prefers-color-scheme: dark) {
|
||||||
|
.side-panel {
|
||||||
|
border-top-color: #434C5E;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
38
src/routes/cospend/+page.server.ts
Normal file
38
src/routes/cospend/+page.server.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
import { redirect, error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
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,
|
||||||
|
balance,
|
||||||
|
debtData
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error loading dashboard data:', e);
|
||||||
|
throw error(500, 'Failed to load dashboard data');
|
||||||
|
}
|
||||||
|
};
|
||||||
729
src/routes/cospend/+page.svelte
Normal file
729
src/routes/cospend/+page.svelte
Normal file
@@ -0,0 +1,729 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { page } from '$app/stores';
|
||||||
|
import { pushState } from '$app/navigation';
|
||||||
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import EnhancedBalance from '$lib/components/EnhancedBalance.svelte';
|
||||||
|
import DebtBreakdown from '$lib/components/DebtBreakdown.svelte';
|
||||||
|
import BarChart from '$lib/components/BarChart.svelte';
|
||||||
|
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||||
|
import { isSettlementPayment, getSettlementIcon, getSettlementClasses, getSettlementReceiver } from '$lib/utils/settlements';
|
||||||
|
import AddButton from '$lib/components/AddButton.svelte';
|
||||||
|
|
||||||
|
export let data; // Contains session data and balance from server
|
||||||
|
|
||||||
|
// Use server-side data, with fallback for progressive enhancement
|
||||||
|
let balance = data.balance || {
|
||||||
|
netBalance: 0,
|
||||||
|
recentSplits: []
|
||||||
|
};
|
||||||
|
let loading = false; // Start as false since we have server data
|
||||||
|
let error = null;
|
||||||
|
let monthlyExpensesData = { labels: [], datasets: [] };
|
||||||
|
let expensesLoading = false;
|
||||||
|
|
||||||
|
// Component references for refreshing
|
||||||
|
let enhancedBalanceComponent;
|
||||||
|
let debtBreakdownComponent;
|
||||||
|
|
||||||
|
// 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 Promise.all([
|
||||||
|
fetchBalance(),
|
||||||
|
fetchMonthlyExpenses()
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Listen for dashboard refresh events from the layout
|
||||||
|
const handleDashboardRefresh = () => {
|
||||||
|
refreshAllComponents();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('dashboardRefresh', handleDashboardRefresh);
|
||||||
|
|
||||||
|
// Cleanup
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('dashboardRefresh', handleDashboardRefresh);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
async function fetchBalance() {
|
||||||
|
try {
|
||||||
|
loading = true;
|
||||||
|
const response = await fetch('/api/cospend/balance');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch balance');
|
||||||
|
}
|
||||||
|
balance = await response.json();
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchMonthlyExpenses() {
|
||||||
|
try {
|
||||||
|
expensesLoading = true;
|
||||||
|
const response = await fetch('/api/cospend/monthly-expenses');
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch monthly expenses');
|
||||||
|
}
|
||||||
|
monthlyExpensesData = await response.json();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error fetching monthly expenses:', err);
|
||||||
|
// Don't show this error in the main error state
|
||||||
|
} finally {
|
||||||
|
expensesLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function to refresh all dashboard components after payment deletion
|
||||||
|
async function refreshAllComponents() {
|
||||||
|
// Refresh the main balance and recent activity
|
||||||
|
await Promise.all([
|
||||||
|
fetchBalance(),
|
||||||
|
fetchMonthlyExpenses()
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Refresh the enhanced balance component if it exists and has a refresh method
|
||||||
|
if (enhancedBalanceComponent && enhancedBalanceComponent.refresh) {
|
||||||
|
await enhancedBalanceComponent.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the debt breakdown component if it exists and has a refresh method
|
||||||
|
if (debtBreakdownComponent && debtBreakdownComponent.refresh) {
|
||||||
|
await debtBreakdownComponent.refresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
function truncateDescription(description, maxLength = 100) {
|
||||||
|
if (!description) return '';
|
||||||
|
if (description.length <= maxLength) return description;
|
||||||
|
return description.substring(0, maxLength).trim() + '...';
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePaymentClick(paymentId, event) {
|
||||||
|
// Progressive enhancement: if JavaScript is available, use pushState for modal behavior
|
||||||
|
if (typeof pushState !== 'undefined') {
|
||||||
|
event.preventDefault();
|
||||||
|
pushState(`/cospend/payments/view/${paymentId}`, { paymentId });
|
||||||
|
}
|
||||||
|
// Otherwise, let the regular link navigation happen (no preventDefault)
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSettlementReceiverFromSplit(split) {
|
||||||
|
if (!isSettlementPayment(split.paymentId)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// In a settlement, the receiver is the person who is NOT the payer
|
||||||
|
// Since we're viewing the current user's activity, the receiver is the current user
|
||||||
|
// when someone else paid, or the other user when current user paid
|
||||||
|
|
||||||
|
const paidBy = split.paymentId?.paidBy;
|
||||||
|
const currentUser = data.session?.user?.nickname;
|
||||||
|
|
||||||
|
if (paidBy === currentUser) {
|
||||||
|
// Current user paid, so receiver is the other user
|
||||||
|
return split.otherUser || '';
|
||||||
|
} else {
|
||||||
|
// Someone else paid, so current user is the receiver
|
||||||
|
return currentUser;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Cospend - Expense Sharing</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="cospend-main">
|
||||||
|
<h1>Cospend</h1>
|
||||||
|
|
||||||
|
<EnhancedBalance bind:this={enhancedBalanceComponent} initialBalance={data.balance} initialDebtData={data.debtData} />
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
{#if balance.netBalance !== 0}
|
||||||
|
<a href="/cospend/settle" class="btn btn-settlement">Settle Debts</a>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DebtBreakdown bind:this={debtBreakdownComponent} />
|
||||||
|
|
||||||
|
<!-- Monthly Expenses Chart -->
|
||||||
|
<div class="chart-section">
|
||||||
|
{#if expensesLoading}
|
||||||
|
<div class="loading">Loading monthly expenses chart...</div>
|
||||||
|
{:else if monthlyExpensesData.datasets && monthlyExpensesData.datasets.length > 0}
|
||||||
|
<BarChart
|
||||||
|
data={monthlyExpensesData}
|
||||||
|
title="Monthly Expenses by Category"
|
||||||
|
height="400px"
|
||||||
|
/>
|
||||||
|
{:else}
|
||||||
|
<div class="loading">
|
||||||
|
Debug: expensesLoading={expensesLoading},
|
||||||
|
datasets={monthlyExpensesData.datasets?.length || 0},
|
||||||
|
data={JSON.stringify(monthlyExpensesData)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading recent activity...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if balance.recentSplits && balance.recentSplits.length > 0}
|
||||||
|
<div class="recent-activity">
|
||||||
|
<h2>Recent Activity</h2>
|
||||||
|
<div class="activity-dialog">
|
||||||
|
{#each balance.recentSplits as split}
|
||||||
|
{#if isSettlementPayment(split.paymentId)}
|
||||||
|
<!-- Settlement Payment Display - User -> User Flow -->
|
||||||
|
<a
|
||||||
|
href="/cospend/payments/view/{split.paymentId?._id}"
|
||||||
|
class="settlement-flow-activity"
|
||||||
|
on:click={(e) => handlePaymentClick(split.paymentId?._id, e)}
|
||||||
|
>
|
||||||
|
<div class="settlement-activity-content">
|
||||||
|
<div class="settlement-user-flow">
|
||||||
|
<div class="settlement-payer">
|
||||||
|
<ProfilePicture username={split.paymentId?.paidBy || 'Unknown'} size={64} />
|
||||||
|
<span class="settlement-username">{split.paymentId?.paidBy || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-arrow-section">
|
||||||
|
<div class="settlement-amount-large">
|
||||||
|
{formatCurrency(Math.abs(split.amount))}
|
||||||
|
</div>
|
||||||
|
<div class="settlement-flow-arrow">→</div>
|
||||||
|
<div class="settlement-date">{formatDate(split.createdAt)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-receiver">
|
||||||
|
<ProfilePicture username={getSettlementReceiverFromSplit(split) || 'Unknown'} size={64} />
|
||||||
|
<span class="settlement-username">{getSettlementReceiverFromSplit(split) || 'Unknown'}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
{:else}
|
||||||
|
<!-- Regular Payment Display - Speech Bubble Style -->
|
||||||
|
<div class="activity-message"
|
||||||
|
class:is-me={split.paymentId?.paidBy === data.session?.user?.nickname}>
|
||||||
|
<div class="message-content">
|
||||||
|
<ProfilePicture username={split.paymentId?.paidBy || 'Unknown'} size={36} />
|
||||||
|
<a
|
||||||
|
href="/cospend/payments/view/{split.paymentId?._id}"
|
||||||
|
class="activity-bubble"
|
||||||
|
on:click={(e) => handlePaymentClick(split.paymentId?._id, e)}
|
||||||
|
>
|
||||||
|
<div class="activity-header">
|
||||||
|
<div class="user-info">
|
||||||
|
<div class="payment-title-row">
|
||||||
|
<span class="category-emoji">{getCategoryEmoji(split.paymentId?.category || 'groceries')}</span>
|
||||||
|
<strong class="payment-title">{split.paymentId?.title || 'Payment'}</strong>
|
||||||
|
</div>
|
||||||
|
<span class="username">Paid by {split.paymentId?.paidBy || 'Unknown'}</span>
|
||||||
|
<span class="category-name">{getCategoryName(split.paymentId?.category || 'groceries')}</span>
|
||||||
|
</div>
|
||||||
|
<div class="activity-amount"
|
||||||
|
class:positive={split.amount < 0}
|
||||||
|
class:negative={split.amount > 0}>
|
||||||
|
{#if split.amount > 0}
|
||||||
|
-{formatCurrency(split.amount)}
|
||||||
|
{:else if split.amount < 0}
|
||||||
|
+{formatCurrency(split.amount)}
|
||||||
|
{:else}
|
||||||
|
{formatCurrency(split.amount)}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="payment-details">
|
||||||
|
<div class="payment-meta">
|
||||||
|
<span class="payment-date">{formatDate(split.createdAt)}</span>
|
||||||
|
</div>
|
||||||
|
{#if split.paymentId?.description}
|
||||||
|
<div class="payment-description">
|
||||||
|
{truncateDescription(split.paymentId.description)}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<AddButton href="/cospend/payments/add" />
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.cospend-main {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 2.5rem;
|
||||||
|
margin-block: 0.5rem 1.5rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.positive {
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.negative {
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.even {
|
||||||
|
color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
justify-content: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-settlement {
|
||||||
|
background: linear-gradient(135deg, var(--green), var(--lightblue));
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-settlement:hover {
|
||||||
|
background: linear-gradient(135deg, var(--lightblue), var(--green));
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity h2 {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.recent-activity {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.recent-activity h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-dialog {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me {
|
||||||
|
flex-direction: row-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-content {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.75rem;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me .message-content {
|
||||||
|
flex-direction: row-reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-bubble {
|
||||||
|
background: var(--nord5);
|
||||||
|
border-radius: 1rem;
|
||||||
|
padding: 1rem;
|
||||||
|
position: relative;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
display: block;
|
||||||
|
transition: all 0.2s;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me .activity-bubble {
|
||||||
|
background: var(--nord8);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.activity-bubble {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me .activity-bubble {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-bubble:hover {
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-bubble::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: 1rem;
|
||||||
|
width: 0;
|
||||||
|
height: 0;
|
||||||
|
border: 8px solid transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-bubble::before {
|
||||||
|
left: -15px;
|
||||||
|
border-right-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me .activity-bubble::before {
|
||||||
|
left: auto;
|
||||||
|
right: -15px;
|
||||||
|
border-left-color: var(--nord8);
|
||||||
|
border-right-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.activity-bubble::before {
|
||||||
|
border-right-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-message.is-me .activity-bubble::before {
|
||||||
|
border-left-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* New Settlement Flow Activity Styles */
|
||||||
|
.settlement-flow-activity {
|
||||||
|
display: block;
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
background: linear-gradient(135deg, var(--nord6), var(--nord5));
|
||||||
|
border: 2px solid var(--green);
|
||||||
|
border-radius: 1rem;
|
||||||
|
padding: 1.5rem;
|
||||||
|
margin: 0 auto 1rem auto;
|
||||||
|
max-width: 400px;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow-activity:hover {
|
||||||
|
box-shadow: 0 6px 20px rgba(163, 190, 140, 0.3);
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.settlement-flow-activity {
|
||||||
|
background: linear-gradient(135deg, var(--nord2), var(--nord1));
|
||||||
|
border-color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow-activity:hover {
|
||||||
|
box-shadow: 0 6px 20px rgba(163, 190, 140, 0.2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-activity-content {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-user-flow {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-payer, .settlement-receiver {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-username {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--green);
|
||||||
|
font-size: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-arrow-section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-large {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--green);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow-arrow {
|
||||||
|
font-size: 1.8rem;
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-date {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.settlement-date {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-info {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-title-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-emoji {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-name {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-title {
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.category-name {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-title {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-amount {
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 1rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-details {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-meta {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.paid-by, .payment-date {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-style: italic;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.paid-by, .payment-date {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.cospend-main {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 300px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mobile Settlement Flow */
|
||||||
|
.settlement-user-flow {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-payer, .settlement-receiver {
|
||||||
|
order: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-arrow-section {
|
||||||
|
order: 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow-arrow {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-large {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-section {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart-section .loading {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
padding: 2rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
text-align: center;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.chart-section .loading {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { error } from "@sveltejs/kit";
|
|
||||||
|
|
||||||
export async function load({ fetch, params}) {
|
|
||||||
let balance_res = await fetch(`/api/cospend/balance`);
|
|
||||||
if (!balance_res.ok) {
|
|
||||||
throw error(balance_res.status, `Failed to fetch balance`);
|
|
||||||
}
|
|
||||||
let balance = await balance_res.json();
|
|
||||||
const items_res = await fetch(`/api/cospend/page/1`);
|
|
||||||
if (!items_res.ok) {
|
|
||||||
throw error(items_res.status, `Failed to fetch items`);
|
|
||||||
}
|
|
||||||
let items = await items_res.json();
|
|
||||||
return {
|
|
||||||
balance,
|
|
||||||
items
|
|
||||||
};
|
|
||||||
}
|
|
||||||
34
src/routes/cospend/payments/+page.server.ts
Normal file
34
src/routes/cospend/payments/+page.server.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
import { redirect, error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
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,
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
};
|
||||||
699
src/routes/cospend/payments/+page.svelte
Normal file
699
src/routes/cospend/payments/+page.svelte
Normal file
@@ -0,0 +1,699 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||||
|
import { isSettlementPayment, getSettlementIcon, getSettlementReceiver } from '$lib/utils/settlements';
|
||||||
|
import AddButton from '$lib/components/AddButton.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
// 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 = 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) {
|
||||||
|
try {
|
||||||
|
loading = true;
|
||||||
|
const response = await fetch(`/api/cospend/payments?limit=${limit}&offset=${page * limit}`);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to load payments');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (page === 0) {
|
||||||
|
payments = result.payments;
|
||||||
|
} else {
|
||||||
|
payments = [...payments, ...result.payments];
|
||||||
|
}
|
||||||
|
|
||||||
|
hasMore = result.payments.length === limit;
|
||||||
|
currentPage = page;
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMore() {
|
||||||
|
if (!loading && hasMore) {
|
||||||
|
await loadPayments(currentPage + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deletePayment(paymentId) {
|
||||||
|
if (!confirm('Are you sure you want to delete this payment?')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/cospend/payments/${paymentId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
payments = payments.filter(p => p._id !== paymentId);
|
||||||
|
} catch (err) {
|
||||||
|
alert('Error: ' + err.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCurrency(amount) {
|
||||||
|
return new Intl.NumberFormat('de-CH', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'CHF'
|
||||||
|
}).format(amount);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateString) {
|
||||||
|
return new Date(dateString).toLocaleDateString('de-CH');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUserSplitAmount(payment, username) {
|
||||||
|
const split = payment.splits?.find(s => s.username === username);
|
||||||
|
return split ? split.amount : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSplitDescription(payment) {
|
||||||
|
if (!payment.splits || payment.splits.length === 0) return 'No splits';
|
||||||
|
|
||||||
|
if (payment.splitMethod === 'equal') {
|
||||||
|
return `Split equally among ${payment.splits.length} people`;
|
||||||
|
} else if (payment.splitMethod === 'full') {
|
||||||
|
return `Paid in full by ${payment.paidBy}`;
|
||||||
|
} else if (payment.splitMethod === 'personal_equal') {
|
||||||
|
return `Personal amounts + equal split among ${payment.splits.length} people`;
|
||||||
|
} else {
|
||||||
|
return `Custom split among ${payment.splits.length} people`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>All Payments - Cospend</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="payments-list">
|
||||||
|
<div class="header">
|
||||||
|
<div class="header-content">
|
||||||
|
<h1>All Payments</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if loading && payments.length === 0}
|
||||||
|
<div class="loading">Loading payments...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if payments.length === 0}
|
||||||
|
<div class="empty-state">
|
||||||
|
<div class="empty-content">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
|
||||||
|
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
|
||||||
|
</svg>
|
||||||
|
<h2>No payments yet</h2>
|
||||||
|
<p>Start by adding your first shared expense</p>
|
||||||
|
<a href="/cospend/payments/add" class="btn btn-primary">Add Your First Payment</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="payments-grid">
|
||||||
|
{#each payments as 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">
|
||||||
|
<div class="settlement-user-from">
|
||||||
|
<ProfilePicture username={payment.paidBy} size={32} />
|
||||||
|
<span class="username">{payment.paidBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-arrow">
|
||||||
|
<span class="arrow">→</span>
|
||||||
|
<span class="settlement-badge-small">Settlement</span>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-user-to">
|
||||||
|
<ProfilePicture username={getSettlementReceiver(payment)} size={32} />
|
||||||
|
<span class="username">{getSettlementReceiver(payment)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-amount">
|
||||||
|
<span class="amount settlement-amount-text">{formatCurrency(payment.amount)}</span>
|
||||||
|
<span class="date">{formatDate(payment.date)}</span>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="payment-title-section">
|
||||||
|
<ProfilePicture username={payment.paidBy} size={40} />
|
||||||
|
<div class="payment-title">
|
||||||
|
<div class="title-with-category">
|
||||||
|
<span class="category-emoji">{getCategoryEmoji(payment.category || 'groceries')}</span>
|
||||||
|
<h3>{payment.title}</h3>
|
||||||
|
</div>
|
||||||
|
<div class="payment-meta">
|
||||||
|
<span class="category-name">{getCategoryName(payment.category || 'groceries')}</span>
|
||||||
|
<span class="date">{formatDate(payment.date)}</span>
|
||||||
|
<span class="amount">{formatCurrency(payment.amount)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if payment.image}
|
||||||
|
<img src={payment.image} alt="Receipt" class="receipt-thumb" />
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.description}
|
||||||
|
<p class="payment-description">{payment.description}</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="payment-details">
|
||||||
|
<div class="detail-row">
|
||||||
|
<span class="label">Paid by:</span>
|
||||||
|
<span class="value">{payment.paidBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="detail-row">
|
||||||
|
<span class="label">Split:</span>
|
||||||
|
<span class="value">{getSplitDescription(payment)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.splits && payment.splits.length > 0}
|
||||||
|
<div class="splits-summary">
|
||||||
|
<h4>Split Details</h4>
|
||||||
|
<div class="splits-list">
|
||||||
|
{#each payment.splits as split}
|
||||||
|
<div class="split-item">
|
||||||
|
<span class="split-user">{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}
|
||||||
|
owed {formatCurrency(Math.abs(split.amount))}
|
||||||
|
{:else}
|
||||||
|
owes {formatCurrency(split.amount)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
</a>
|
||||||
|
{/each}
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<AddButton href="/cospend/payments/add" />
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.payments-list {
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin-block: 0 2rem;
|
||||||
|
margin-inline: auto;
|
||||||
|
color: var(--nord0);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: all 0.2s;
|
||||||
|
border: none;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-content svg {
|
||||||
|
color: var(--nord3);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-content h2 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-content p {
|
||||||
|
margin: 0 0 2rem 0;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.empty-content svg {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-content h2 {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-content p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payments-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
|
||||||
|
gap: 1.5rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card {
|
||||||
|
display: block;
|
||||||
|
background: var(--nord6);
|
||||||
|
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;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card:hover {
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
|
||||||
|
text-decoration: none;
|
||||||
|
color: inherit;
|
||||||
|
transform: translateY(-1px);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-card {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card:hover {
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-card {
|
||||||
|
background: linear-gradient(135deg, var(--nord6), var(--nord5));
|
||||||
|
border: 2px solid var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-card:hover {
|
||||||
|
box-shadow: 0 4px 16px rgba(163, 190, 140, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.settlement-card {
|
||||||
|
background: linear-gradient(135deg, var(--nord2), var(--nord1));
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-card:hover {
|
||||||
|
box-shadow: 0 4px 16px rgba(163, 190, 140, 0.2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-user-from, .settlement-user-to {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-user-from .username,
|
||||||
|
.settlement-user-to .username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-arrow {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-arrow .arrow {
|
||||||
|
color: var(--green);
|
||||||
|
font-size: 1.2rem;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-badge-small {
|
||||||
|
background: linear-gradient(135deg, var(--green), var(--lightblue));
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.375rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
font-size: 0.65rem;
|
||||||
|
font-weight: 500;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.025em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-end;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-text {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-title-section {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.75rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category .category-emoji {
|
||||||
|
font-size: 1.3rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-title h3 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-title h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-meta {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-meta .category-name {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-style: italic;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-meta .amount {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-meta {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-meta .category-name {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-thumb {
|
||||||
|
width: 60px;
|
||||||
|
height: 60px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.receipt-thumb {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord2);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-details {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row .label {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row .value {
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.detail-row .label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.detail-row .value {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-summary {
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
padding-top: 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-summary h4 {
|
||||||
|
margin: 0 0 0.75rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.splits-summary {
|
||||||
|
border-top-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-summary h4 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user {
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-user {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.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;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payments-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
</style>
|
||||||
229
src/routes/cospend/payments/add/+page.server.ts
Normal file
229
src/routes/cospend/payments/add/+page.server.ts
Normal file
@@ -0,0 +1,229 @@
|
|||||||
|
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();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
throw redirect(302, '/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
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';
|
||||||
|
|
||||||
|
// Recurring payment data
|
||||||
|
const isRecurring = formData.get('isRecurring') === 'true';
|
||||||
|
const recurringFrequency = formData.get('recurringFrequency')?.toString() || 'monthly';
|
||||||
|
const recurringCronExpression = formData.get('recurringCronExpression')?.toString() || '';
|
||||||
|
const recurringStartDate = formData.get('recurringStartDate')?.toString() || '';
|
||||||
|
const recurringEndDate = formData.get('recurringEndDate')?.toString() || '';
|
||||||
|
|
||||||
|
// Basic validation
|
||||||
|
if (!title || amount <= 0 || !paidBy) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Please fill in all required fields with valid values',
|
||||||
|
values: Object.fromEntries(formData)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recurring payment validation
|
||||||
|
if (isRecurring) {
|
||||||
|
if (recurringFrequency === 'custom' && !recurringCronExpression) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Please provide a cron expression for custom recurring payments',
|
||||||
|
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 their share of the full amount
|
||||||
|
const otherUsers = users.filter(user => user !== paidBy);
|
||||||
|
const amountPerOtherUser = otherUsers.length > 0 ? amount / otherUsers.length : 0;
|
||||||
|
|
||||||
|
splits = users.map(user => ({
|
||||||
|
username: user,
|
||||||
|
amount: user === paidBy ? -amount : amountPerOtherUser
|
||||||
|
}));
|
||||||
|
} 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)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const paymentResult = await response.json();
|
||||||
|
|
||||||
|
// If this is a recurring payment, create the recurring payment record
|
||||||
|
if (isRecurring) {
|
||||||
|
const recurringPayload = {
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
amount,
|
||||||
|
paidBy,
|
||||||
|
category,
|
||||||
|
splitMethod,
|
||||||
|
splits,
|
||||||
|
frequency: recurringFrequency,
|
||||||
|
cronExpression: recurringFrequency === 'custom' ? recurringCronExpression : undefined,
|
||||||
|
startDate: recurringStartDate ? new Date(recurringStartDate).toISOString() : new Date().toISOString(),
|
||||||
|
endDate: recurringEndDate ? new Date(recurringEndDate).toISOString() : null,
|
||||||
|
isActive: true,
|
||||||
|
nextExecutionDate: recurringStartDate ? new Date(recurringStartDate).toISOString() : new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
const recurringResponse = await fetch('/api/cospend/recurring-payments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(recurringPayload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!recurringResponse.ok) {
|
||||||
|
// Log the error but don't fail the entire operation since the payment was created
|
||||||
|
console.error('Failed to create recurring payment:', await recurringResponse.text());
|
||||||
|
// Could optionally return a warning to the user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success - redirect to dashboard
|
||||||
|
throw redirect(303, '/cospend');
|
||||||
|
|
||||||
|
} 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)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
867
src/routes/cospend/payments/add/+page.svelte
Normal file
867
src/routes/cospend/payments/add/+page.svelte
Normal file
@@ -0,0 +1,867 @@
|
|||||||
|
<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 { validateCronExpression, getFrequencyDescription, calculateNextExecutionDate } from '$lib/utils/recurring';
|
||||||
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import SplitMethodSelector from '$lib/components/SplitMethodSelector.svelte';
|
||||||
|
import UsersList from '$lib/components/UsersList.svelte';
|
||||||
|
import ImageUpload from '$lib/components/ImageUpload.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
export let form;
|
||||||
|
|
||||||
|
// Initialize form data with server values if available (for error handling)
|
||||||
|
let formData = {
|
||||||
|
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: [],
|
||||||
|
isRecurring: form?.values?.isRecurring === 'true' || false
|
||||||
|
};
|
||||||
|
|
||||||
|
// Recurring payment settings
|
||||||
|
let recurringData = {
|
||||||
|
frequency: form?.values?.recurringFrequency || 'monthly',
|
||||||
|
cronExpression: form?.values?.recurringCronExpression || '',
|
||||||
|
startDate: form?.values?.recurringStartDate || new Date().toISOString().split('T')[0],
|
||||||
|
endDate: form?.values?.recurringEndDate || ''
|
||||||
|
};
|
||||||
|
|
||||||
|
let imageFile = null;
|
||||||
|
let imagePreview = '';
|
||||||
|
let uploading = false;
|
||||||
|
let newUser = '';
|
||||||
|
let splitAmounts = {};
|
||||||
|
let personalAmounts = {};
|
||||||
|
let loading = false;
|
||||||
|
let error = form?.error || null;
|
||||||
|
let predefinedMode = data.predefinedUsers.length > 0;
|
||||||
|
let jsEnhanced = false;
|
||||||
|
let cronError = false;
|
||||||
|
let nextExecutionPreview = '';
|
||||||
|
|
||||||
|
// 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 = [...data.predefinedUsers];
|
||||||
|
users.forEach(user => addSplitForUser(user));
|
||||||
|
// Default to current user as payer if they're in the predefined list
|
||||||
|
if (data.currentUser && data.predefinedUsers.includes(data.currentUser)) {
|
||||||
|
formData.paidBy = data.currentUser;
|
||||||
|
} else {
|
||||||
|
formData.paidBy = data.predefinedUsers[0];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Original behavior for manual user management
|
||||||
|
if (data.currentUser) {
|
||||||
|
users = [data.currentUser];
|
||||||
|
addSplitForUser(data.currentUser);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleImageSelected(event) {
|
||||||
|
imageFile = event.detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageError(event) {
|
||||||
|
error = event.detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageRemoved() {
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSplitForUser(username) {
|
||||||
|
if (!splitAmounts[username]) {
|
||||||
|
splitAmounts[username] = 0;
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadImage() {
|
||||||
|
if (!imageFile) return null;
|
||||||
|
|
||||||
|
uploading = true;
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('image', imageFile);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/cospend/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to upload image');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
return result.path;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Image upload failed:', err);
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
uploading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (users.length === 0) {
|
||||||
|
error = 'Please add at least one user to split with';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
loading = true;
|
||||||
|
error = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let imagePath = null;
|
||||||
|
if (imageFile) {
|
||||||
|
imagePath = await uploadImage();
|
||||||
|
}
|
||||||
|
|
||||||
|
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),
|
||||||
|
image: imagePath,
|
||||||
|
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();
|
||||||
|
throw new Error(errorData.message || 'Failed to create payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
await goto('/cospend');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function validateCron() {
|
||||||
|
if (recurringData.frequency !== 'custom') {
|
||||||
|
cronError = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cronError = !validateCronExpression(recurringData.cronExpression);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateNextExecutionPreview() {
|
||||||
|
try {
|
||||||
|
if (recurringData.frequency && recurringData.startDate && formData.isRecurring) {
|
||||||
|
const recurringPayment = {
|
||||||
|
...recurringData,
|
||||||
|
startDate: new Date(recurringData.startDate)
|
||||||
|
};
|
||||||
|
const nextDate = calculateNextExecutionDate(recurringPayment, new Date(recurringData.startDate));
|
||||||
|
nextExecutionPreview = nextDate.toLocaleString('de-CH', {
|
||||||
|
weekday: 'long',
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'long',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit'
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
nextExecutionPreview = '';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
nextExecutionPreview = 'Invalid configuration';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$: if (recurringData.cronExpression) {
|
||||||
|
validateCron();
|
||||||
|
}
|
||||||
|
|
||||||
|
$: if (recurringData.frequency || recurringData.cronExpression || recurringData.startDate || formData.isRecurring) {
|
||||||
|
updateNextExecutionPreview();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Add Payment - Cospend</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="add-payment">
|
||||||
|
<div class="header">
|
||||||
|
<h1>Add New Payment</h1>
|
||||||
|
<p>Create a new shared expense or recurring payment</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form method="POST" use:enhance 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"
|
||||||
|
name="title"
|
||||||
|
value={formData.title}
|
||||||
|
required
|
||||||
|
placeholder="e.g., Dinner at restaurant"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="description">Description</label>
|
||||||
|
<textarea
|
||||||
|
id="description"
|
||||||
|
name="description"
|
||||||
|
value={formData.description}
|
||||||
|
placeholder="Additional details..."
|
||||||
|
rows="3"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="category">Category *</label>
|
||||||
|
<select id="category" name="category" 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"
|
||||||
|
name="amount"
|
||||||
|
bind:value={formData.amount}
|
||||||
|
required
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="date">Date</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
id="date"
|
||||||
|
name="date"
|
||||||
|
value={formData.date}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="paidBy">Paid by</label>
|
||||||
|
<select id="paidBy" name="paidBy" bind:value={formData.paidBy} required>
|
||||||
|
{#each users as user}
|
||||||
|
<option value={user}>{user}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label class="checkbox-label">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="isRecurring"
|
||||||
|
bind:checked={formData.isRecurring}
|
||||||
|
value="true"
|
||||||
|
/>
|
||||||
|
Make this a recurring payment
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if formData.isRecurring}
|
||||||
|
<div class="form-section">
|
||||||
|
<h2>Recurring Payment</h2>
|
||||||
|
|
||||||
|
<div class="recurring-options">
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="frequency">Frequency *</label>
|
||||||
|
<select id="frequency" name="recurringFrequency" bind:value={recurringData.frequency} required>
|
||||||
|
<option value="daily">Daily</option>
|
||||||
|
<option value="weekly">Weekly</option>
|
||||||
|
<option value="monthly">Monthly</option>
|
||||||
|
<option value="quarterly">Quarterly</option>
|
||||||
|
<option value="yearly">Yearly</option>
|
||||||
|
<option value="custom">Custom (Cron)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="recurringStartDate">Start Date *</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
id="recurringStartDate"
|
||||||
|
name="recurringStartDate"
|
||||||
|
bind:value={recurringData.startDate}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if recurringData.frequency === 'custom'}
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="recurringCronExpression">Cron Expression *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="recurringCronExpression"
|
||||||
|
name="recurringCronExpression"
|
||||||
|
bind:value={recurringData.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="recurringEndDate">End Date (optional)</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
id="recurringEndDate"
|
||||||
|
name="recurringEndDate"
|
||||||
|
bind:value={recurringData.endDate}
|
||||||
|
min={recurringData.startDate}
|
||||||
|
/>
|
||||||
|
<small class="help-text">Leave empty for indefinite recurring</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
{#if nextExecutionPreview}
|
||||||
|
<div class="execution-preview">
|
||||||
|
<h3>Next Execution</h3>
|
||||||
|
<p class="next-execution">{nextExecutionPreview}</p>
|
||||||
|
<p class="frequency-description">{getFrequencyDescription(recurringData)}</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<ImageUpload
|
||||||
|
bind:imagePreview={imagePreview}
|
||||||
|
bind:imageFile={imageFile}
|
||||||
|
bind:uploading={uploading}
|
||||||
|
on:imageSelected={handleImageSelected}
|
||||||
|
on:imageRemoved={handleImageRemoved}
|
||||||
|
on:error={handleImageError}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<UsersList
|
||||||
|
bind:users={users}
|
||||||
|
bind:newUser={newUser}
|
||||||
|
currentUser={data.session?.user?.nickname || data.currentUser}
|
||||||
|
predefinedMode={predefinedMode}
|
||||||
|
canRemoveUsers={!predefinedMode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- 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} Enter additional users..."
|
||||||
|
rows="4"
|
||||||
|
>{data.currentUser}</textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 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}
|
||||||
|
|
||||||
|
<SplitMethodSelector
|
||||||
|
bind:splitMethod={formData.splitMethod}
|
||||||
|
bind:splitAmounts={splitAmounts}
|
||||||
|
bind:personalAmounts={personalAmounts}
|
||||||
|
{users}
|
||||||
|
amount={formData.amount}
|
||||||
|
paidBy={formData.paidBy}
|
||||||
|
currentUser={data.session?.user?.nickname || data.currentUser}
|
||||||
|
{predefinedMode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if error}
|
||||||
|
<div class="error">{error}</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<a href="/cospend" class="btn-secondary">
|
||||||
|
Cancel
|
||||||
|
</a>
|
||||||
|
<button type="submit" class="btn-primary" disabled={loading}>
|
||||||
|
{loading ? 'Creating...' : (formData.isRecurring ? 'Create Recurring Payment' : 'Create Payment')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.add-payment {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
label {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
input, textarea, select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus, select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
input, textarea, select {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--red);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--blue);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-block;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* 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: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.manual-users p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Recurring payment styles */
|
||||||
|
.checkbox-label {
|
||||||
|
display: flex !important;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-label input[type="checkbox"] {
|
||||||
|
width: auto;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.recurring-options {
|
||||||
|
margin-top: 1rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.recurring-options {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.help-text {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text p {
|
||||||
|
margin: 0.5rem 0 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text code {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 0.125rem 0.25rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.85em;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.help-text code {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text ul {
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
padding-left: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text li {
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-error {
|
||||||
|
color: var(--red);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
input.error {
|
||||||
|
border-color: var(--red);
|
||||||
|
box-shadow: 0 0 0 2px rgba(191, 97, 106, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview {
|
||||||
|
background-color: var(--nord8);
|
||||||
|
border: 1px solid var(--blue);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview h3 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.next-execution {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--blue);
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.frequency-description {
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin: 0;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.execution-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.frequency-description {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.add-payment {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
15
src/routes/cospend/payments/edit/[id]/+page.server.ts
Normal file
15
src/routes/cospend/payments/edit/[id]/+page.server.ts
Normal 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,
|
||||||
|
paymentId: params.id
|
||||||
|
};
|
||||||
|
};
|
||||||
559
src/routes/cospend/payments/edit/[id]/+page.svelte
Normal file
559
src/routes/cospend/payments/edit/[id]/+page.svelte
Normal file
@@ -0,0 +1,559 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import { getCategoryOptions } from '$lib/utils/categories';
|
||||||
|
import FormSection from '$lib/components/FormSection.svelte';
|
||||||
|
import ImageUpload from '$lib/components/ImageUpload.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
let payment = null;
|
||||||
|
let loading = true;
|
||||||
|
let saving = false;
|
||||||
|
let uploading = false;
|
||||||
|
let error = null;
|
||||||
|
let imageFile = null;
|
||||||
|
let imagePreview = '';
|
||||||
|
|
||||||
|
$: categoryOptions = getCategoryOptions();
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
await loadPayment();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadPayment() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/cospend/payments/${data.paymentId}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to load payment');
|
||||||
|
}
|
||||||
|
const result = await response.json();
|
||||||
|
payment = result.payment;
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageSelected(event) {
|
||||||
|
imageFile = event.detail;
|
||||||
|
handleImageUpload();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageError(event) {
|
||||||
|
error = event.detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleImageRemoved() {
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCurrentImageRemoved() {
|
||||||
|
payment.image = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleImageUpload() {
|
||||||
|
if (!imageFile) return;
|
||||||
|
|
||||||
|
uploading = true;
|
||||||
|
try {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('image', imageFile);
|
||||||
|
|
||||||
|
const response = await fetch('/api/cospend/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to upload image');
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
payment.image = result.imageUrl;
|
||||||
|
imageFile = null;
|
||||||
|
imagePreview = '';
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
uploading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit() {
|
||||||
|
if (!payment) return;
|
||||||
|
|
||||||
|
saving = true;
|
||||||
|
error = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/cospend/payments/${data.paymentId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payment)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to update payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
await goto('/cospend/payments');
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
saving = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(dateString) {
|
||||||
|
return new Date(dateString).toISOString().split('T')[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
let deleting = false;
|
||||||
|
|
||||||
|
async function deletePayment() {
|
||||||
|
if (!confirm('Are you sure you want to delete this payment? This action cannot be undone.')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
deleting = true;
|
||||||
|
const response = await fetch(`/api/cospend/payments/${data.paymentId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to payments list after successful deletion
|
||||||
|
goto('/cospend/payments');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
deleting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Edit Payment - Cospend</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="edit-payment">
|
||||||
|
<div class="header">
|
||||||
|
<h1>Edit Payment</h1>
|
||||||
|
<p>Modify payment details and receipt image</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading payment...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if payment}
|
||||||
|
<form on:submit|preventDefault={handleSubmit} class="payment-form">
|
||||||
|
<FormSection title="Payment Details">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="title">Title *</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="title"
|
||||||
|
bind:value={payment.title}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="description">Description</label>
|
||||||
|
<textarea
|
||||||
|
id="description"
|
||||||
|
bind:value={payment.description}
|
||||||
|
rows="3"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="category">Category</label>
|
||||||
|
<select id="category" bind:value={payment.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={payment.amount}
|
||||||
|
required
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="date">Date</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
id="date"
|
||||||
|
value={formatDate(payment.date)}
|
||||||
|
on:change={(e) => payment.date = new Date(e.target.value).toISOString()}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="paidBy">Paid by</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="paidBy"
|
||||||
|
bind:value={payment.paidBy}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</FormSection>
|
||||||
|
|
||||||
|
<ImageUpload
|
||||||
|
bind:imagePreview={imagePreview}
|
||||||
|
bind:imageFile={imageFile}
|
||||||
|
bind:uploading={uploading}
|
||||||
|
currentImage={payment.image}
|
||||||
|
on:imageSelected={handleImageSelected}
|
||||||
|
on:imageRemoved={handleImageRemoved}
|
||||||
|
on:currentImageRemoved={handleCurrentImageRemoved}
|
||||||
|
on:error={handleImageError}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if payment.splits && payment.splits.length > 0}
|
||||||
|
<FormSection title="Current Splits">
|
||||||
|
<div class="splits-display">
|
||||||
|
{#each payment.splits as split}
|
||||||
|
<div class="split-item">
|
||||||
|
<span>{split.username}</span>
|
||||||
|
<span class:positive={split.amount < 0} class:negative={split.amount > 0}>
|
||||||
|
{#if split.amount > 0}
|
||||||
|
owes CHF {split.amount.toFixed(2)}
|
||||||
|
{:else if split.amount < 0}
|
||||||
|
owed CHF {Math.abs(split.amount).toFixed(2)}
|
||||||
|
{:else}
|
||||||
|
owes CHF {split.amount.toFixed(2)}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<p class="note">Note: To modify splits, please delete and recreate the payment.</p>
|
||||||
|
</FormSection>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-danger"
|
||||||
|
on:click={deletePayment}
|
||||||
|
disabled={deleting || saving}
|
||||||
|
>
|
||||||
|
{deleting ? 'Deleting...' : 'Delete Payment'}
|
||||||
|
</button>
|
||||||
|
<div class="main-actions">
|
||||||
|
<button type="button" class="btn-secondary" on:click={() => goto('/cospend/payments')}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" class="btn-primary" disabled={saving || deleting}>
|
||||||
|
{saving ? 'Saving...' : 'Save Changes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.edit-payment {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.form-section {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
label {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
input, textarea, select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus, select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
input, textarea, select {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-display {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-item {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.positive {
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.negative {
|
||||||
|
color: var(--red);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.note {
|
||||||
|
color: var(--nord2);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-style: italic;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.note {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary, .btn-secondary, .btn-danger {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover:not(:disabled) {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.edit-payment {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
28
src/routes/cospend/payments/view/[id]/+page.server.ts
Normal file
28
src/routes/cospend/payments/view/[id]/+page.server.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
import { redirect, error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
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,
|
||||||
|
payment: paymentData.payment
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error loading payment data:', e);
|
||||||
|
throw error(500, 'Failed to load payment data');
|
||||||
|
}
|
||||||
|
};
|
||||||
504
src/routes/cospend/payments/view/[id]/+page.svelte
Normal file
504
src/routes/cospend/payments/view/[id]/+page.svelte
Normal file
@@ -0,0 +1,504 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||||
|
import EditButton from '$lib/components/EditButton.svelte';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
|
||||||
|
// 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');
|
||||||
|
}
|
||||||
|
const result = await response.json();
|
||||||
|
payment = result.payment;
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSplitDescription(payment) {
|
||||||
|
if (!payment.splits || payment.splits.length === 0) return 'No splits';
|
||||||
|
|
||||||
|
if (payment.splitMethod === 'equal') {
|
||||||
|
return `Split equally among ${payment.splits.length} people`;
|
||||||
|
} else if (payment.splitMethod === 'full') {
|
||||||
|
return `Paid in full by ${payment.paidBy}`;
|
||||||
|
} else if (payment.splitMethod === 'personal_equal') {
|
||||||
|
return `Personal amounts + equal split among ${payment.splits.length} people`;
|
||||||
|
} else {
|
||||||
|
return `Custom split among ${payment.splits.length} people`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let deleting = false;
|
||||||
|
|
||||||
|
async function deletePayment() {
|
||||||
|
if (!confirm('Are you sure you want to delete this payment? This action cannot be undone.')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
deleting = true;
|
||||||
|
const response = await fetch(`/api/cospend/payments/${data.paymentId}`, {
|
||||||
|
method: 'DELETE'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to delete payment');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect to dashboard after successful deletion
|
||||||
|
goto('/cospend');
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
} finally {
|
||||||
|
deleting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>{payment ? payment.title : 'Payment'} - Cospend</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="payment-view">
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading payment...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if payment}
|
||||||
|
<div class="payment-card">
|
||||||
|
<div class="payment-header">
|
||||||
|
<div class="title-section">
|
||||||
|
<div class="title-with-category">
|
||||||
|
<span class="category-emoji">{getCategoryEmoji(payment.category || 'groceries')}</span>
|
||||||
|
<h1>{payment.title}</h1>
|
||||||
|
</div>
|
||||||
|
<div class="payment-amount">
|
||||||
|
{formatCurrency(payment.amount)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{#if payment.image}
|
||||||
|
<div class="receipt-image">
|
||||||
|
<img src={payment.image} alt="Receipt" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="payment-info">
|
||||||
|
<div class="info-grid">
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Date:</span>
|
||||||
|
<span class="value">{formatDate(payment.date)}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Paid by:</span>
|
||||||
|
<span class="value">{payment.paidBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Created by:</span>
|
||||||
|
<span class="value">{payment.createdBy}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Category:</span>
|
||||||
|
<span class="value">{getCategoryName(payment.category || 'groceries')}</span>
|
||||||
|
</div>
|
||||||
|
<div class="info-item">
|
||||||
|
<span class="label">Split method:</span>
|
||||||
|
<span class="value">{getSplitDescription(payment)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.description}
|
||||||
|
<div class="description">
|
||||||
|
<h3>Description</h3>
|
||||||
|
<p>{payment.description}</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if payment.splits && payment.splits.length > 0}
|
||||||
|
<div class="splits-section">
|
||||||
|
<h3>Split Details</h3>
|
||||||
|
<div class="splits-list">
|
||||||
|
{#each payment.splits as split}
|
||||||
|
<div class="split-item" class:current-user={split.username === data.session.user.nickname}>
|
||||||
|
<div class="split-user">
|
||||||
|
<ProfilePicture username={split.username} size={24} />
|
||||||
|
<div class="user-info">
|
||||||
|
<span class="username">{split.username}</span>
|
||||||
|
{#if split.username === data.session.user.nickname}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div 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}
|
||||||
|
owed {formatCurrency(split.amount)}
|
||||||
|
{:else}
|
||||||
|
owes {formatCurrency(split.amount)}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{#if payment && payment.createdBy === data.session.user.nickname}
|
||||||
|
<EditButton href="/cospend/payments/edit/{data.paymentId}" />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.payment-view {
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-card {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 2rem;
|
||||||
|
background: linear-gradient(135deg, var(--nord5), var(--nord4));
|
||||||
|
border-bottom: 1px solid var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-header {
|
||||||
|
background: linear-gradient(135deg, var(--nord2), var(--nord3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-with-category .category-emoji {
|
||||||
|
font-size: 2rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title-section h1 {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-amount {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.title-section h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-left: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image img {
|
||||||
|
max-width: 150px;
|
||||||
|
max-height: 150px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.receipt-image img {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-info {
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-item {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.description {
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
padding-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description h3 {
|
||||||
|
margin: 0 0 0.75rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.description p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord2);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.description {
|
||||||
|
border-top-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.description h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.description p {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section {
|
||||||
|
border-top: 1px solid var(--nord4);
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section h3 {
|
||||||
|
margin: 0 0 1rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.splits-section {
|
||||||
|
border-top-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-section h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1rem;
|
||||||
|
background: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item.current-user {
|
||||||
|
background: var(--nord8);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-item {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item.current-user {
|
||||||
|
background: var(--nord3);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-user .user-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.payment-view {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-header {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.receipt-image {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-content {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-item {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
14
src/routes/cospend/recurring/+page.server.ts
Normal file
14
src/routes/cospend/recurring/+page.server.ts
Normal 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
|
||||||
|
};
|
||||||
|
};
|
||||||
699
src/routes/cospend/recurring/+page.svelte
Normal file
699
src/routes/cospend/recurring/+page.svelte
Normal file
@@ -0,0 +1,699 @@
|
|||||||
|
<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';
|
||||||
|
import AddButton from '$lib/components/AddButton.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>
|
||||||
|
<p>Automate your regular shared expenses</p>
|
||||||
|
</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/payments/add" class="btn btn-primary">Add Your First 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}
|
||||||
|
owes {formatCurrency(split.amount)}
|
||||||
|
{/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>
|
||||||
|
|
||||||
|
<AddButton href="/cospend/payments/add" />
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.recurring-payments {
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header h1 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.filters {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.filters label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.filters {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.filters label {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state h2 {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state p {
|
||||||
|
color: var(--nord2);
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
max-width: 500px;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.empty-state {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payments-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card {
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
padding: 1.5rem;
|
||||||
|
transition: all 0.2s;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card:hover {
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card.inactive {
|
||||||
|
opacity: 0.7;
|
||||||
|
background: var(--nord5);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-card {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card:hover {
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-card.inactive {
|
||||||
|
background: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-title h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--green);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-badge.inactive {
|
||||||
|
background-color: var(--orange);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-amount {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord2);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.payment-description {
|
||||||
|
color: var(--nord5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--nord0);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.next-execution {
|
||||||
|
color: var(--blue);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.value {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.payer-info {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-preview {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-preview h4 {
|
||||||
|
margin: 0 0 0.75rem 0;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--nord2);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.splits-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.splits-preview h4 {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.positive {
|
||||||
|
color: var(--green);
|
||||||
|
}
|
||||||
|
|
||||||
|
.split-amount.negative {
|
||||||
|
color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.split-item .username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--blue);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: var(--nord10);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-warning {
|
||||||
|
background-color: var(--orange);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-warning:hover {
|
||||||
|
background-color: var(--nord12);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-success {
|
||||||
|
background-color: var(--green);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-success:hover {
|
||||||
|
background-color: var(--nord14);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background-color: var(--red);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover {
|
||||||
|
background-color: var(--nord11);
|
||||||
|
transform: translateY(-1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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>
|
||||||
15
src/routes/cospend/recurring/edit/[id]/+page.server.ts
Normal file
15
src/routes/cospend/recurring/edit/[id]/+page.server.ts
Normal 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
|
||||||
|
};
|
||||||
|
};
|
||||||
655
src/routes/cospend/recurring/edit/[id]/+page.svelte
Normal file
655
src/routes/cospend/recurring/edit/[id]/+page.svelte
Normal file
@@ -0,0 +1,655 @@
|
|||||||
|
<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';
|
||||||
|
import SplitMethodSelector from '$lib/components/SplitMethodSelector.svelte';
|
||||||
|
import UsersList from '$lib/components/UsersList.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 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 addSplitForUser(username) {
|
||||||
|
if (!splitAmounts[username]) {
|
||||||
|
splitAmounts[username] = 0;
|
||||||
|
splitAmounts = { ...splitAmounts };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (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.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>
|
||||||
|
|
||||||
|
<UsersList
|
||||||
|
bind:users={users}
|
||||||
|
bind:newUser={newUser}
|
||||||
|
currentUser={data.session?.user?.nickname}
|
||||||
|
{predefinedMode}
|
||||||
|
canRemoveUsers={!predefinedMode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SplitMethodSelector
|
||||||
|
bind:splitMethod={formData.splitMethod}
|
||||||
|
bind:splitAmounts={splitAmounts}
|
||||||
|
bind:personalAmounts={personalAmounts}
|
||||||
|
{users}
|
||||||
|
amount={formData.amount}
|
||||||
|
paidBy={formData.paidBy}
|
||||||
|
currentUser={data.session?.user?.nickname}
|
||||||
|
{predefinedMode}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#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: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.back-link {
|
||||||
|
color: var(--blue);
|
||||||
|
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: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--nord3);
|
||||||
|
}
|
||||||
|
|
||||||
|
input, textarea, select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
box-sizing: border-box;
|
||||||
|
background: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus, select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(136, 192, 208, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
input.error {
|
||||||
|
border-color: var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text code {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
padding: 0.125rem 0.25rem;
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
font-family: monospace;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text ul {
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
padding-left: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text li {
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-error {
|
||||||
|
color: var(--red);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview {
|
||||||
|
background-color: var(--nord8);
|
||||||
|
border: 1px solid var(--blue);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview h3 {
|
||||||
|
margin: 0 0 0.5rem 0;
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.next-execution {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--blue);
|
||||||
|
margin: 0.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.frequency-description {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin: 0;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--nord6);
|
||||||
|
color: var(--red);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
border: 1px solid var(--red);
|
||||||
|
}
|
||||||
|
|
||||||
|
.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: var(--blue);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background-color: var(--lightblue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
input, textarea, select {
|
||||||
|
background: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus, textarea:focus, select:focus {
|
||||||
|
box-shadow: 0 0 0 2px rgba(136, 192, 208, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text code {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.execution-preview {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
border-color: var(--blue);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.edit-recurring-payment {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
133
src/routes/cospend/settle/+page.server.ts
Normal file
133
src/routes/cospend/settle/+page.server.ts
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { PageServerLoad, Actions } from './$types';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ fetch, locals, request }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
throw redirect(302, '/login');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Fetch debt data server-side with authentication cookies
|
||||||
|
const response = await fetch('/api/cospend/debts', {
|
||||||
|
headers: {
|
||||||
|
'Cookie': request.headers.get('Cookie') || ''
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to fetch debt data');
|
||||||
|
}
|
||||||
|
|
||||||
|
const debtData = await response.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
debtData,
|
||||||
|
session,
|
||||||
|
currentUser: session.user?.nickname || ''
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error loading debt data:', error);
|
||||||
|
return {
|
||||||
|
debtData: {
|
||||||
|
whoOwesMe: [],
|
||||||
|
whoIOwe: [],
|
||||||
|
totalOwedToMe: 0,
|
||||||
|
totalIOwe: 0
|
||||||
|
},
|
||||||
|
error: error.message,
|
||||||
|
session,
|
||||||
|
currentUser: session.user?.nickname || ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const actions: Actions = {
|
||||||
|
settle: async ({ request, fetch, locals }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
|
||||||
|
const settlementType = data.get('settlementType');
|
||||||
|
const fromUser = data.get('fromUser');
|
||||||
|
const toUser = data.get('toUser');
|
||||||
|
const amount = parseFloat(data.get('amount'));
|
||||||
|
|
||||||
|
// Validation
|
||||||
|
if (!settlementType || !fromUser || !toUser || !amount) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'All fields are required',
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Please enter a valid positive amount',
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create a settlement payment
|
||||||
|
const payload = {
|
||||||
|
title: 'Settlement Payment',
|
||||||
|
description: `Settlement: ${fromUser} pays ${toUser}`,
|
||||||
|
amount: amount,
|
||||||
|
paidBy: fromUser,
|
||||||
|
date: new Date().toISOString().split('T')[0],
|
||||||
|
category: 'settlement',
|
||||||
|
splitMethod: 'full',
|
||||||
|
splits: [
|
||||||
|
{
|
||||||
|
username: fromUser,
|
||||||
|
amount: -amount // Payer gets negative (receives money back)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: toUser,
|
||||||
|
amount: amount // Receiver owes money
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch('/api/cospend/payments', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Cookie': request.headers.get('Cookie') || ''
|
||||||
|
},
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.json();
|
||||||
|
throw new Error(errorData.message || 'Failed to record settlement');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect back to dashboard on success
|
||||||
|
throw redirect(303, '/cospend');
|
||||||
|
} catch (error) {
|
||||||
|
if (error.status === 303) {
|
||||||
|
throw error; // Re-throw redirect
|
||||||
|
}
|
||||||
|
|
||||||
|
return fail(500, {
|
||||||
|
error: error.message,
|
||||||
|
values: {
|
||||||
|
settlementType,
|
||||||
|
fromUser,
|
||||||
|
toUser,
|
||||||
|
amount: data.get('amount')
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
811
src/routes/cospend/settle/+page.svelte
Normal file
811
src/routes/cospend/settle/+page.svelte
Normal file
@@ -0,0 +1,811 @@
|
|||||||
|
<script>
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { enhance } from '$app/forms';
|
||||||
|
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||||
|
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
||||||
|
|
||||||
|
export let data;
|
||||||
|
export let form;
|
||||||
|
|
||||||
|
// Use server-side data with progressive enhancement
|
||||||
|
let debtData = data.debtData || {
|
||||||
|
whoOwesMe: [],
|
||||||
|
whoIOwe: [],
|
||||||
|
totalOwedToMe: 0,
|
||||||
|
totalIOwe: 0
|
||||||
|
};
|
||||||
|
let loading = false; // Start as false since we have server data
|
||||||
|
let error = data.error || form?.error || null;
|
||||||
|
let selectedSettlement = null;
|
||||||
|
let settlementAmount = form?.values?.amount || '';
|
||||||
|
let submitting = false;
|
||||||
|
let predefinedMode = isPredefinedUsersMode();
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
// For predefined mode with 2 users, auto-select the debt if there's only one
|
||||||
|
if (predefinedMode && PREDEFINED_USERS.length === 2) {
|
||||||
|
const totalDebts = debtData.whoOwesMe.length + debtData.whoIOwe.length;
|
||||||
|
if (totalDebts === 1) {
|
||||||
|
if (debtData.whoOwesMe.length === 1) {
|
||||||
|
selectedSettlement = {
|
||||||
|
type: 'receive',
|
||||||
|
from: debtData.whoOwesMe[0].username,
|
||||||
|
to: data.currentUser,
|
||||||
|
amount: debtData.whoOwesMe[0].netAmount,
|
||||||
|
description: `Settlement: ${debtData.whoOwesMe[0].username} pays ${data.currentUser}`
|
||||||
|
};
|
||||||
|
if (!settlementAmount) {
|
||||||
|
settlementAmount = debtData.whoOwesMe[0].netAmount.toString();
|
||||||
|
}
|
||||||
|
} else if (debtData.whoIOwe.length === 1) {
|
||||||
|
selectedSettlement = {
|
||||||
|
type: 'pay',
|
||||||
|
from: data.currentUser,
|
||||||
|
to: debtData.whoIOwe[0].username,
|
||||||
|
amount: debtData.whoIOwe[0].netAmount,
|
||||||
|
description: `Settlement: ${data.currentUser} pays ${debtData.whoIOwe[0].username}`
|
||||||
|
};
|
||||||
|
if (!settlementAmount) {
|
||||||
|
settlementAmount = debtData.whoIOwe[0].netAmount.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function selectSettlement(type, user, amount) {
|
||||||
|
const currentUser = data.currentUser;
|
||||||
|
if (type === 'receive') {
|
||||||
|
selectedSettlement = {
|
||||||
|
type: 'receive',
|
||||||
|
from: user,
|
||||||
|
to: currentUser,
|
||||||
|
amount: amount,
|
||||||
|
description: `Settlement: ${user} pays ${currentUser}`
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
selectedSettlement = {
|
||||||
|
type: 'pay',
|
||||||
|
from: currentUser,
|
||||||
|
to: user,
|
||||||
|
amount: amount,
|
||||||
|
description: `Settlement: ${currentUser} pays ${user}`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
settlementAmount = amount.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function processSettlement() {
|
||||||
|
if (!selectedSettlement || !settlementAmount) {
|
||||||
|
error = 'Please select a settlement and enter an amount';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const amount = parseFloat(settlementAmount);
|
||||||
|
if (isNaN(amount) || amount <= 0) {
|
||||||
|
error = 'Please enter a valid positive amount';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
submitting = true;
|
||||||
|
error = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Create a settlement payment directly using the API
|
||||||
|
const payload = {
|
||||||
|
title: 'Settlement Payment',
|
||||||
|
description: selectedSettlement.description,
|
||||||
|
amount: amount,
|
||||||
|
paidBy: selectedSettlement.from,
|
||||||
|
date: new Date().toISOString().split('T')[0],
|
||||||
|
category: 'settlement',
|
||||||
|
splitMethod: 'full',
|
||||||
|
splits: [
|
||||||
|
{
|
||||||
|
username: selectedSettlement.from,
|
||||||
|
amount: -amount // Payer gets negative (receives money back)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
username: selectedSettlement.to,
|
||||||
|
amount: amount // Receiver owes money
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
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();
|
||||||
|
throw new Error(errorData.message || 'Failed to record settlement');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect back to dashboard on success
|
||||||
|
window.location.href = '/cospend';
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
submitting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCurrency(amount) {
|
||||||
|
return new Intl.NumberFormat('de-CH', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'CHF'
|
||||||
|
}).format(amount);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Settle Debts - Cospend</title>
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="settle-main">
|
||||||
|
<div class="header-section">
|
||||||
|
<h1>Settle Debts</h1>
|
||||||
|
<p>Record payments to settle outstanding debts between users</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if loading}
|
||||||
|
<div class="loading">Loading debt information...</div>
|
||||||
|
{:else if error}
|
||||||
|
<div class="error">Error: {error}</div>
|
||||||
|
{:else if debtData.whoOwesMe.length === 0 && debtData.whoIOwe.length === 0}
|
||||||
|
<div class="no-debts">
|
||||||
|
<h2>🎉 All Settled!</h2>
|
||||||
|
<p>No outstanding debts to settle. Everyone is even!</p>
|
||||||
|
<div class="actions">
|
||||||
|
<a href="/cospend" class="btn btn-primary">Back to Dashboard</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="settlement-container">
|
||||||
|
<!-- Available Settlements -->
|
||||||
|
<div class="available-settlements">
|
||||||
|
<h2>Available Settlements</h2>
|
||||||
|
|
||||||
|
{#if debtData.whoOwesMe.length > 0}
|
||||||
|
<div class="settlement-section">
|
||||||
|
<h3>Money You're Owed</h3>
|
||||||
|
{#each debtData.whoOwesMe as debt}
|
||||||
|
<div class="settlement-option"
|
||||||
|
class:selected={selectedSettlement?.type === 'receive' && selectedSettlement?.from === debt.username}
|
||||||
|
on:click={() => selectSettlement('receive', debt.username, debt.netAmount)}>
|
||||||
|
<div class="settlement-user">
|
||||||
|
<ProfilePicture username={debt.username} size={40} />
|
||||||
|
<div class="user-details">
|
||||||
|
<span class="username">{debt.username}</span>
|
||||||
|
<span class="debt-amount">owes you {formatCurrency(debt.netAmount)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-action">
|
||||||
|
<span class="action-text">Receive Payment</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if debtData.whoIOwe.length > 0}
|
||||||
|
<div class="settlement-section">
|
||||||
|
<h3>Money You Owe</h3>
|
||||||
|
{#each debtData.whoIOwe as debt}
|
||||||
|
<div class="settlement-option"
|
||||||
|
class:selected={selectedSettlement?.type === 'pay' && selectedSettlement?.to === debt.username}
|
||||||
|
on:click={() => selectSettlement('pay', debt.username, debt.netAmount)}>
|
||||||
|
<div class="settlement-user">
|
||||||
|
<ProfilePicture username={debt.username} size={40} />
|
||||||
|
<div class="user-details">
|
||||||
|
<span class="username">{debt.username}</span>
|
||||||
|
<span class="debt-amount">you owe {formatCurrency(debt.netAmount)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="settlement-action">
|
||||||
|
<span class="action-text">Make Payment</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Settlement Details -->
|
||||||
|
{#if selectedSettlement}
|
||||||
|
<div class="settlement-details">
|
||||||
|
<h2>Settlement Details</h2>
|
||||||
|
|
||||||
|
<div class="settlement-summary">
|
||||||
|
<div class="settlement-flow">
|
||||||
|
<div class="user-from">
|
||||||
|
<ProfilePicture username={selectedSettlement.from} size={48} />
|
||||||
|
<span class="username">{selectedSettlement.from}</span>
|
||||||
|
{#if selectedSettlement.from === data.currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="flow-arrow">→</div>
|
||||||
|
<div class="user-to">
|
||||||
|
<ProfilePicture username={selectedSettlement.to} size={48} />
|
||||||
|
<span class="username">{selectedSettlement.to}</span>
|
||||||
|
{#if selectedSettlement.to === data.currentUser}
|
||||||
|
<span class="you-badge">You</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settlement-amount-section">
|
||||||
|
<label for="amount">Settlement Amount</label>
|
||||||
|
<div class="amount-input">
|
||||||
|
<span class="currency">CHF</span>
|
||||||
|
<input
|
||||||
|
id="amount"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0.01"
|
||||||
|
bind:value={settlementAmount}
|
||||||
|
placeholder="0.00"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<small class="max-amount">
|
||||||
|
</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settlement-description">
|
||||||
|
<strong>Description:</strong> {selectedSettlement.description}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settlement-actions">
|
||||||
|
<button
|
||||||
|
class="btn btn-settlement"
|
||||||
|
on:click={processSettlement}
|
||||||
|
disabled={submitting || !settlementAmount}>
|
||||||
|
{#if submitting}
|
||||||
|
Recording Settlement...
|
||||||
|
{:else}
|
||||||
|
Record Settlement
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-secondary" on:click={() => selectedSettlement = null}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<!-- No-JS Fallback Form -->
|
||||||
|
<div class="settlement-details no-js-fallback">
|
||||||
|
<h2>Record Settlement</h2>
|
||||||
|
<form method="POST" action="?/settle" class="settlement-form">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="settlementType">Settlement Type</label>
|
||||||
|
<select id="settlementType" name="settlementType" required>
|
||||||
|
<option value="">Select settlement type</option>
|
||||||
|
{#each debtData.whoOwesMe as debt}
|
||||||
|
<option value="receive" data-from="{debt.username}" data-to="{data.currentUser}">
|
||||||
|
Receive {formatCurrency(debt.netAmount)} from {debt.username}
|
||||||
|
</option>
|
||||||
|
{/each}
|
||||||
|
{#each debtData.whoIOwe as debt}
|
||||||
|
<option value="pay" data-from="{data.currentUser}" data-to="{debt.username}">
|
||||||
|
Pay {formatCurrency(debt.netAmount)} to {debt.username}
|
||||||
|
</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="fromUser">From User</label>
|
||||||
|
<select id="fromUser" name="fromUser" required>
|
||||||
|
<option value="">Select payer</option>
|
||||||
|
{#each [...debtData.whoOwesMe.map(d => d.username), data.currentUser].filter(Boolean) as user}
|
||||||
|
<option value="{user}">{user}{user === data.currentUser ? ' (You)' : ''}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="toUser">To User</label>
|
||||||
|
<select id="toUser" name="toUser" required>
|
||||||
|
<option value="">Select recipient</option>
|
||||||
|
{#each [...debtData.whoIOwe.map(d => d.username), data.currentUser].filter(Boolean) as user}
|
||||||
|
<option value="{user}">{user}{user === data.currentUser ? ' (You)' : ''}</option>
|
||||||
|
{/each}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="fallback-amount">Settlement Amount (CHF)</label>
|
||||||
|
<input
|
||||||
|
id="fallback-amount"
|
||||||
|
name="amount"
|
||||||
|
type="number"
|
||||||
|
step="0.01"
|
||||||
|
min="0.01"
|
||||||
|
value={form?.values?.amount || ''}
|
||||||
|
placeholder="0.00"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="settlement-actions">
|
||||||
|
<button type="submit" class="btn btn-settlement">
|
||||||
|
Record Settlement
|
||||||
|
</button>
|
||||||
|
<a href="/cospend" class="btn btn-secondary">
|
||||||
|
Cancel
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.settle-main {
|
||||||
|
max-width: 1000px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section h1 {
|
||||||
|
color: var(--nord0);
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section p {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading, .error {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
color: var(--red);
|
||||||
|
background-color: var(--nord6);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-debts {
|
||||||
|
text-align: center;
|
||||||
|
padding: 3rem 2rem;
|
||||||
|
background: var(--nord6);
|
||||||
|
border-radius: 1rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-debts h2 {
|
||||||
|
color: var(--green);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-container {
|
||||||
|
display: grid;
|
||||||
|
gap: 2rem;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.settlement-container {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.available-settlements {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-section {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-section h3 {
|
||||||
|
color: var(--nord0);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-size: 1.1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1rem;
|
||||||
|
border: 2px solid var(--nord4);
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
background: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option:hover {
|
||||||
|
border-color: var(--green);
|
||||||
|
box-shadow: 0 2px 8px rgba(163, 190, 140, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option.selected {
|
||||||
|
border-color: var(--green);
|
||||||
|
background-color: var(--nord5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-user {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-details {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-amount {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-action {
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-details {
|
||||||
|
background: var(--nord6);
|
||||||
|
padding: 1.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
height: fit-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-summary {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-from, .user-to {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flow-arrow {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
color: var(--green);
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
padding: 0.125rem 0.5rem;
|
||||||
|
border-radius: 1rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-section {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-section label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
background: var(--nord5);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.currency {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-weight: 500;
|
||||||
|
margin-right: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input input {
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.25rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input input:focus {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.max-amount {
|
||||||
|
color: var(--nord3);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-description {
|
||||||
|
color: var(--nord0);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
padding: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-form {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select,
|
||||||
|
.form-group input {
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
font-size: 1rem;
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select:focus,
|
||||||
|
.form-group input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--blue);
|
||||||
|
box-shadow: 0 0 0 2px rgba(94, 129, 172, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-js-fallback {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
:global(body:has(script)) .no-js-fallback {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-block;
|
||||||
|
text-align: center;
|
||||||
|
transition: all 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--blue);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: var(--lightblue);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord5);
|
||||||
|
color: var(--nord0);
|
||||||
|
border: 1px solid var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-settlement {
|
||||||
|
background: linear-gradient(135deg, var(--green), var(--lightblue));
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-settlement:hover:not(:disabled) {
|
||||||
|
background: linear-gradient(135deg, var(--lightblue), var(--green));
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-settlement:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.back-actions {
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
.header-section h1 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section p {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
background-color: var(--accent-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-debts {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.available-settlements {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-section h3 {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option {
|
||||||
|
border-color: var(--nord2);
|
||||||
|
background: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option:hover {
|
||||||
|
box-shadow: 0 2px 8px rgba(163, 190, 140, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-option.selected {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.username {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.debt-amount {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-details {
|
||||||
|
background: var(--accent-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-amount-section label {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input {
|
||||||
|
background: var(--nord1);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.currency {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.max-amount {
|
||||||
|
color: var(--nord4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-description {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
background-color: var(--nord1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount-input input {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background-color: var(--nord2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group select,
|
||||||
|
.form-group input {
|
||||||
|
background-color: var(--nord1);
|
||||||
|
color: var(--font-default-dark);
|
||||||
|
border-color: var(--nord2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.settle-main {
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-flow {
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.flow-arrow {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-actions {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -463,19 +463,19 @@ Der unten abgebildete Rosenkranz zeigt die aktuellen Gehmeinisse des Tages nach
|
|||||||
</g>
|
</g>
|
||||||
<g id=lbead5>
|
<g id=lbead5>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
<g id=lbead4>
|
<g id=lbead4>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
<g id=lbead3>
|
<g id=lbead3>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
<g id=lbead6>
|
<g id=lbead6>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
<g class=beforedecades>
|
<g class=beforedecades>
|
||||||
@@ -490,11 +490,11 @@ Der unten abgebildete Rosenkranz zeigt die aktuellen Gehmeinisse des Tages nach
|
|||||||
</g>
|
</g>
|
||||||
<g id=lbead1>
|
<g id=lbead1>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
<g id=lbead2>
|
<g id=lbead2>
|
||||||
<circle class=lbead />
|
<circle class=lbead />
|
||||||
<circle class=hitbox onclick="{true}" />
|
<circle class=hitbox onclick="{true}" role="button" tabindex="0" />
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
</g>
|
</g>
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ if(data.session){
|
|||||||
<Header>
|
<Header>
|
||||||
<ul class=site_header slot=links>
|
<ul class=site_header slot=links>
|
||||||
<li><a href="/rezepte">Alle Rezepte</a></li>
|
<li><a href="/rezepte">Alle Rezepte</a></li>
|
||||||
|
{#if user}
|
||||||
|
<li><a href="/rezepte/favorites">Favoriten</a></li>
|
||||||
|
{/if}
|
||||||
<li><a href="/rezepte/season">In Saison</a></li>
|
<li><a href="/rezepte/season">In Saison</a></li>
|
||||||
<li><a href="/rezepte/category">Kategorie</a></li>
|
<li><a href="/rezepte/category">Kategorie</a></li>
|
||||||
<li><a href="/rezepte/icon">Icon</a></li>
|
<li><a href="/rezepte/icon">Icon</a></li>
|
||||||
|
|||||||
@@ -1,13 +1,22 @@
|
|||||||
import type { PageServerLoad } from "./$types";
|
import type { PageServerLoad } from "./$types";
|
||||||
|
import { getUserFavorites, addFavoriteStatusToRecipes } from "$lib/server/favorites";
|
||||||
|
|
||||||
export async function load({ fetch }) {
|
export async function load({ fetch, locals }) {
|
||||||
let current_month = new Date().getMonth() + 1
|
let current_month = new Date().getMonth() + 1
|
||||||
const res_season = await fetch(`/api/rezepte/items/in_season/` + current_month);
|
const res_season = await fetch(`/api/rezepte/items/in_season/` + current_month);
|
||||||
const res_all_brief = await fetch(`/api/rezepte/items/all_brief`);
|
const res_all_brief = await fetch(`/api/rezepte/items/all_brief`);
|
||||||
const item_season = await res_season.json();
|
const item_season = await res_season.json();
|
||||||
const item_all_brief = await res_all_brief.json();
|
const item_all_brief = await res_all_brief.json();
|
||||||
|
|
||||||
|
// Get user favorites and session
|
||||||
|
const [userFavorites, session] = await Promise.all([
|
||||||
|
getUserFavorites(fetch, locals),
|
||||||
|
locals.auth()
|
||||||
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
season: item_season,
|
season: addFavoriteStatusToRecipes(item_season, userFavorites),
|
||||||
all_brief: item_all_brief,
|
all_brief: addFavoriteStatusToRecipes(item_all_brief, userFavorites),
|
||||||
|
session
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -36,15 +36,15 @@ h1{
|
|||||||
|
|
||||||
<MediaScroller title="In Saison">
|
<MediaScroller title="In Saison">
|
||||||
{#each data.season as recipe}
|
{#each data.season as recipe}
|
||||||
<Card {recipe} {current_month} loading_strat={"eager"} do_margin_right={true}></Card>
|
<Card {recipe} {current_month} loading_strat={"eager"} do_margin_right={true} isFavorite={recipe.isFavorite} showFavoriteIndicator={!!data.session?.user}></Card>
|
||||||
{/each}
|
{/each}
|
||||||
</MediaScroller>
|
</MediaScroller>
|
||||||
|
|
||||||
{#each categories as category}
|
{#each categories as category}
|
||||||
<MediaScroller title={category}>
|
<MediaScroller title={category}>
|
||||||
{#each data.all_brief.filter(recipe => recipe.category == category) as recipe}
|
{#each data.all_brief.filter(recipe => recipe.category == category) as recipe}
|
||||||
<Card {recipe} {current_month} do_margin_right={true}></Card>
|
<Card {recipe} {current_month} do_margin_right={true} isFavorite={recipe.isFavorite} showFavoriteIndicator={!!data.session?.user}></Card>
|
||||||
{/each}
|
{/each}
|
||||||
</MediaScroller>
|
</MediaScroller>
|
||||||
{/each}
|
{/each}
|
||||||
<AddButton></AddButton>
|
<AddButton href="/rezepte/add"></AddButton>
|
||||||
|
|||||||
73
src/routes/rezepte/[name]/+page.server.ts
Normal file
73
src/routes/rezepte/[name]/+page.server.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
import { redirect, error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
toggleFavorite: async ({ request, locals, url, fetch }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw error(401, 'Authentication required');
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = await request.formData();
|
||||||
|
const recipeId = formData.get('recipeId') as string;
|
||||||
|
const isFavorite = formData.get('isFavorite') === 'true';
|
||||||
|
|
||||||
|
if (!recipeId) {
|
||||||
|
throw error(400, 'Recipe ID required');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Use the existing API endpoint
|
||||||
|
const method = isFavorite ? 'DELETE' : 'POST';
|
||||||
|
const response = await fetch('/api/rezepte/favorites', {
|
||||||
|
method,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ recipeId }),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorData = await response.text();
|
||||||
|
console.error('API error:', response.status, errorData);
|
||||||
|
throw error(response.status, `Failed to toggle favorite: ${errorData}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect back to the same page to refresh the state
|
||||||
|
throw redirect(303, url.pathname);
|
||||||
|
} catch (e) {
|
||||||
|
// If it's a redirect, let it through
|
||||||
|
if (e && typeof e === 'object' && 'status' in e && e.status === 303) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
console.error('Favorite toggle error:', e);
|
||||||
|
throw error(500, 'Failed to toggle favorite');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
swapYeast: async ({ request, url }) => {
|
||||||
|
const formData = await request.formData();
|
||||||
|
const yeastId = parseInt(formData.get('yeastId') as string);
|
||||||
|
|
||||||
|
// Build new URL
|
||||||
|
const newUrl = new URL(url.pathname, url.origin);
|
||||||
|
|
||||||
|
// Restore all parameters from the form data (they were submitted as currentParam_*)
|
||||||
|
for (const [key, value] of formData.entries()) {
|
||||||
|
if (key.startsWith('currentParam_')) {
|
||||||
|
const paramName = key.substring('currentParam_'.length);
|
||||||
|
newUrl.searchParams.set(paramName, value as string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toggle the yeast flag - if it exists, remove it; if not, add it
|
||||||
|
const yeastParam = `y${yeastId}`;
|
||||||
|
if (newUrl.searchParams.has(yeastParam)) {
|
||||||
|
newUrl.searchParams.delete(yeastParam);
|
||||||
|
} else {
|
||||||
|
newUrl.searchParams.set(yeastParam, '1');
|
||||||
|
}
|
||||||
|
|
||||||
|
throw redirect(303, newUrl.toString());
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -12,6 +12,7 @@
|
|||||||
import {season} from '$lib/js/season_store';
|
import {season} from '$lib/js/season_store';
|
||||||
import RecipeNote from '$lib/components/RecipeNote.svelte';
|
import RecipeNote from '$lib/components/RecipeNote.svelte';
|
||||||
import {stripHtmlTags} from '$lib/js/stripHtmlTags';
|
import {stripHtmlTags} from '$lib/js/stripHtmlTags';
|
||||||
|
import FavoriteButton from '$lib/components/FavoriteButton.svelte';
|
||||||
|
|
||||||
export let data: PageData;
|
export let data: PageData;
|
||||||
|
|
||||||
@@ -276,6 +277,7 @@ h4{
|
|||||||
<meta property="og:image:secure_url" content="https://bocken.org/static/rezepte/thumb/{data.short_name}.webp" />
|
<meta property="og:image:secure_url" content="https://bocken.org/static/rezepte/thumb/{data.short_name}.webp" />
|
||||||
<meta property="og:image:type" content="image/webp" />
|
<meta property="og:image:type" content="image/webp" />
|
||||||
<meta property="og:image:alt" content="{stripHtmlTags(data.name)}" />
|
<meta property="og:image:alt" content="{stripHtmlTags(data.name)}" />
|
||||||
|
{@html `<script type="application/ld+json">${JSON.stringify(data.recipeJsonLd)}</script>`}
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<TitleImgParallax src={hero_img_src} {placeholder_src}>
|
<TitleImgParallax src={hero_img_src} {placeholder_src}>
|
||||||
@@ -308,6 +310,13 @@ h4{
|
|||||||
<a class=tag href="/rezepte/tag/{tag}">{tag}</a>
|
<a class=tag href="/rezepte/tag/{tag}">{tag}</a>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<FavoriteButton
|
||||||
|
recipeId={data.short_name}
|
||||||
|
isFavorite={data.isFavorite || false}
|
||||||
|
isLoggedIn={!!data.session?.user}
|
||||||
|
/>
|
||||||
|
|
||||||
{#if data.note}
|
{#if data.note}
|
||||||
<RecipeNote note={data.note}></RecipeNote>
|
<RecipeNote note={data.note}></RecipeNote>
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,10 +1,114 @@
|
|||||||
import { error } from "@sveltejs/kit";
|
import { error } from "@sveltejs/kit";
|
||||||
|
import { generateRecipeJsonLd } from '$lib/js/recipeJsonLd';
|
||||||
|
|
||||||
export async function load({ fetch, params}) {
|
export async function load({ fetch, params, url}) {
|
||||||
const res = await fetch(`/api/rezepte/items/${params.name}`);
|
const res = await fetch(`/api/rezepte/items/${params.name}`);
|
||||||
let item = await res.json();
|
let item = await res.json();
|
||||||
if(!res.ok){
|
if(!res.ok){
|
||||||
throw error(res.status, item.message)
|
throw error(res.status, item.message)
|
||||||
}
|
}
|
||||||
return item;
|
|
||||||
|
// Check if this recipe is favorited by the user
|
||||||
|
let isFavorite = false;
|
||||||
|
try {
|
||||||
|
const favRes = await fetch(`/api/rezepte/favorites/check/${params.name}`);
|
||||||
|
if (favRes.ok) {
|
||||||
|
const favData = await favRes.json();
|
||||||
|
isFavorite = favData.isFavorite;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Silently fail if not authenticated or other error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get multiplier from URL parameters
|
||||||
|
const multiplier = parseFloat(url.searchParams.get('multiplier') || '1');
|
||||||
|
|
||||||
|
// Handle yeast swapping from URL parameters based on toggle flags
|
||||||
|
// Look for parameters like y0=1, y1=1 (yeast #0 and #1 are toggled)
|
||||||
|
if (item.ingredients) {
|
||||||
|
let yeastCounter = 0;
|
||||||
|
|
||||||
|
// Iterate through all ingredients to find yeast and apply conversions
|
||||||
|
for (let listIndex = 0; listIndex < item.ingredients.length; listIndex++) {
|
||||||
|
const list = item.ingredients[listIndex];
|
||||||
|
if (list.list) {
|
||||||
|
for (let ingredientIndex = 0; ingredientIndex < list.list.length; ingredientIndex++) {
|
||||||
|
const ingredient = list.list[ingredientIndex];
|
||||||
|
|
||||||
|
// Check if this is a yeast ingredient
|
||||||
|
if (ingredient.name === "Frischhefe" || ingredient.name === "Trockenhefe") {
|
||||||
|
// Check if this yeast should be toggled
|
||||||
|
const yeastParam = `y${yeastCounter}`;
|
||||||
|
const isToggled = url.searchParams.has(yeastParam);
|
||||||
|
|
||||||
|
if (isToggled) {
|
||||||
|
// Perform yeast conversion from original recipe data
|
||||||
|
const originalName = ingredient.name;
|
||||||
|
const originalAmount = parseFloat(ingredient.amount);
|
||||||
|
const originalUnit = ingredient.unit;
|
||||||
|
|
||||||
|
let newName: string, newAmount: string, newUnit: string;
|
||||||
|
|
||||||
|
if (originalName === "Frischhefe") {
|
||||||
|
// Convert fresh yeast to dry yeast
|
||||||
|
newName = "Trockenhefe";
|
||||||
|
|
||||||
|
if (originalUnit === "Prise") {
|
||||||
|
// "1 Prise Frischhefe" → "1 Prise Trockenhefe"
|
||||||
|
newAmount = ingredient.amount;
|
||||||
|
newUnit = "Prise";
|
||||||
|
} else if (originalUnit === "g" && originalAmount === 1) {
|
||||||
|
// "1 g Frischhefe" → "1 Prise Trockenhefe"
|
||||||
|
newAmount = "1";
|
||||||
|
newUnit = "Prise";
|
||||||
|
} else {
|
||||||
|
// Normal conversion: "9 g Frischhefe" → "3 g Trockenhefe" (divide by 3)
|
||||||
|
newAmount = (originalAmount / 3).toString();
|
||||||
|
newUnit = "g";
|
||||||
|
}
|
||||||
|
} else if (originalName === "Trockenhefe") {
|
||||||
|
// Convert dry yeast to fresh yeast
|
||||||
|
newName = "Frischhefe";
|
||||||
|
|
||||||
|
if (originalUnit === "Prise") {
|
||||||
|
// "1 Prise Trockenhefe" → "1 g Frischhefe"
|
||||||
|
newAmount = "1";
|
||||||
|
newUnit = "g";
|
||||||
|
} else {
|
||||||
|
// Normal conversion: "1 g Trockenhefe" → "3 g Frischhefe" (multiply by 3)
|
||||||
|
newAmount = (originalAmount * 3).toString();
|
||||||
|
newUnit = "g";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback
|
||||||
|
newName = originalName;
|
||||||
|
newAmount = ingredient.amount;
|
||||||
|
newUnit = originalUnit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply the conversion
|
||||||
|
item.ingredients[listIndex].list[ingredientIndex] = {
|
||||||
|
...item.ingredients[listIndex].list[ingredientIndex],
|
||||||
|
name: newName,
|
||||||
|
amount: newAmount,
|
||||||
|
unit: newUnit
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
yeastCounter++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate JSON-LD server-side
|
||||||
|
const recipeJsonLd = generateRecipeJsonLd(item);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...item,
|
||||||
|
isFavorite,
|
||||||
|
multiplier,
|
||||||
|
recipeJsonLd
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
19
src/routes/rezepte/category/[category]/+page.server.ts
Normal file
19
src/routes/rezepte/category/[category]/+page.server.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { PageServerLoad } from "./$types";
|
||||||
|
import { getUserFavorites, addFavoriteStatusToRecipes } from "$lib/server/favorites";
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ fetch, locals, params }) => {
|
||||||
|
const res = await fetch(`/api/rezepte/items/category/${params.category}`);
|
||||||
|
const items = await res.json();
|
||||||
|
|
||||||
|
// Get user favorites and session
|
||||||
|
const [userFavorites, session] = await Promise.all([
|
||||||
|
getUserFavorites(fetch, locals),
|
||||||
|
locals.auth()
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
category: params.category,
|
||||||
|
recipes: addFavoriteStatusToRecipes(items, userFavorites),
|
||||||
|
session
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -14,11 +14,11 @@
|
|||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<h1>Rezepte in Kategorie <q>{data.category}</q>:</h1>
|
<h1>Rezepte in Kategorie <q>{data.category}</q>:</h1>
|
||||||
<Search></Search>
|
<Search category={data.category}></Search>
|
||||||
<section>
|
<section>
|
||||||
<Recipes>
|
<Recipes>
|
||||||
{#each rand_array(data.recipes) as recipe}
|
{#each rand_array(data.recipes) as recipe}
|
||||||
<Card {recipe} {current_month}></Card>
|
<Card {recipe} {current_month} isFavorite={recipe.isFavorite} showFavoriteIndicator={!!data.session?.user}></Card>
|
||||||
{/each}
|
{/each}
|
||||||
</Recipes>
|
</Recipes>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
import type { PageLoad } from "./$types";
|
|
||||||
|
|
||||||
export async function load({ fetch, params }) {
|
|
||||||
const res = await fetch(`/api/rezepte/items/category/${params.category}`);
|
|
||||||
const items = await res.json();
|
|
||||||
return {
|
|
||||||
category: params.category,
|
|
||||||
recipes: items
|
|
||||||
}
|
|
||||||
};
|
|
||||||
32
src/routes/rezepte/favorites/+page.server.ts
Normal file
32
src/routes/rezepte/favorites/+page.server.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import type { PageServerLoad } from "./$types";
|
||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ fetch, locals }) => {
|
||||||
|
const session = await locals.auth();
|
||||||
|
|
||||||
|
if (!session?.user?.nickname) {
|
||||||
|
throw redirect(302, '/rezepte');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/rezepte/favorites/recipes');
|
||||||
|
if (!res.ok) {
|
||||||
|
return {
|
||||||
|
favorites: [],
|
||||||
|
error: 'Failed to load favorites'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const favorites = await res.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
favorites,
|
||||||
|
session
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
return {
|
||||||
|
favorites: [],
|
||||||
|
error: 'Failed to load favorites'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
58
src/routes/rezepte/favorites/+page.svelte
Normal file
58
src/routes/rezepte/favorites/+page.svelte
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { PageData } from './$types';
|
||||||
|
import '$lib/css/nordtheme.css';
|
||||||
|
import Recipes from '$lib/components/Recipes.svelte';
|
||||||
|
import Card from '$lib/components/Card.svelte';
|
||||||
|
import Search from '$lib/components/Search.svelte';
|
||||||
|
export let data: PageData;
|
||||||
|
export let current_month = new Date().getMonth() + 1;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
h1{
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 0;
|
||||||
|
font-size: 4rem;
|
||||||
|
}
|
||||||
|
.subheading{
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
}
|
||||||
|
.empty-state{
|
||||||
|
text-align: center;
|
||||||
|
margin-top: 3rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Meine Favoriten - Bocken Rezepte</title>
|
||||||
|
<meta name="description" content="Meine favorisierten Rezepte aus der Bockenschen Küche." />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<h1>Favoriten</h1>
|
||||||
|
<p class=subheading>
|
||||||
|
{#if data.favorites.length > 0}
|
||||||
|
{data.favorites.length} favorisierte Rezepte
|
||||||
|
{:else}
|
||||||
|
Noch keine Favoriten gespeichert
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<Search favoritesOnly={true}></Search>
|
||||||
|
|
||||||
|
{#if data.error}
|
||||||
|
<p class="empty-state">Fehler beim Laden der Favoriten: {data.error}</p>
|
||||||
|
{:else if data.favorites.length > 0}
|
||||||
|
<Recipes>
|
||||||
|
{#each data.favorites as recipe}
|
||||||
|
<Card {recipe} {current_month} isFavorite={true} showFavoriteIndicator={true}></Card>
|
||||||
|
{/each}
|
||||||
|
</Recipes>
|
||||||
|
{:else}
|
||||||
|
<div class="empty-state">
|
||||||
|
<p>Du hast noch keine Rezepte als Favoriten gespeichert.</p>
|
||||||
|
<p>Besuche ein <a href="/rezepte">Rezept</a> und klicke auf das Herz-Symbol, um es zu deinen Favoriten hinzuzufügen.</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
22
src/routes/rezepte/icon/[icon]/+page.server.ts
Normal file
22
src/routes/rezepte/icon/[icon]/+page.server.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import type { PageServerLoad } from "./$types";
|
||||||
|
import { getUserFavorites, addFavoriteStatusToRecipes } from "$lib/server/favorites";
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ fetch, locals, params }) => {
|
||||||
|
const res_season = await fetch(`/api/rezepte/items/icon/` + params.icon);
|
||||||
|
const res_icons = await fetch(`/api/rezepte/items/icon`);
|
||||||
|
const icons = await res_icons.json();
|
||||||
|
const item_season = await res_season.json();
|
||||||
|
|
||||||
|
// Get user favorites and session
|
||||||
|
const [userFavorites, session] = await Promise.all([
|
||||||
|
getUserFavorites(fetch, locals),
|
||||||
|
locals.auth()
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
icons: icons,
|
||||||
|
icon: params.icon,
|
||||||
|
season: addFavoriteStatusToRecipes(item_season, userFavorites),
|
||||||
|
session
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
<IconLayout icons={data.icons} active_icon={data.icon} >
|
<IconLayout icons={data.icons} active_icon={data.icon} >
|
||||||
<Recipes slot=recipes>
|
<Recipes slot=recipes>
|
||||||
{#each rand_array(data.season) as recipe}
|
{#each rand_array(data.season) as recipe}
|
||||||
<Card {recipe} icon_override=true></Card>
|
<Card {recipe} icon_override=true isFavorite={recipe.isFavorite} showFavoriteIndicator={!!data.session?.user}></Card>
|
||||||
{/each}
|
{/each}
|
||||||
</Recipes>
|
</Recipes>
|
||||||
</IconLayout>
|
</IconLayout>
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
import type { PageLoad } from "./$types";
|
|
||||||
|
|
||||||
export async function load({ fetch, params }) {
|
|
||||||
const res_season = await fetch(`/api/rezepte/items/icon/` + params.icon);
|
|
||||||
const res_icons = await fetch(`/api/rezepte/items/icon`);
|
|
||||||
const icons = await res_icons.json();
|
|
||||||
const item_season = await res_season.json();
|
|
||||||
return {
|
|
||||||
icons: icons,
|
|
||||||
icon: params.icon,
|
|
||||||
season: item_season,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
50
src/routes/rezepte/search/+page.server.ts
Normal file
50
src/routes/rezepte/search/+page.server.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ url, fetch }) => {
|
||||||
|
const query = url.searchParams.get('q') || '';
|
||||||
|
const category = url.searchParams.get('category');
|
||||||
|
const tag = url.searchParams.get('tag');
|
||||||
|
const icon = url.searchParams.get('icon');
|
||||||
|
const season = url.searchParams.get('season');
|
||||||
|
const favoritesOnly = url.searchParams.get('favorites') === 'true';
|
||||||
|
|
||||||
|
// Build API URL with filters
|
||||||
|
const apiUrl = new URL('/api/rezepte/search', url.origin);
|
||||||
|
if (query) apiUrl.searchParams.set('q', query);
|
||||||
|
if (category) apiUrl.searchParams.set('category', category);
|
||||||
|
if (tag) apiUrl.searchParams.set('tag', tag);
|
||||||
|
if (icon) apiUrl.searchParams.set('icon', icon);
|
||||||
|
if (season) apiUrl.searchParams.set('season', season);
|
||||||
|
if (favoritesOnly) apiUrl.searchParams.set('favorites', 'true');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(apiUrl.toString());
|
||||||
|
const results = await response.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
query,
|
||||||
|
results: response.ok ? results : [],
|
||||||
|
error: response.ok ? null : results.error || 'Search failed',
|
||||||
|
filters: {
|
||||||
|
category,
|
||||||
|
tag,
|
||||||
|
icon,
|
||||||
|
season,
|
||||||
|
favoritesOnly
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
query,
|
||||||
|
results: [],
|
||||||
|
error: 'Search failed',
|
||||||
|
filters: {
|
||||||
|
category,
|
||||||
|
tag,
|
||||||
|
icon,
|
||||||
|
season,
|
||||||
|
favoritesOnly
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
75
src/routes/rezepte/search/+page.svelte
Normal file
75
src/routes/rezepte/search/+page.svelte
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { PageData } from './$types';
|
||||||
|
import Recipes from '$lib/components/Recipes.svelte';
|
||||||
|
import Search from '$lib/components/Search.svelte';
|
||||||
|
import Card from '$lib/components/Card.svelte';
|
||||||
|
export let data: PageData;
|
||||||
|
export let current_month = new Date().getMonth() + 1;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
h1 {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 3em;
|
||||||
|
}
|
||||||
|
.search-info {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
color: var(--nord3);
|
||||||
|
}
|
||||||
|
.filter-info {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-size: 0.9em;
|
||||||
|
color: var(--nord2);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Suchergebnisse{data.query ? ` für "${data.query}"` : ''} - Bocken Rezepte</title>
|
||||||
|
<meta name="description" content="Suchergebnisse in den Bockenschen Rezepten." />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<h1>Suchergebnisse</h1>
|
||||||
|
|
||||||
|
{#if data.filters.category || data.filters.tag || data.filters.icon || data.filters.season || data.filters.favoritesOnly}
|
||||||
|
<div class="filter-info">
|
||||||
|
Gefiltert nach:
|
||||||
|
{#if data.filters.category}Kategorie "{data.filters.category}"{/if}
|
||||||
|
{#if data.filters.tag}Stichwort "{data.filters.tag}"{/if}
|
||||||
|
{#if data.filters.icon}Icon "{data.filters.icon}"{/if}
|
||||||
|
{#if data.filters.season}Saison "{data.filters.season}"{/if}
|
||||||
|
{#if data.filters.favoritesOnly}Nur Favoriten{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<Search
|
||||||
|
category={data.filters.category}
|
||||||
|
tag={data.filters.tag}
|
||||||
|
icon={data.filters.icon}
|
||||||
|
season={data.filters.season}
|
||||||
|
favoritesOnly={data.filters.favoritesOnly}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{#if data.error}
|
||||||
|
<div class="search-info">
|
||||||
|
<p>Fehler bei der Suche: {data.error}</p>
|
||||||
|
</div>
|
||||||
|
{:else if data.query}
|
||||||
|
<div class="search-info">
|
||||||
|
<p>{data.results.length} Ergebnisse für "{data.query}"</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if data.results.length > 0}
|
||||||
|
<Recipes>
|
||||||
|
{#each data.results as recipe}
|
||||||
|
<Card {recipe} {current_month} isFavorite={recipe.isFavorite} showFavoriteIndicator={true}></Card>
|
||||||
|
{/each}
|
||||||
|
</Recipes>
|
||||||
|
{:else if data.query && !data.error}
|
||||||
|
<div class="search-info">
|
||||||
|
<p>Keine Rezepte gefunden.</p>
|
||||||
|
<p>Versuche es mit anderen Suchbegriffen.</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
19
src/routes/rezepte/season/+page.server.ts
Normal file
19
src/routes/rezepte/season/+page.server.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import type { PageServerLoad } from "./$types";
|
||||||
|
import { getUserFavorites, addFavoriteStatusToRecipes } from "$lib/server/favorites";
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ fetch, locals }) => {
|
||||||
|
let current_month = new Date().getMonth() + 1
|
||||||
|
const res_season = await fetch(`/api/rezepte/items/in_season/` + current_month);
|
||||||
|
const item_season = await res_season.json();
|
||||||
|
|
||||||
|
// Get user favorites and session
|
||||||
|
const [userFavorites, session] = await Promise.all([
|
||||||
|
getUserFavorites(fetch, locals),
|
||||||
|
locals.auth()
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
season: addFavoriteStatusToRecipes(item_season, userFavorites),
|
||||||
|
session
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
<SeasonLayout active_index={current_month-1}>
|
<SeasonLayout active_index={current_month-1}>
|
||||||
<Recipes slot=recipes>
|
<Recipes slot=recipes>
|
||||||
{#each rand_array(data.season) as recipe}
|
{#each rand_array(data.season) as recipe}
|
||||||
<Card {recipe} {current_month}></Card>
|
<Card {recipe} {current_month} isFavorite={recipe.isFavorite} showFavoriteIndicator={!!data.session?.user}></Card>
|
||||||
{/each}
|
{/each}
|
||||||
</Recipes>
|
</Recipes>
|
||||||
</SeasonLayout>
|
</SeasonLayout>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user