Refactor year management in the database layer, enhance Year model with budget field, and update UI components for year selection and dashboard display

This commit is contained in:
Norbert Maciaszek
2025-11-25 00:16:21 +01:00
parent 1030991d92
commit f31eb3dc0d
15 changed files with 498 additions and 14 deletions

View File

@@ -0,0 +1,12 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Year" (
"year" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"budget" REAL NOT NULL DEFAULT 3000
);
INSERT INTO "new_Year" ("year") SELECT "year" FROM "Year";
DROP TABLE "Year";
ALTER TABLE "new_Year" RENAME TO "Year";
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;

View File

@@ -10,7 +10,8 @@ datasource db {
} }
model Year { model Year {
year Int @id year Int @id
budget Float @default(3000)
people Person[] people Person[]
} }

View File

@@ -0,0 +1,31 @@
<script>
import { XIcon } from 'lucide-svelte';
import { fade } from 'svelte/transition';
let { isOpen, onClose, children, heading = 'Modal' } = $props();
</script>
<div
role="dialog"
aria-modal="true"
transition:fade={{ duration: 200 }}
class="fixed inset-0 bg-black/50 flex justify-center items-center"
onclick={(e) => {
if (e.target === e.currentTarget) {
onClose();
}
}}
>
<div class="bg-neutral-200 rounded-lg text-black shadow-md min-w-xl">
{#if heading}
<div class="p-4 flex justify-between items-center border-b border-neutral-400">
<h2 class="text-lg font-bold">{heading}</h2>
<XIcon class="size-6 cursor-pointer" onclick={onClose} />
</div>
{/if}
<div class="p-4">
{@render children()}
</div>
</div>
</div>

View File

@@ -0,0 +1,102 @@
<script lang="ts">
import { formatCurrency } from '$lib/helpers/formatCurrency';
import { deleteGift, updateGift, type getPeople } from '$lib/remotes/db.remote';
import { Circle, CircleCheck, Square, SquarePen, Trash } from 'lucide-svelte';
type Props = {
gift: Awaited<ReturnType<typeof getPeople>>[number]['gifts'][number];
};
let { gift }: Props = $props();
let editing = $state(false);
let purchased = $derived(gift.status === 'BOUGHT');
let wrapped = $derived(gift.status === 'WRAPPED');
let given = $derived(gift.status === 'GIVEN');
let buy = $derived(gift.status === 'BUY');
let planned = $derived(gift.status === 'PLANNED');
const handleUpdateGift = (update: Partial<Props['gift']>) => {
updateGift({ id: gift.id, ...update });
};
function editable(element: HTMLElement, key: keyof Props['gift']) {
function handleBlur() {
let value: any = element.innerText;
if (key === 'price') {
value = parseFloat(value);
}
handleUpdateGift({ [key]: value });
}
$effect(() => {
element.contentEditable = editing ? 'true' : 'false';
if (editing) {
element.classList.add('border-2', 'border-red-500', 'border-dashed');
} else {
element.classList.remove('border-2', 'border-red-500', 'border-dashed');
}
});
element.addEventListener('blur', handleBlur);
return {
destroy() {
element.removeEventListener('blur', handleBlur);
}
};
}
</script>
<div
class={[
'flex items-start gap-3 p-3 rounded-lg border mt-4',
purchased && 'bg-green-50 border-green-100',
wrapped && 'bg-yellow-50 border-yellow-100',
given && 'bg-blue-50 border-blue-100',
buy && 'bg-red-50 border-red-100',
planned && 'bg-gray-50 border-gray-100'
]}
>
<div class="flex justify-between items-center w-full">
<div class="flex items-center gap-2">
<button
class="cursor-pointer"
onclick={() => handleUpdateGift({ status: purchased ? 'PLANNED' : 'BOUGHT' })}
>
{#if purchased}
<CircleCheck class="w-5 h-5 text-green-500" />
{:else}
<Circle class="w-5 h-5" />
{/if}
</button>
<div class="flex flex-col">
<h4 class="text-sm font-medium flex items-center gap-2">
<span use:editable={'name'}>{gift.name}</span>
{#if editing}
<Square class="size-3 cursor-pointer" onclick={() => (editing = false)} />
{:else}
<SquarePen class="size-3 cursor-pointer" onclick={() => (editing = true)} />
{/if}
</h4>
<p class="text-xs text-gray-500" use:editable={'description'}>{gift.description}</p>
<span use:editable={'url'} class:hidden={!editing}>{gift.url}</span>
{#if !editing}
{#each gift.url?.split('\n') as line}
<a href={line} target="_blank" class="text-xs text-blue-500">
{line}
</a>
{/each}
{/if}
</div>
</div>
<div class="text-xs text-gray-500 flex items-center gap-2">
<span use:editable={'price'} class:hidden={!editing}>{gift.price}</span>
{#if !editing}
{formatCurrency(gift.price ?? 0)}
{/if}
<Trash class="text-red-500 cursor-pointer size-3" onclick={() => deleteGift(gift.id)} />
</div>
</div>
</div>

View File

@@ -0,0 +1,84 @@
<script lang="ts">
import { addGift } from '$lib/remotes/db.remote';
import { GiftStatus, type Gift } from '@prisma/client';
import { Plus } from 'lucide-svelte';
import Modal from '../atoms/Modal.svelte';
let { personId, personName } = $props();
let isOpen = $state(false);
let gift: Omit<Gift, 'id' | 'personId'> = $state({
name: '',
price: 0,
url: '',
description: '',
status: 'PLANNED'
});
const open = () => {
isOpen = true;
};
const close = () => {
isOpen = false;
};
const handleAddGift = () => {
addGift({
personId,
gift: {
name: gift.name,
price: gift.price ?? 0,
url: gift.url ?? '',
description: gift.description ?? '',
status: gift.status
}
}).then(close);
};
const inputClasses = [
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive'
];
</script>
<button
class="w-full border-dashed border-2 mt-4 hover:bg-red-50 hover:border-red-200 hover:text-red-600 flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer p-2"
onclick={open}
>
<Plus class="w-4 h-4" />
Dodaj prezent dla {personName}
</button>
{#if isOpen}
<Modal {isOpen} heading="Dodaj nową osobę" onClose={close}>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">Nazwa</legend>
<input type="text" bind:value={gift.name} placeholder="Prezentu" class={inputClasses} />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">Cena</legend>
<input type="number" bind:value={gift.price} placeholder="Cena" class={inputClasses} />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">URL</legend>
<input type="url" bind:value={gift.url} placeholder="URL" class={inputClasses} />
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">Opis</legend>
<textarea bind:value={gift.description} placeholder="Opis"></textarea>
</fieldset>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">Status</legend>
<select bind:value={gift.status} class={inputClasses}>
{#each Object.values(GiftStatus) as status}
<option value={status}>{status}</option>
{/each}
</select>
</fieldset>
<div class="flex justify-end mt-6">
<button class="btn btn-error" onclick={handleAddGift}>Dodaj prezent</button>
</div>
</Modal>
{/if}

View File

@@ -0,0 +1,55 @@
<script lang="ts">
import { formatCurrency } from '$lib/helpers/formatCurrency';
import { deletePerson, type getPeople } from '$lib/remotes/db.remote';
import { Trash } from 'lucide-svelte';
import { slide } from 'svelte/transition';
import GiftCard from './GiftCard.svelte';
import GiftModal from './GiftModal.svelte';
type Props = {
person: Awaited<ReturnType<typeof getPeople>>[number];
};
let { person }: Props = $props();
let gifts = $derived(person.gifts);
let showGifts = $state(false);
</script>
<div class="border-gray-200 bg-white rounded-lg p-4">
<div
class="flex justify-between items-center cursor-pointer"
onclick={() => (showGifts = !showGifts)}
>
<div class="flex items-center gap-2">
<div
class="h-10 w-10 rounded-full bg-red-100 flex items-center justify-center text-red-700 font-bold"
>
{person.name.charAt(0)}
</div>
<div>
<h3>{person.name}</h3>
<div class="text-xs text-gray-500">
{person.gifts.length} prezentów • {person.gifts.filter((g) => g.status === 'BOUGHT')
.length}/{person.gifts.length} kupionych
</div>
</div>
</div>
<div class="text-right flex items-center gap-2">
<span class="font-mono font-medium text-green-700">
{formatCurrency(person.gifts.reduce((sum, gift) => sum + (gift.price ?? 0), 0))}
</span>
<Trash class="text-red-500 cursor-pointer size-3" onclick={() => deletePerson(person.id)} />
</div>
</div>
{#if showGifts}
<div transition:slide={{ duration: 200 }}>
{#each gifts as gift (gift.id)}
<GiftCard {gift} />
{/each}
<GiftModal personId={person.id} personName={person.name} />
</div>
{/if}
</div>

View File

@@ -0,0 +1,44 @@
<script>
import { addPerson } from '$lib/remotes/db.remote';
import Modal from '../atoms/Modal.svelte';
let { year } = $props();
let isOpen = $state(false);
let name = $state('');
const open = () => {
isOpen = true;
};
const close = () => {
isOpen = false;
};
const handleAddYear = () => {
addPerson({ year, name }).then(close);
};
</script>
<button class="btn btn-error" onclick={open}>Dodaj osobę</button>
{#if isOpen}
<Modal {isOpen} heading="Dodaj nową osobę" onClose={close}>
<fieldset class="fieldset">
<legend class="fieldset-legend text-black/70">Nazwa</legend>
<input
type="text"
bind:value={name}
placeholder="Nazwa osoby"
class={[
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive'
]}
/>
</fieldset>
<div class="flex justify-end mt-6">
<button class="btn btn-error" onclick={handleAddYear}>Dodaj {name}</button>
</div>
</Modal>
{/if}

View File

@@ -0,0 +1,80 @@
<script lang="ts">
import { formatCurrency } from '$lib/helpers/formatCurrency';
import { getPeople, getYear } from '$lib/remotes/db.remote';
import { Calendar, GiftIcon, UserPlus } from 'lucide-svelte';
import PersonCard from '../molecules/PersonCard.svelte';
import PersonModal from '../molecules/PersonModal.svelte';
let { year } = $props();
const query = getYear(year);
let data = $derived(query.current ?? (await getYear(year))!);
const peopleQuery = getPeople(year);
let people = $derived(peopleQuery.current ?? (await getPeople(year)));
let totalSpent = $derived(
people.reduce(
(sum, person) => sum + person.gifts.reduce((sum, gift) => sum + (gift.price ?? 0), 0),
0
)
);
let totalBudget = $derived(data.budget);
let remainingBudget = $derived(totalBudget - totalSpent);
let progress = $derived((totalSpent / totalBudget) * 100);
</script>
<section class="my-block relative">
<!-- Header -->
<div class="bg-linear-to-r from-green-800 to-green-700 text-white pb-8 p-5 rounded-t-xl">
<div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div>
<h2 class="text-2xl flex items-center">
<Calendar class="w-6 h-6 mr-2 opacity-80" />
Podsumowanie {year}
</h2>
<p class="text-green-100 mt-1">
Prezenty dla {data?.people?.length || 0} osób
</p>
</div>
<div
class="text-right w-full md:w-auto bg-green-900/30 p-3 rounded-lg backdrop-blur-sm border border-green-500/30"
>
<div class="text-sm text-green-100">Łączny budżet</div>
<div class="text-3xl font-bold font-mono text-yellow-300">
{formatCurrency(totalBudget)}
</div>
</div>
</div>
<div class="mt-6">
<div class="flex justify-between text-xs mb-2 text-green-100 font-medium">
<span>Wydane: {formatCurrency(totalSpent)}</span>
<span>Zostało: {formatCurrency(remainingBudget)}</span>
</div>
<progress value={progress} max={100} class="progress progress-neutral" />
</div>
</div>
<!-- Body -->
<div class="bg-neutral-200 text-black pb-8 p-5 rounded-b-xl">
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-semibold text-gray-800 flex items-center">
<UserPlus class="w-5 h-5 mr-2 text-red-600" />
Osoby
</h2>
<PersonModal {year} />
</div>
<div class="space-y-4">
{#each people as person (person.id)}
<PersonCard {person} />
{:else}
<div class="text-center py-12 border-2 border-dashed border-gray-200 rounded-xl">
<GiftIcon class="w-12 h-12 text-gray-300 mx-auto mb-3" />
<h3 class="text-lg font-medium text-gray-500">Nie ma jeszcze żadnej osoby na liście</h3>
<p class="text-gray-400 text-sm">Dodaj osoby, aby móc śledzić ich prezenty!</p>
</div>
{/each}
</div>
</div>
</section>

View File

@@ -0,0 +1,6 @@
export const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('pl-PL', {
style: 'currency',
currency: 'PLN'
}).format(amount);
};

View File

@@ -2,8 +2,14 @@ import { command, query } from '$app/server';
import { DB } from '$lib/server/db'; import { DB } from '$lib/server/db';
import * as v from 'valibot'; import * as v from 'valibot';
export const getYear = query(v.number(), async (year) => {
return await DB.GET.year({
year: year
});
});
export const getYears = query(async () => { export const getYears = query(async () => {
return await DB.GET.years(); return await DB.GET.years({});
}); });
export const addYear = command(v.number(), async (year) => { export const addYear = command(v.number(), async (year) => {
@@ -16,8 +22,56 @@ export const addYear = command(v.number(), async (year) => {
export const deleteYear = command(v.number(), async (year) => { export const deleteYear = command(v.number(), async (year) => {
await DB.DELETE.year({ await DB.DELETE.year({
year: year year
}); });
getYears().refresh(); getYears().refresh();
}); });
export const addPerson = command(v.any(), async (data) => {
await DB.CREATE.person(data);
getPeople(data.yearId).refresh();
});
export const getPeople = query(v.number(), async (year) => {
return await DB.GET.people({
yearId: year
});
});
export const deletePerson = command(v.number(), async (id) => {
const person = await DB.DELETE.person({ id });
const year = await DB.GET.year({ year: person!.yearId });
getPeople(year!.year).refresh();
});
export const addGift = command(v.any(), async (data) => {
await DB.CREATE.gift({
...data,
person: {
connect: {
id: data.personId
}
}
});
const person = await DB.GET.person({ id: data.personId });
getPeople(person!.yearId).refresh();
});
export const updateGift = command(v.any(), async (data) => {
const res = await DB.UPDATE.gift({ id: data.id }, data);
const person = await DB.GET.person({ id: res.personId });
getPeople(person!.yearId).refresh();
});
export const deleteGift = command(v.number(), async (id) => {
const gift = await DB.DELETE.gift({ id });
const person = await DB.GET.person({ id: gift.personId });
getPeople(person!.yearId).refresh();
});

View File

@@ -11,11 +11,16 @@ const db = new PrismaClient({ adapter });
const GET = { const GET = {
year: async (where: Prisma.YearWhereUniqueInput) => { year: async (where: Prisma.YearWhereUniqueInput) => {
return await db.year.findUnique({ return await db.year.findUnique({
where where,
include: {
people: true
}
}); });
}, },
years: async () => { years: async (where: Prisma.YearWhereInput) => {
return await db.year.findMany(); return await db.year.findMany({
where
});
}, },
person: async (where: Prisma.PersonWhereUniqueInput) => { person: async (where: Prisma.PersonWhereUniqueInput) => {
@@ -23,9 +28,12 @@ const GET = {
where where
}); });
}, },
people: async (where: Prisma.PersonWhereUniqueInput) => { people: async (where: Prisma.PersonWhereInput) => {
return await db.person.findMany({ return await db.person.findMany({
where where,
include: {
gifts: true
}
}); });
}, },

View File

@@ -11,8 +11,9 @@
<link rel="icon" href={favicon} /> <link rel="icon" href={favicon} />
</svelte:head> </svelte:head>
<main class="min-h-screen bg-slate-50 relative font-sans selection:bg-red-100"> <main
<div class="fixed inset-0 bg-linear-to-b from-red-950 via-red-900 to-green-900 z-0"></div> class="min-h-screen bg-slate-50 relative font-sans selection:bg-red-100 bg-linear-to-b from-red-950 via-red-900 to-green-900"
>
<div class="container"> <div class="container">
<Header /> <Header />
<YearSelection /> <YearSelection />

View File

@@ -1,2 +1,8 @@
<h1>Welcome to SvelteKit</h1> <script>
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p> import { page } from '$app/state';
import YearDashboard from '$lib/components/organisms/YearDashboard.svelte';
const year = page.params.year ?? new Date().getFullYear();
</script>
<YearDashboard {year} />

View File

@@ -12,6 +12,6 @@
} }
.container { .container {
@apply max-w-7xl mx-auto; @apply max-w-4xl mx-auto;
padding-inline: 15px; padding-inline: 15px;
} }

View File

@@ -20,7 +20,7 @@ const config = {
compilerOptions: { compilerOptions: {
warningFilter: (warning) => { warningFilter: (warning) => {
return !warning.message.startsWith('a11y_'); return warning.message.startsWith('a11y_');
}, },
experimental: { experimental: {
async: true async: true