Compare commits
8 Commits
95b49ab6ce
...
c53300d5a7
Author | SHA1 | Date | |
---|---|---|---|
c53300d5a7
|
|||
73c7626c32
|
|||
098ccb8568
|
|||
fd4a25376b
|
|||
b67bb0b263
|
|||
b08bbbdab9
|
|||
712829ad8e
|
|||
815975dba0
|
246
src/lib/components/DebtBreakdown.svelte
Normal file
246
src/lib/components/DebtBreakdown.svelte
Normal file
@@ -0,0 +1,246 @@
|
||||
<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);
|
||||
}
|
||||
</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>
|
324
src/lib/components/EnhancedBalance.svelte
Normal file
324
src/lib/components/EnhancedBalance.svelte
Normal file
@@ -0,0 +1,324 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import ProfilePicture from './ProfilePicture.svelte';
|
||||
|
||||
let balance = {
|
||||
netBalance: 0,
|
||||
recentSplits: []
|
||||
};
|
||||
let debtData = {
|
||||
whoOwesMe: [],
|
||||
whoIOwe: [],
|
||||
totalOwedToMe: 0,
|
||||
totalIOwe: 0
|
||||
};
|
||||
let loading = true;
|
||||
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
|
||||
singleDebtUser = getSingleDebtUser();
|
||||
shouldShowIntegratedView = singleDebtUser !== null;
|
||||
}
|
||||
|
||||
|
||||
onMount(async () => {
|
||||
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');
|
||||
}
|
||||
balance = await response.json();
|
||||
} 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');
|
||||
}
|
||||
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(Math.abs(amount));
|
||||
}
|
||||
|
||||
</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>
|
539
src/lib/components/PaymentModal.svelte
Normal file
539
src/lib/components/PaymentModal.svelte
Normal file
@@ -0,0 +1,539 @@
|
||||
<script>
|
||||
import { onMount, createEventDispatcher } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/stores';
|
||||
import ProfilePicture from './ProfilePicture.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}
|
||||
<a href="/cospend/payments/edit/{paymentId}" class="btn btn-primary">Edit Payment</a>
|
||||
<button
|
||||
class="btn btn-danger"
|
||||
on:click={deletePayment}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? 'Deleting...' : 'Delete'}
|
||||
</button>
|
||||
{/if}
|
||||
<button class="btn btn-secondary" on:click={closeModal}>Close</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.panel-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.panel-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1.5rem;
|
||||
border-bottom: 1px solid #eee;
|
||||
background: #f8f9fa;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.panel-header h2 {
|
||||
margin: 0;
|
||||
color: #333;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.close-button {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
color: #666;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.close-button:hover {
|
||||
background: #e9ecef;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.panel-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
}
|
||||
|
||||
.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, #f8f9fa, #e9ecef);
|
||||
border-bottom: 1px solid #dee2e6;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.payment-amount {
|
||||
font-size: 1.25rem;
|
||||
font-weight: bold;
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.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 #ddd;
|
||||
}
|
||||
|
||||
.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: #666;
|
||||
font-size: 0.85rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: #333;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.description {
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.description h3 {
|
||||
margin: 0 0 0.75rem 0;
|
||||
color: #333;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.description p {
|
||||
margin: 0;
|
||||
color: #555;
|
||||
line-height: 1.5;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.splits-section {
|
||||
border-top: 1px solid #eee;
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.splits-section h3 {
|
||||
margin: 0 0 1rem 0;
|
||||
color: #333;
|
||||
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: #f8f9fa;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.split-item.current-user {
|
||||
background: #e3f2fd;
|
||||
border-color: #2196f3;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
background-color: #1976d2;
|
||||
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: #2e7d32;
|
||||
}
|
||||
|
||||
.split-amount.negative {
|
||||
color: #d32f2f;
|
||||
}
|
||||
|
||||
.panel-actions {
|
||||
padding: 1.5rem;
|
||||
border-top: 1px solid #eee;
|
||||
background: #f8f9fa;
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: flex-end;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 0.25rem;
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: white;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background-color: #c62828;
|
||||
}
|
||||
|
||||
.btn-danger:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@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>
|
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];
|
||||
}
|
@@ -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);
|
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
|
||||
}));
|
||||
}
|
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);
|
@@ -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,91 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit';
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { Payment } from '$lib/models/Payment'; // adjust path as needed
|
||||
import { dbConnect, dbDisconnect } from '$lib/db/db';
|
||||
import { PaymentSplit } from '../../../../models/PaymentSplit';
|
||||
import { Payment } from '../../../../models/Payment'; // Need to import Payment for populate to work
|
||||
import { dbConnect, dbDisconnect } from '../../../../utils/db';
|
||||
import { error, json } from '@sveltejs/kit';
|
||||
|
||||
const UPLOAD_DIR = '/var/lib/www/static/test';
|
||||
const BASE_CURRENCY = 'CHF'; // Default currency
|
||||
|
||||
export const GET: RequestHandler = async ({ request, locals }) => {
|
||||
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]
|
||||
}
|
||||
}
|
||||
export const GET: RequestHandler = async ({ locals, url }) => {
|
||||
const auth = await locals.auth();
|
||||
if (!auth || !auth.user?.nickname) {
|
||||
throw error(401, 'Not logged in');
|
||||
}
|
||||
]);
|
||||
|
||||
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.find({ username })
|
||||
.populate('paymentId')
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(10)
|
||||
.lean();
|
||||
|
||||
// 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();
|
||||
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();
|
||||
}
|
||||
};
|
@@ -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 })
|
||||
.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();
|
||||
}
|
||||
};
|
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');
|
||||
}
|
||||
};
|
125
src/routes/cospend/+layout.svelte
Normal file
125
src/routes/cospend/+layout.svelte
Normal file
@@ -0,0 +1,125 @@
|
||||
<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';
|
||||
|
||||
let showModal = false;
|
||||
let paymentId = null;
|
||||
|
||||
$: {
|
||||
// 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';
|
||||
|
||||
console.log('Layout debug:', {
|
||||
pathname: $page.url.pathname,
|
||||
routeId: $page.route.id,
|
||||
match: match,
|
||||
statePaymentId: statePaymentId,
|
||||
isOnDashboard: isOnDashboard,
|
||||
showModal: showModal
|
||||
});
|
||||
|
||||
// Only show modal if we're on the dashboard AND have a payment to show
|
||||
if (isOnDashboard && (match || statePaymentId)) {
|
||||
showModal = true;
|
||||
paymentId = match ? match[1] : statePaymentId;
|
||||
} else {
|
||||
showModal = false;
|
||||
paymentId = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<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} />
|
||||
</div>
|
||||
{/key}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.layout-container {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.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: 0;
|
||||
right: 0;
|
||||
width: 400px;
|
||||
height: 100vh;
|
||||
background: white;
|
||||
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 (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);
|
||||
}
|
||||
}
|
||||
</style>
|
14
src/routes/cospend/+page.server.ts
Normal file
14
src/routes/cospend/+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
|
||||
};
|
||||
};
|
567
src/routes/cospend/+page.svelte
Normal file
567
src/routes/cospend/+page.svelte
Normal file
@@ -0,0 +1,567 @@
|
||||
<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 { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||
import { isSettlementPayment, getSettlementIcon, getSettlementClasses, getSettlementReceiver } from '$lib/utils/settlements';
|
||||
|
||||
export let data; // Used by the layout for session data
|
||||
|
||||
let balance = {
|
||||
netBalance: 0,
|
||||
recentSplits: []
|
||||
};
|
||||
let loading = true;
|
||||
let error = null;
|
||||
|
||||
onMount(async () => {
|
||||
await fetchBalance();
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
event.preventDefault();
|
||||
// Use pushState for true shallow routing - only updates URL without navigation
|
||||
pushState(`/cospend/payments/view/${paymentId}`, { paymentId });
|
||||
}
|
||||
|
||||
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">
|
||||
<div class="header-section">
|
||||
<h1>Cospend</h1>
|
||||
<p>Track and split expenses with your friends and family</p>
|
||||
</div>
|
||||
|
||||
<EnhancedBalance />
|
||||
|
||||
<div class="actions">
|
||||
<a href="/cospend/payments/add" class="btn btn-primary">Add Payment</a>
|
||||
<a href="/cospend/payments" class="btn btn-secondary">View All Payments</a>
|
||||
{#if balance.netBalance !== 0}
|
||||
<a href="/cospend/settle" class="btn btn-settlement">Settle Debts</a>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<DebtBreakdown />
|
||||
|
||||
{#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}
|
||||
even
|
||||
{/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>
|
||||
|
||||
<style>
|
||||
.cospend-main {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.header-section {
|
||||
text-align: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.header-section h1 {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.header-section p {
|
||||
color: #666;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
|
||||
.positive {
|
||||
color: #2e7d32;
|
||||
}
|
||||
|
||||
.negative {
|
||||
color: #d32f2f;
|
||||
}
|
||||
|
||||
.even {
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.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-primary {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.btn-settlement {
|
||||
background: linear-gradient(135deg, #28a745, #20c997);
|
||||
color: white;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-settlement:hover {
|
||||
background: linear-gradient(135deg, #20c997, #1e7e34);
|
||||
}
|
||||
|
||||
.recent-activity {
|
||||
background: white;
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.recent-activity h2 {
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.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: #f8f9fa;
|
||||
border-radius: 1rem;
|
||||
padding: 1rem;
|
||||
position: relative;
|
||||
border: 1px solid #e9ecef;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
display: block;
|
||||
transition: all 0.2s;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.activity-message.is-me .activity-bubble {
|
||||
background: #e3f2fd;
|
||||
border-color: #2196f3;
|
||||
}
|
||||
|
||||
.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: #f8f9fa;
|
||||
}
|
||||
|
||||
.activity-message.is-me .activity-bubble::before {
|
||||
left: auto;
|
||||
right: -15px;
|
||||
border-left-color: #e3f2fd;
|
||||
border-right-color: transparent;
|
||||
}
|
||||
|
||||
|
||||
/* New Settlement Flow Activity Styles */
|
||||
.settlement-flow-activity {
|
||||
display: block;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
background: linear-gradient(135deg, #f8fff9, #e8f5e8);
|
||||
border: 2px solid #28a745;
|
||||
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(40, 167, 69, 0.2);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.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: #28a745;
|
||||
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: #28a745;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.settlement-flow-arrow {
|
||||
font-size: 1.8rem;
|
||||
color: #28a745;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.settlement-date {
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.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: #888;
|
||||
font-size: 0.8rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.payment-title {
|
||||
color: #333;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.username {
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
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: #666;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.payment-description {
|
||||
color: #555;
|
||||
font-size: 0.9rem;
|
||||
font-style: italic;
|
||||
margin-top: 0.25rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
</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
|
||||
};
|
||||
}
|
14
src/routes/cospend/payments/+page.server.ts
Normal file
14
src/routes/cospend/payments/+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
|
||||
};
|
||||
};
|
626
src/routes/cospend/payments/+page.svelte
Normal file
626
src/routes/cospend/payments/+page.svelte
Normal file
@@ -0,0 +1,626 @@
|
||||
<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';
|
||||
|
||||
export let data;
|
||||
|
||||
let payments = [];
|
||||
let loading = true;
|
||||
let error = null;
|
||||
let currentPage = 0;
|
||||
let limit = 20;
|
||||
let hasMore = true;
|
||||
|
||||
onMount(async () => {
|
||||
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>
|
||||
<p>Manage your shared expenses</p>
|
||||
</div>
|
||||
<div class="header-actions">
|
||||
<a href="/cospend/payments/add" class="btn btn-primary">Add Payment</a>
|
||||
<a href="/cospend" class="btn btn-secondary">Back to Dashboard</a>
|
||||
</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}
|
||||
<div 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}
|
||||
even
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="payment-actions">
|
||||
<span class="created-by">Created by {payment.createdBy}</span>
|
||||
{#if payment.createdBy === data.session.user.nickname}
|
||||
<div class="action-buttons">
|
||||
<button
|
||||
class="btn-edit"
|
||||
on:click={() => goto(`/cospend/payments/edit/${payment._id}`)}
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
class="btn-delete"
|
||||
on:click={() => deletePayment(payment._id)}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if hasMore}
|
||||
<div class="load-more">
|
||||
<button class="btn btn-secondary" on:click={loadMore} disabled={loading}>
|
||||
{loading ? 'Loading...' : 'Load More'}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.payments-list {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 2rem;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.header-content h1 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: #333;
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.header-content p {
|
||||
margin: 0;
|
||||
color: #666;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.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: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 4rem 2rem;
|
||||
}
|
||||
|
||||
.empty-content svg {
|
||||
color: #ccc;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.empty-content h2 {
|
||||
margin: 0 0 0.5rem 0;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.empty-content p {
|
||||
margin: 0 0 2rem 0;
|
||||
color: #777;
|
||||
}
|
||||
|
||||
.payments-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
|
||||
gap: 1.5rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.payment-card {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
padding: 1.5rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.payment-card:hover {
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.settlement-card {
|
||||
background: linear-gradient(135deg, #f8fff9, #f0f8f0);
|
||||
border: 2px solid #28a745;
|
||||
}
|
||||
|
||||
.settlement-card:hover {
|
||||
box-shadow: 0 4px 16px rgba(40, 167, 69, 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: #28a745;
|
||||
}
|
||||
|
||||
.settlement-arrow {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.settlement-arrow .arrow {
|
||||
color: #28a745;
|
||||
font-size: 1.2rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.settlement-badge-small {
|
||||
background: linear-gradient(135deg, #28a745, #20c997);
|
||||
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: #28a745;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.payment-meta {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.payment-meta .category-name {
|
||||
color: #888;
|
||||
font-style: italic;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.payment-meta .amount {
|
||||
font-weight: 600;
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.receipt-thumb {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
object-fit: cover;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.payment-description {
|
||||
color: #555;
|
||||
margin-bottom: 1rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.payment-details {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.detail-row .label {
|
||||
color: #666;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.detail-row .value {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.splits-summary {
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.splits-summary h4 {
|
||||
margin: 0 0 0.75rem 0;
|
||||
color: #333;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.splits-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.split-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.split-user {
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.split-amount.positive {
|
||||
color: #2e7d32;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.split-amount.negative {
|
||||
color: #d32f2f;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.payment-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
.created-by {
|
||||
font-size: 0.9rem;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn-edit, .btn-delete {
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 0.25rem;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-edit {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.btn-edit:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.btn-delete {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-delete:hover {
|
||||
background-color: #c62828;
|
||||
}
|
||||
|
||||
.load-more {
|
||||
text-align: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
.payment-actions {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
}
|
||||
}
|
||||
</style>
|
14
src/routes/cospend/payments/add/+page.server.ts
Normal file
14
src/routes/cospend/payments/add/+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
|
||||
};
|
||||
};
|
929
src/routes/cospend/payments/add/+page.svelte
Normal file
929
src/routes/cospend/payments/add/+page.svelte
Normal file
@@ -0,0 +1,929 @@
|
||||
<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 ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||
|
||||
export let data;
|
||||
|
||||
let formData = {
|
||||
title: '',
|
||||
description: '',
|
||||
amount: '',
|
||||
paidBy: data.session?.user?.nickname || '',
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
category: 'groceries',
|
||||
splitMethod: 'equal',
|
||||
splits: []
|
||||
};
|
||||
|
||||
let imageFile = null;
|
||||
let imagePreview = '';
|
||||
let users = [];
|
||||
let newUser = '';
|
||||
let splitAmounts = {};
|
||||
let personalAmounts = {};
|
||||
let loading = false;
|
||||
let error = null;
|
||||
let personalTotalError = false;
|
||||
let predefinedMode = isPredefinedUsersMode();
|
||||
|
||||
$: categoryOptions = getCategoryOptions();
|
||||
|
||||
onMount(() => {
|
||||
if (predefinedMode) {
|
||||
// Use predefined users and always split between them
|
||||
users = [...PREDEFINED_USERS];
|
||||
users.forEach(user => addSplitForUser(user));
|
||||
// Default to current user as payer if they're in the predefined list
|
||||
if (data.session?.user?.nickname && PREDEFINED_USERS.includes(data.session.user.nickname)) {
|
||||
formData.paidBy = data.session.user.nickname;
|
||||
} else {
|
||||
formData.paidBy = PREDEFINED_USERS[0];
|
||||
}
|
||||
} else {
|
||||
// Original behavior for manual user management
|
||||
if (data.session?.user?.nickname) {
|
||||
users = [data.session.user.nickname];
|
||||
addSplitForUser(data.session.user.nickname);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function handleImageChange(event) {
|
||||
const file = event.target.files[0];
|
||||
if (file) {
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
alert('File size must be less than 5MB');
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
alert('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);
|
||||
}
|
||||
}
|
||||
|
||||
function removeImage() {
|
||||
imageFile = null;
|
||||
imagePreview = '';
|
||||
}
|
||||
|
||||
function addUser() {
|
||||
if (predefinedMode) return; // No adding users in predefined mode
|
||||
|
||||
if (newUser.trim() && !users.includes(newUser.trim())) {
|
||||
users = [...users, newUser.trim()];
|
||||
addSplitForUser(newUser.trim());
|
||||
newUser = '';
|
||||
}
|
||||
}
|
||||
|
||||
function removeUser(userToRemove) {
|
||||
if (predefinedMode) return; // No removing users in predefined mode
|
||||
|
||||
if (users.length > 1 && userToRemove !== data.session.user.nickname) {
|
||||
users = users.filter(u => u !== userToRemove);
|
||||
delete splitAmounts[userToRemove];
|
||||
splitAmounts = { ...splitAmounts };
|
||||
}
|
||||
}
|
||||
|
||||
function addSplitForUser(username) {
|
||||
if (!splitAmounts[username]) {
|
||||
splitAmounts[username] = 0;
|
||||
splitAmounts = { ...splitAmounts };
|
||||
}
|
||||
}
|
||||
|
||||
function calculateEqualSplits() {
|
||||
if (!formData.amount || users.length === 0) return;
|
||||
|
||||
const amountNum = parseFloat(formData.amount);
|
||||
const splitAmount = amountNum / users.length;
|
||||
|
||||
users.forEach(user => {
|
||||
if (user === formData.paidBy) {
|
||||
splitAmounts[user] = splitAmount - amountNum; // They get negative (they're owed)
|
||||
} else {
|
||||
splitAmounts[user] = splitAmount; // They owe positive amount
|
||||
}
|
||||
});
|
||||
splitAmounts = { ...splitAmounts };
|
||||
}
|
||||
|
||||
function calculateFullPayment() {
|
||||
if (!formData.amount) return;
|
||||
|
||||
const amountNum = parseFloat(formData.amount);
|
||||
|
||||
users.forEach(user => {
|
||||
if (user === formData.paidBy) {
|
||||
splitAmounts[user] = -amountNum; // They paid it all, so they're owed the full amount
|
||||
} else {
|
||||
splitAmounts[user] = 0; // Others don't owe anything
|
||||
}
|
||||
});
|
||||
splitAmounts = { ...splitAmounts };
|
||||
}
|
||||
|
||||
function calculatePersonalEqualSplit() {
|
||||
if (!formData.amount || users.length === 0) return;
|
||||
|
||||
const totalAmount = parseFloat(formData.amount);
|
||||
|
||||
// Calculate total personal amounts
|
||||
const totalPersonal = users.reduce((sum, user) => {
|
||||
return sum + (parseFloat(personalAmounts[user]) || 0);
|
||||
}, 0);
|
||||
|
||||
// Remaining amount to be split equally
|
||||
const remainder = Math.max(0, totalAmount - totalPersonal);
|
||||
const equalShare = remainder / users.length;
|
||||
|
||||
users.forEach(user => {
|
||||
const personalAmount = parseFloat(personalAmounts[user]) || 0;
|
||||
const totalOwed = personalAmount + equalShare;
|
||||
|
||||
if (user === formData.paidBy) {
|
||||
// Person who paid gets back what others owe minus what they personally used
|
||||
splitAmounts[user] = totalOwed - totalAmount;
|
||||
} else {
|
||||
// Others owe their personal amount + equal share
|
||||
splitAmounts[user] = totalOwed;
|
||||
}
|
||||
});
|
||||
splitAmounts = { ...splitAmounts };
|
||||
}
|
||||
|
||||
function handleSplitMethodChange() {
|
||||
if (formData.splitMethod === 'equal') {
|
||||
calculateEqualSplits();
|
||||
} else if (formData.splitMethod === 'full') {
|
||||
calculateFullPayment();
|
||||
} else if (formData.splitMethod === 'personal_equal') {
|
||||
calculatePersonalEqualSplit();
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadImage() {
|
||||
if (!imageFile) return null;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!formData.title.trim() || !formData.amount || parseFloat(formData.amount) <= 0) {
|
||||
error = 'Please fill in all required fields with valid values';
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate personal amounts for personal_equal split
|
||||
if (formData.splitMethod === 'personal_equal') {
|
||||
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
||||
const totalAmount = parseFloat(formData.amount);
|
||||
|
||||
if (totalPersonal > totalAmount) {
|
||||
error = 'Personal amounts cannot exceed the total payment amount';
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (users.length === 0) {
|
||||
error = 'Please add at least one user to split with';
|
||||
return;
|
||||
}
|
||||
|
||||
loading = true;
|
||||
error = null;
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
$: if (formData.amount && formData.splitMethod && formData.paidBy) {
|
||||
handleSplitMethodChange();
|
||||
}
|
||||
|
||||
// Validate and recalculate when personal amounts change
|
||||
$: if (formData.splitMethod === 'personal_equal' && personalAmounts && formData.amount) {
|
||||
const totalPersonal = Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0);
|
||||
const totalAmount = parseFloat(formData.amount);
|
||||
personalTotalError = totalPersonal > totalAmount;
|
||||
|
||||
if (!personalTotalError) {
|
||||
calculatePersonalEqualSplit();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Add Payment - Cospend</title>
|
||||
</svelte:head>
|
||||
|
||||
<main class="add-payment">
|
||||
<div class="header">
|
||||
<h1>Add New Payment</h1>
|
||||
<a href="/cospend" class="back-link">← Back to Cospend</a>
|
||||
</div>
|
||||
|
||||
<form on:submit|preventDefault={handleSubmit} class="payment-form">
|
||||
<div class="form-section">
|
||||
<h2>Payment Details</h2>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="title">Title *</label>
|
||||
<input
|
||||
type="text"
|
||||
id="title"
|
||||
bind:value={formData.title}
|
||||
required
|
||||
placeholder="e.g., Dinner at restaurant"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="description">Description</label>
|
||||
<textarea
|
||||
id="description"
|
||||
bind:value={formData.description}
|
||||
placeholder="Additional details..."
|
||||
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="date">Date</label>
|
||||
<input
|
||||
type="date"
|
||||
id="date"
|
||||
bind:value={formData.date}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</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-section">
|
||||
<h2>Receipt Image</h2>
|
||||
|
||||
{#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>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}
|
||||
hidden
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="form-section">
|
||||
<h2>Split Between Users</h2>
|
||||
|
||||
{#if predefinedMode}
|
||||
<div class="predefined-users">
|
||||
<p class="predefined-note">Splitting between predefined users:</p>
|
||||
<div class="users-list">
|
||||
{#each users as user}
|
||||
<div class="user-item with-profile">
|
||||
<ProfilePicture username={user} size={32} />
|
||||
<span class="username">{user}</span>
|
||||
{#if user === data.session?.user?.nickname}
|
||||
<span class="you-badge">You</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="users-list">
|
||||
{#each users as user}
|
||||
<div class="user-item with-profile">
|
||||
<ProfilePicture username={user} size={32} />
|
||||
<span class="username">{user}</span>
|
||||
{#if user !== data.session.user.nickname}
|
||||
<button type="button" class="remove-user" on:click={() => removeUser(user)}>
|
||||
Remove
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="add-user">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={newUser}
|
||||
placeholder="Add user..."
|
||||
on:keydown={(e) => e.key === 'Enter' && (e.preventDefault(), addUser())}
|
||||
/>
|
||||
<button type="button" on:click={addUser}>Add User</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="form-section">
|
||||
<h2>Split Method</h2>
|
||||
|
||||
<div class="split-method">
|
||||
<label>
|
||||
<input type="radio" bind:group={formData.splitMethod} value="equal" />
|
||||
{predefinedMode && users.length === 2 ? 'Split 50/50' : 'Equal Split'}
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" bind:group={formData.splitMethod} value="personal_equal" />
|
||||
Personal + Equal Split
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" bind:group={formData.splitMethod} value="full" />
|
||||
Paid in Full by {formData.paidBy}
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" bind:group={formData.splitMethod} value="proportional" />
|
||||
Custom Proportions
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{#if formData.splitMethod === 'proportional'}
|
||||
<div class="proportional-splits">
|
||||
<h3>Custom Split Amounts</h3>
|
||||
{#each users as user}
|
||||
<div class="split-input">
|
||||
<label>{user}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
bind:value={splitAmounts[user]}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if formData.splitMethod === 'personal_equal'}
|
||||
<div class="personal-splits">
|
||||
<h3>Personal Amounts</h3>
|
||||
<p class="description">Enter personal amounts for each user. The remainder will be split equally.</p>
|
||||
{#each users as user}
|
||||
<div class="split-input">
|
||||
<label>{user}</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
bind:value={personalAmounts[user]}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
{#if formData.amount}
|
||||
<div class="remainder-info" class:error={personalTotalError}>
|
||||
<span>Total Personal: CHF {Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0).toFixed(2)}</span>
|
||||
<span>Remainder to Split: CHF {Math.max(0, parseFloat(formData.amount) - Object.values(personalAmounts).reduce((sum, val) => sum + (parseFloat(val) || 0), 0)).toFixed(2)}</span>
|
||||
{#if personalTotalError}
|
||||
<div class="error-message">⚠️ Personal amounts exceed total payment amount!</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if Object.keys(splitAmounts).length > 0}
|
||||
<div class="split-preview">
|
||||
<h3>Split Preview</h3>
|
||||
{#each users as user}
|
||||
<div class="split-item">
|
||||
<div class="split-user">
|
||||
<ProfilePicture username={user} size={24} />
|
||||
<span class="username">{user}</span>
|
||||
</div>
|
||||
<span class="amount" class:positive={splitAmounts[user] < 0} class:negative={splitAmounts[user] > 0}>
|
||||
{#if splitAmounts[user] > 0}
|
||||
owes CHF {splitAmounts[user].toFixed(2)}
|
||||
{:else if splitAmounts[user] < 0}
|
||||
is owed CHF {Math.abs(splitAmounts[user]).toFixed(2)}
|
||||
{:else}
|
||||
even
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<div class="error">{error}</div>
|
||||
{/if}
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="button" class="btn-secondary" on:click={() => goto('/cospend')}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" class="btn-primary" disabled={loading}>
|
||||
{loading ? 'Creating...' : 'Create Payment'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.add-payment {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.payment-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.form-section {
|
||||
background: white;
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.form-section h2 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
input:focus, textarea:focus, select:focus {
|
||||
outline: none;
|
||||
border-color: #1976d2;
|
||||
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
|
||||
}
|
||||
|
||||
.image-upload {
|
||||
border: 2px dashed #ddd;
|
||||
border-radius: 0.5rem;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.image-upload:hover {
|
||||
border-color: #1976d2;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.upload-label {
|
||||
cursor: pointer;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.upload-content svg {
|
||||
color: #666;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.upload-content p {
|
||||
margin: 0 0 0.5rem 0;
|
||||
font-weight: 500;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.upload-content small {
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.image-preview {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.image-preview img {
|
||||
max-width: 100%;
|
||||
max-height: 300px;
|
||||
border-radius: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.remove-image {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 0.25rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.users-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.user-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
background-color: #f5f5f5;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 1rem;
|
||||
}
|
||||
|
||||
.user-item.with-profile {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.user-item .username {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.predefined-users {
|
||||
background-color: #f8f9fa;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.predefined-note {
|
||||
margin: 0 0 1rem 0;
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.remove-user {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.add-user {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.add-user input {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.add-user button {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.split-method {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.split-method label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.proportional-splits {
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.proportional-splits h3 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.split-preview {
|
||||
background-color: #f8f9fa;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.split-preview h3 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.split-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.split-user {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.amount.positive {
|
||||
color: #2e7d32;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.amount.negative {
|
||||
color: #d32f2f;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.error {
|
||||
background-color: #ffebee;
|
||||
color: #d32f2f;
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.btn-primary, .btn-secondary {
|
||||
padding: 0.75rem 1.5rem;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.personal-splits {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.personal-splits .description {
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 1rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.remainder-info {
|
||||
margin-top: 1rem;
|
||||
padding: 1rem;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid #e9ecef;
|
||||
}
|
||||
|
||||
.remainder-info.error {
|
||||
background-color: #fff5f5;
|
||||
border-color: #fed7d7;
|
||||
}
|
||||
|
||||
.remainder-info span {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #d32f2f;
|
||||
font-weight: 600;
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
@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
|
||||
};
|
||||
};
|
570
src/routes/cospend/payments/edit/[id]/+page.svelte
Normal file
570
src/routes/cospend/payments/edit/[id]/+page.svelte
Normal file
@@ -0,0 +1,570 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { getCategoryOptions } from '$lib/utils/categories';
|
||||
|
||||
export let data;
|
||||
|
||||
let payment = null;
|
||||
let loading = true;
|
||||
let saving = false;
|
||||
let uploading = false;
|
||||
let error = null;
|
||||
let imageFile = null;
|
||||
|
||||
$: 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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
} finally {
|
||||
uploading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleImageRemove() {
|
||||
payment.image = null;
|
||||
}
|
||||
|
||||
function handleFileChange(event) {
|
||||
const file = event.target.files[0];
|
||||
if (file) {
|
||||
imageFile = file;
|
||||
handleImageUpload();
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
<a href="/cospend/payments" class="back-link">← Back to Payments</a>
|
||||
</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">
|
||||
<div class="form-section">
|
||||
<h2>Payment Details</h2>
|
||||
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div class="form-section">
|
||||
<h2>Receipt Image</h2>
|
||||
|
||||
{#if payment.image}
|
||||
<div class="current-image">
|
||||
<img src={payment.image} alt="Receipt" class="receipt-preview" />
|
||||
<div class="image-actions">
|
||||
<button type="button" class="btn-remove" on:click={handleImageRemove}>
|
||||
Remove Image
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="form-group">
|
||||
<label for="imageUpload" class="upload-label">
|
||||
{payment.image ? 'Replace Image' : 'Upload Receipt Image'}
|
||||
</label>
|
||||
<input
|
||||
type="file"
|
||||
id="imageUpload"
|
||||
accept="image/*"
|
||||
on:change={handleFileChange}
|
||||
disabled={uploading}
|
||||
class="file-input"
|
||||
/>
|
||||
{#if uploading}
|
||||
<div class="upload-status">Uploading image...</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if payment.splits && payment.splits.length > 0}
|
||||
<div class="form-section">
|
||||
<h2>Current Splits</h2>
|
||||
<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}
|
||||
even
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<p class="note">Note: To modify splits, please delete and recreate the payment.</p>
|
||||
</div>
|
||||
{/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 {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.payment-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2rem;
|
||||
}
|
||||
|
||||
.form-section {
|
||||
background: white;
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.form-section h2 {
|
||||
margin-top: 0;
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
input, textarea, select {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 0.5rem;
|
||||
font-size: 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
input:focus, textarea:focus, select:focus {
|
||||
outline: none;
|
||||
border-color: #1976d2;
|
||||
box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
|
||||
}
|
||||
|
||||
select {
|
||||
background-color: white;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.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: #f8f9fa;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.positive {
|
||||
color: #2e7d32;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.negative {
|
||||
color: #d32f2f;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.note {
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
font-style: italic;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.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: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-primary:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background-color: #c62828;
|
||||
}
|
||||
|
||||
.btn-danger:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.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 #ddd;
|
||||
margin-bottom: 0.75rem;
|
||||
display: block;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.image-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.btn-remove {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 0.25rem;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-remove:hover {
|
||||
background-color: #c62828;
|
||||
}
|
||||
|
||||
.upload-label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.file-input {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 2px dashed #ddd;
|
||||
border-radius: 0.5rem;
|
||||
background-color: #fafafa;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.file-input:hover {
|
||||
border-color: #1976d2;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.file-input:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.upload-status {
|
||||
margin-top: 0.5rem;
|
||||
color: #1976d2;
|
||||
font-size: 0.9rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@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>
|
15
src/routes/cospend/payments/view/[id]/+page.server.ts
Normal file
15
src/routes/cospend/payments/view/[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
|
||||
};
|
||||
};
|
478
src/routes/cospend/payments/view/[id]/+page.svelte
Normal file
478
src/routes/cospend/payments/view/[id]/+page.svelte
Normal file
@@ -0,0 +1,478 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||
import { getCategoryEmoji, getCategoryName } from '$lib/utils/categories';
|
||||
|
||||
export let data;
|
||||
|
||||
let payment = null;
|
||||
let loading = true;
|
||||
let error = null;
|
||||
|
||||
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 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">
|
||||
<div class="header">
|
||||
<div class="header-content">
|
||||
<a href="/cospend" class="back-link">← Back to Dashboard</a>
|
||||
<div class="header-actions">
|
||||
{#if payment && payment.createdBy === data.session.user.nickname}
|
||||
<a href="/cospend/payments/edit/{data.paymentId}" class="btn btn-secondary">Edit</a>
|
||||
<button
|
||||
class="btn btn-danger"
|
||||
on:click={deletePayment}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? 'Deleting...' : 'Delete'}
|
||||
</button>
|
||||
{/if}
|
||||
<a href="/cospend/payments" class="btn btn-secondary">All Payments</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#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}
|
||||
even
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.payment-view {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.header {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 0.25rem;
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
transition: all 0.2s;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background-color: #d32f2f;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover:not(:disabled) {
|
||||
background-color: #c62828;
|
||||
}
|
||||
|
||||
.btn-danger:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.payment-card {
|
||||
background: white;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.payment-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
padding: 2rem;
|
||||
background: linear-gradient(135deg, #f8f9fa, #e9ecef);
|
||||
border-bottom: 1px solid #dee2e6;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
|
||||
.payment-amount {
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.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 #ddd;
|
||||
}
|
||||
|
||||
.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: #666;
|
||||
font-size: 0.9rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: #333;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.description {
|
||||
border-top: 1px solid #eee;
|
||||
padding-top: 1.5rem;
|
||||
}
|
||||
|
||||
.description h3 {
|
||||
margin: 0 0 0.75rem 0;
|
||||
color: #333;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.description p {
|
||||
margin: 0;
|
||||
color: #555;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.splits-section {
|
||||
border-top: 1px solid #eee;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.splits-section h3 {
|
||||
margin: 0 0 1rem 0;
|
||||
color: #333;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.splits-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.split-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
background: #f8f9fa;
|
||||
border-radius: 0.5rem;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.split-item.current-user {
|
||||
background: #e3f2fd;
|
||||
border-color: #2196f3;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 1rem;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.split-amount {
|
||||
font-weight: 500;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.split-amount.positive {
|
||||
color: #2e7d32;
|
||||
}
|
||||
|
||||
.split-amount.negative {
|
||||
color: #d32f2f;
|
||||
}
|
||||
|
||||
@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>
|
13
src/routes/cospend/settle/+page.server.ts
Normal file
13
src/routes/cospend/settle/+page.server.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
|
||||
export const load: PageServerLoad = async ({ locals }) => {
|
||||
const auth = await locals.auth();
|
||||
if (!auth || !auth.user) {
|
||||
throw redirect(302, '/login');
|
||||
}
|
||||
|
||||
return {
|
||||
session: auth
|
||||
};
|
||||
};
|
608
src/routes/cospend/settle/+page.svelte
Normal file
608
src/routes/cospend/settle/+page.svelte
Normal file
@@ -0,0 +1,608 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import ProfilePicture from '$lib/components/ProfilePicture.svelte';
|
||||
import { PREDEFINED_USERS, isPredefinedUsersMode } from '$lib/config/users';
|
||||
|
||||
export let data;
|
||||
|
||||
let debtData = {
|
||||
whoOwesMe: [],
|
||||
whoIOwe: [],
|
||||
totalOwedToMe: 0,
|
||||
totalIOwe: 0
|
||||
};
|
||||
let loading = true;
|
||||
let error = null;
|
||||
let selectedSettlement = null;
|
||||
let settlementAmount = '';
|
||||
let submitting = false;
|
||||
let predefinedMode = isPredefinedUsersMode();
|
||||
|
||||
onMount(async () => {
|
||||
await fetchDebtData();
|
||||
});
|
||||
|
||||
async function fetchDebtData() {
|
||||
try {
|
||||
loading = true;
|
||||
const response = await fetch('/api/cospend/debts');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch debt data');
|
||||
}
|
||||
debtData = await response.json();
|
||||
|
||||
// For predefined mode with 2 users, auto-select the debt if there's only one
|
||||
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.session?.user?.nickname,
|
||||
amount: debtData.whoOwesMe[0].netAmount,
|
||||
description: `Settlement: ${debtData.whoOwesMe[0].username} pays ${data.session?.user?.nickname}`
|
||||
};
|
||||
settlementAmount = debtData.whoOwesMe[0].netAmount.toString();
|
||||
} else if (debtData.whoIOwe.length === 1) {
|
||||
selectedSettlement = {
|
||||
type: 'pay',
|
||||
from: data.session?.user?.nickname,
|
||||
to: debtData.whoIOwe[0].username,
|
||||
amount: debtData.whoIOwe[0].netAmount,
|
||||
description: `Settlement: ${data.session?.user?.nickname} pays ${debtData.whoIOwe[0].username}`
|
||||
};
|
||||
settlementAmount = debtData.whoIOwe[0].netAmount.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectSettlement(type, user, amount) {
|
||||
const currentUser = data.session?.user?.nickname;
|
||||
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;
|
||||
}
|
||||
|
||||
try {
|
||||
submitting = true;
|
||||
error = null;
|
||||
|
||||
// Create a settlement payment
|
||||
const payload = {
|
||||
title: `Settlement Payment`,
|
||||
description: selectedSettlement.description,
|
||||
amount: amount,
|
||||
paidBy: selectedSettlement.from,
|
||||
date: new Date().toISOString().split('T')[0],
|
||||
category: 'settlement', // Using settlement category
|
||||
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
|
||||
goto('/cospend');
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
} finally {
|
||||
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.session?.user?.nickname}
|
||||
<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.session?.user?.nickname}
|
||||
<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>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="back-actions">
|
||||
<a href="/cospend" class="btn btn-secondary">← Back to Dashboard</a>
|
||||
</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: #333;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.header-section p {
|
||||
color: #666;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
background-color: #ffebee;
|
||||
border-radius: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.no-debts {
|
||||
text-align: center;
|
||||
padding: 3rem 2rem;
|
||||
background: white;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.no-debts h2 {
|
||||
color: #28a745;
|
||||
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: white;
|
||||
padding: 1.5rem;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.settlement-section {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.settlement-section h3 {
|
||||
color: #333;
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.settlement-option {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
border: 2px solid #e9ecef;
|
||||
border-radius: 0.75rem;
|
||||
margin-bottom: 0.75rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.settlement-option:hover {
|
||||
border-color: #28a745;
|
||||
box-shadow: 0 2px 8px rgba(40, 167, 69, 0.1);
|
||||
}
|
||||
|
||||
.settlement-option.selected {
|
||||
border-color: #28a745;
|
||||
background-color: #f8fff9;
|
||||
}
|
||||
|
||||
.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: #333;
|
||||
}
|
||||
|
||||
.debt-amount {
|
||||
color: #666;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.settlement-action {
|
||||
color: #28a745;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.settlement-details {
|
||||
background: white;
|
||||
padding: 1.5rem;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
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: #f8f9fa;
|
||||
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: #28a745;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.you-badge {
|
||||
background-color: #1976d2;
|
||||
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: #333;
|
||||
}
|
||||
|
||||
.amount-input {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #f8f9fa;
|
||||
border: 1px solid #ced4da;
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.currency {
|
||||
color: #666;
|
||||
font-weight: 500;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.amount-input input {
|
||||
border: none;
|
||||
background: none;
|
||||
flex: 1;
|
||||
padding: 0.25rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.amount-input input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.max-amount {
|
||||
color: #666;
|
||||
font-size: 0.85rem;
|
||||
margin-top: 0.25rem;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.settlement-description {
|
||||
color: #333;
|
||||
font-size: 0.9rem;
|
||||
padding: 1rem;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 0.375rem;
|
||||
}
|
||||
|
||||
.settlement-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.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: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
.btn-settlement {
|
||||
background: linear-gradient(135deg, #28a745, #20c997);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-settlement:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #20c997, #1e7e34);
|
||||
}
|
||||
|
||||
.btn-settlement:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.back-actions {
|
||||
text-align: center;
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.actions {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
@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>
|
Reference in New Issue
Block a user