Выбор нескольких папок для желания и фильтр исполненных #20

Merged
agent merged 2 commits from feature/wish-multiple-folders into main 2026-11-19 19:55:26 +00:00
14 changed files with 171 additions and 62 deletions

No files matched your search

+7 -5
View File
@@ -12,7 +12,7 @@ A small, private wishlist app for two users. The signed-in dashboard shows both
## Features
- Two fixed accounts (credentials in env), password stored only as a **bcrypt hash**.
- Either user can create a shared folder with an optional description and emoji or image cover, and add their own wishes to any shared folder. Each wish also appears in its author's list.
- Either user can create a shared folder with an optional description and emoji or image cover. The author can select several shared folders and their own folder when creating or editing a wish. Active and fulfilled wishes always appear in All. The dashboard can hide fulfilled wishes across these views.
- Wish entity: title, price, currency, link, comment, image (auto-fetched from link or uploaded).
- Statuses: **Active → Archive / Fulfilled → Trash** (kept for 30 days, then permanently removed by a daily cron job).
- Restore from archive or trash. Duplicate from fulfilled into a new active wish.
@@ -60,7 +60,7 @@ utils/ errors, bcrypt helpers, version helper
See `apps/backend/prisma/schema.prisma`. Tables:
- `User` — `id`, `username`, `slug`, `displayName`, `bio`, `avatarUrl`. **No password hash.**
- `Wish` — `userId`, optional `folderId`, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `Wish` — `userId`, optional `folderId` and additional folder links, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `WishFolder` — shared folder metadata and its creator.
- `GuestView` — `(guestId, wishId)` pairs for "already seen" tracking.
@@ -160,11 +160,11 @@ On first start, the backend:
### Production release
Follow the [controlled deployment runbook in infra-home](https://git.vakanaut.ru/admin/infra-home/src/branch/main/docs/runbooks/deployment.md). Build the frontend and backend images from the same merged revision and record both image digests. Release the pair together because the 0.4.0 home page uses the new `/api/dashboard` endpoint.
Follow the [controlled deployment runbook in infra-home](https://git.vakanaut.ru/admin/infra-home/src/branch/main/docs/runbooks/deployment.md). Build the frontend and backend images from the same merged revision and record both image digests. Release the pair together so the frontend can read and save multi-folder assignments.
Before upgrading an existing deployment, back up PostgreSQL and the uploads volume. Verify that the backup can be restored in an isolated environment. After deployment, check `/api/health`, `/api/version` and the signed-in dashboard. Confirm that an existing wish is still visible and a new wish in a shared folder also appears in the author's folder.
If a rollback is needed, restore the previous frontend and backend images together. For a pre-0.4.0 backend image, override the command with `node dist/src/index.js` (from `/app/apps/backend`). The previous image's default startup runs `prisma db push --accept-data-loss`, which can remove the shared folder table and wish-to-folder links.
If a rollback is needed, restore the previous frontend and backend images together. Start a pre-0.5.0 backend with `node dist/src/index.js` (from `/app/apps/backend`) to preserve the new schema. Version 0.4.0 shows the first shared folder while it is running. Backend images older than 0.4.0 run `prisma db push --accept-data-loss` by default, which can remove the shared folder data.
### Development schema migrations
@@ -234,6 +234,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
| POST | `/api/public/:slug/views` | — | Body `{ wishIds: [] }`. Marks as seen. |
| GET | `/api/health`, `/api/version` | — | Meta. |
For create and update, `folderIds` accepts the selected shared folder IDs. An empty array removes all shared assignments. When both folder ID keys are omitted from an update, assignments are preserved. Version 0.4.0 clients can still update the primary folder with `folderId`. `showInAuthorFolder` is true for existing wishes and by default for new wishes. The author can set it to false to hide the wish from their own folder.
---
## Versioning
@@ -241,7 +243,7 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
Each package has its own version (`apps/backend/package.json` and `apps/frontend/package.json`). The app footer shows both:
```
frontend v0.4.0 · backend v0.4.0
frontend v0.5.0 · backend v0.5.0
```
Bump them per semver on each change:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/backend",
"version": "0.4.0",
"version": "0.5.0",
"private": true,
"type": "module",
"main": "dist/index.js",
+3
View File
@@ -41,6 +41,7 @@ model WishFolder {
creator User @relation(fields: [creatorId], references: [id])
createdAt DateTime @default(now())
wishes Wish[]
additionalWishes Wish[] @relation("AdditionalWishFolders")
}
enum WishStatus {
@@ -76,6 +77,8 @@ model Wish {
sourceWishId String?
folderId String?
folder WishFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
additionalFolders WishFolder[] @relation("AdditionalWishFolders")
showInAuthorFolder Boolean @default(true)
views GuestView[]
@@ -31,7 +31,7 @@ export default async function publicRoutes(app: FastifyInstance) {
})
: [];
const seenSet = new Set(seen.map((s) => s.wishId));
return wishes.map(({ folderId: _folderId, ...w }) => ({
return wishes.map(({ folderId: _folderId, showInAuthorFolder: _showInAuthorFolder, ...w }) => ({
...w,
isNewForGuest: w.status === 'ACTIVE' && !seenSet.has(w.id),
}));
@@ -5,6 +5,7 @@ import { usersRegistry } from '../../auth/users.registry.js';
import { MAX_UPLOAD_BYTES } from '../../plugins/multipart.js';
import { UnauthorizedError, ValidationError } from '../../utils/errors.js';
import { deleteLocalImageIfAny, saveUploadedImage } from '../images/storage.service.js';
import { includeWishFolders, withFolderIds } from './wishes.service.js';
const folderFields = ['name', 'description', 'emoji'];
@@ -28,6 +29,7 @@ export default async function dashboardRoutes(app: FastifyInstance) {
app.prisma.wish.findMany({
where: { userId: { in: authorIds }, status: { in: ['ACTIVE', 'COMPLETED'] } },
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }, { id: 'asc' }],
include: includeWishFolders,
}),
]);
const newSince = Date.now() - NEW_BADGE_DAYS * 24 * 60 * 60 * 1000;
@@ -36,7 +38,7 @@ export default async function dashboardRoutes(app: FastifyInstance) {
authors: users.sort((a, b) => authorIds.indexOf(a.id) - authorIds.indexOf(b.id)),
folders,
wishes: wishes.map((wish) => ({
...wish,
...withFolderIds(wish),
isNewForOwner: wish.status === 'ACTIVE' && wish.createdAt.getTime() > newSince,
})),
};
@@ -15,55 +15,88 @@ const statusMap: Record<Status, WishStatus> = {
deleted: 'DELETED',
};
export const includeWishFolders = {
additionalFolders: { select: { id: true }, orderBy: { id: 'asc' as const } },
};
export function withFolderIds({ additionalFolders, ...wish }: Wish & {
additionalFolders: { id: string }[];
}) {
const folderIds = new Set(wish.folderId ? [wish.folderId] : []);
for (const { id } of additionalFolders) folderIds.add(id);
return { ...wish, folderIds: [...folderIds] };
}
export class WishesService {
constructor(private readonly prisma: PrismaClient) {}
list(userId: string, status: Status): Promise<Wish[]> {
return this.prisma.wish.findMany({
async list(userId: string, status: Status) {
const wishes = await this.prisma.wish.findMany({
where: { userId, status: statusMap[status] },
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }],
include: includeWishFolders,
});
return wishes.map(withFolderIds);
}
async getOwned(userId: string, id: string): Promise<Wish> {
const wish = await this.prisma.wish.findUnique({ where: { id } });
async getOwned(userId: string, id: string) {
const wish = await this.prisma.wish.findUnique({ where: { id }, include: includeWishFolders });
if (!wish) throw new NotFoundError('Wish');
if (wish.userId !== userId) throw new ForbiddenError();
return wish;
return withFolderIds(wish);
}
private async checkFolder(folderId: string | null | undefined): Promise<void> {
if (folderId && !(await this.prisma.wishFolder.findUnique({ where: { id: folderId } }))) {
private async checkFolders(folderIds: string[]): Promise<void> {
if (folderIds.length && await this.prisma.wishFolder.count({
where: { id: { in: folderIds } },
}) !== folderIds.length) {
throw new NotFoundError('Folder');
}
}
async create(userId: string, input: CreateWishInput): Promise<Wish> {
await this.checkFolder(input.folderId);
return this.prisma.wish.create({
async create(userId: string, input: CreateWishInput) {
const folderIds = [...new Set(input.folderIds ?? (input.folderId ? [input.folderId] : []))];
await this.checkFolders(folderIds);
const [folderId, ...additional] = folderIds;
const wish = await this.prisma.wish.create({
data: {
userId,
folderId: input.folderId,
folderId,
additionalFolders: { connect: additional.map((id) => ({ id })) },
title: input.title,
showInAuthorFolder: input.showInAuthorFolder,
price: input.price ?? null,
currency: input.currency ?? 'RUB',
url: input.url ?? null,
comment: input.comment ?? null,
},
include: includeWishFolders,
});
return withFolderIds(wish);
}
async update(userId: string, id: string, input: UpdateWishInput): Promise<Wish> {
async update(userId: string, id: string, input: UpdateWishInput) {
await this.getOwned(userId, id);
await this.checkFolder(input.folderId);
const data: Record<string, unknown> = {};
if (input.folderId !== undefined) data.folderId = input.folderId;
if (input.folderIds !== undefined) {
const folderIds = [...new Set(input.folderIds)];
await this.checkFolders(folderIds);
const [folderId, ...additional] = folderIds;
data.folderId = folderId ?? null;
data.additionalFolders = { set: additional.map((id) => ({ id })) };
} else if (input.folderId !== undefined) {
await this.checkFolders(input.folderId ? [input.folderId] : []);
data.folderId = input.folderId;
}
if (input.showInAuthorFolder !== undefined) data.showInAuthorFolder = input.showInAuthorFolder;
if (input.title !== undefined) data.title = input.title;
if (input.price !== undefined) data.price = input.price ?? null;
if (input.currency !== undefined) data.currency = input.currency ?? 'RUB';
if (input.url !== undefined) data.url = input.url ?? null;
if (input.comment !== undefined) data.comment = input.comment ?? null;
return this.prisma.wish.update({ where: { id }, data });
return withFolderIds(await this.prisma.wish.update({
where: { id }, data, include: includeWishFolders,
}));
}
async archive(userId: string, id: string): Promise<Wish> {
@@ -108,9 +141,9 @@ export class WishesService {
});
}
async duplicate(userId: string, id: string): Promise<Wish> {
async duplicate(userId: string, id: string) {
const source = await this.getOwned(userId, id);
return this.prisma.wish.create({
const wish = await this.prisma.wish.create({
data: {
userId,
title: source.title,
@@ -121,8 +154,14 @@ export class WishesService {
imageUrl: source.imageSource === 'UPLOADED' ? null : source.imageUrl,
imageSource: source.imageSource === 'UPLOADED' ? 'DEFAULT' : source.imageSource,
sourceWishId: source.id,
showInAuthorFolder: source.showInAuthorFolder,
folderId: source.folderId,
additionalFolders: {
connect: source.folderIds.filter((id) => id !== source.folderId).map((id) => ({ id })),
},
},
include: includeWishFolders,
});
return withFolderIds(wish);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/frontend",
"version": "0.4.0",
"version": "0.5.0",
"private": true,
"type": "module",
"scripts": {
@@ -57,8 +57,10 @@ function WishCardInner({
const actions: WishCardAction[] = [];
if (view === 'owner') {
if (onEdit && (wish.status === 'ACTIVE' || completed)) {
actions.push({ key: 'edit', icon: Pencil, label: t('wish.action.edit'), onClick: onEdit });
}
if (wish.status === 'ACTIVE') {
if (onEdit) actions.push({ key: 'edit', icon: Pencil, label: t('wish.action.edit'), onClick: onEdit });
if (onComplete)
actions.push({
key: 'complete',
@@ -1,5 +1,5 @@
import { useRef } from 'react';
import { useForm } from 'react-hook-form';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createWishSchema, type CreateWishInput, type Wish, type WishFolder } from '@family-wishlist/shared';
import { Button } from '../ui/Button';
@@ -21,11 +21,12 @@ interface Props {
mode: 'create' | 'edit';
initial?: Wish;
folders?: WishFolder[];
authorName: string;
defaultFolderId?: string;
onClose: () => void;
}
export function WishForm({ mode, initial, folders, defaultFolderId, onClose }: Props) {
export function WishForm({ mode, initial, folders, authorName, defaultFolderId, onClose }: Props) {
const { t } = useI18n();
const create = useCreateWish();
const update = useUpdateWish();
@@ -37,6 +38,7 @@ export function WishForm({ mode, initial, folders, defaultFolderId, onClose }: P
const {
register,
control,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<CreateWishInput>({
@@ -47,12 +49,14 @@ export function WishForm({ mode, initial, folders, defaultFolderId, onClose }: P
currency: initial?.currency ?? 'RUB',
url: initial?.url ?? '',
comment: initial?.comment ?? '',
folderId: initial?.folderId ?? defaultFolderId ?? null,
folderIds: initial?.folderIds ??
(initial?.folderId ? [initial.folderId] : defaultFolderId ? [defaultFolderId] : []),
showInAuthorFolder: initial?.showInAuthorFolder ?? true,
},
});
const submit = handleSubmit(async (values) => {
const input = { ...values, folderId: folders ? values.folderId : undefined };
const input = { ...values, folderIds: folders ? values.folderIds : undefined };
try {
if (mode === 'create') {
await create.mutateAsync(input);
@@ -99,21 +103,45 @@ export function WishForm({ mode, initial, folders, defaultFolderId, onClose }: P
)}
</div>
{folders && folders.length > 0 && (
<div className="field">
<Label htmlFor="wish-folder">{t('folders.field')}</Label>
<select
id="wish-folder"
className="field__select"
{...register('folderId', { setValueAs: (value) => value || null })}
>
<option value="">{t('folders.noFolder')}</option>
{folders.map((folder) => (
<option key={folder.id} value={folder.id}>{folder.name}</option>
))}
</select>
<fieldset aria-describedby="wish-folders-hint" className="field min-w-0">
<legend className="field__label">{t('folders.field')}</legend>
<p id="wish-folders-hint" className="text-sm text-ink">
{t('folders.alwaysVisible')}
</p>
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
<label className="wish-checkbox">
<input type="checkbox" {...register('showInAuthorFolder')} />
<span>{authorName}</span>
</label>
{folders && folders.length > 0 && (
<Controller
name="folderIds"
control={control}
render={({ field }) => {
const ids = field.value ?? [];
return (
<>
{folders.map(({ id, name }) => (
<label key={id} className="wish-checkbox">
<input
type="checkbox"
name={field.name}
checked={ids.includes(id)}
onBlur={field.onBlur}
onChange={(event) => field.onChange(event.target.checked
? [...ids, id]
: ids.filter((selectedId) => selectedId !== id))}
/>
<span>{name}</span>
</label>
))}
</>
);
}}
/>
)}
</div>
)}
</fieldset>
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
<div className="field">
+8 -4
View File
@@ -50,6 +50,8 @@ const translations = {
'dashboard.emptyTitle': 'Желаний пока нет',
'dashboard.loadError': 'Не удалось загрузить список желаний.',
'dashboard.retry': 'Повторить',
'dashboard.hideCompleted': 'Скрыть исполненные',
'dashboard.completedHidden': 'Исполненные желания скрыты',
'folders.title': 'Папки желаний',
'folders.all': 'Все',
'folders.create': 'Создать папку',
@@ -59,8 +61,8 @@ const translations = {
'folders.noCover': 'Без обложки',
'folders.emoji': 'Эмодзи',
'folders.image': 'Изображение',
'folders.field': 'Папка',
'folders.noFolder': 'Без общей папки',
'folders.field': 'В каких папках видно желание',
'folders.alwaysVisible': 'Желание всегда видно во «Все».',
'folders.invalidDetails': 'Проверьте название и описание папки.',
'folders.invalidEmoji': 'Введите эмодзи для обложки.',
'folders.invalidImage': 'Выберите файл JPEG, PNG, WebP или GIF размером до 8 МБ.',
@@ -182,6 +184,8 @@ const translations = {
'dashboard.emptyTitle': 'No wishes yet',
'dashboard.loadError': "Couldn't load wishes.",
'dashboard.retry': 'Try again',
'dashboard.hideCompleted': 'Hide fulfilled wishes',
'dashboard.completedHidden': 'Fulfilled wishes are hidden',
'folders.title': 'Wish folders',
'folders.all': 'All',
'folders.create': 'Create folder',
@@ -191,8 +195,8 @@ const translations = {
'folders.noCover': 'No cover',
'folders.emoji': 'Emoji',
'folders.image': 'Image',
'folders.field': 'Folder',
'folders.noFolder': 'No shared folder',
'folders.field': 'Show wish in folders',
'folders.alwaysVisible': 'The wish always appears in “All”.',
'folders.invalidDetails': 'Check the folder name and description.',
'folders.invalidEmoji': 'Enter an emoji for the cover.',
'folders.invalidImage': 'Choose a JPEG, PNG, WebP, or GIF file up to 8 MB.',
+30 -12
View File
@@ -46,6 +46,7 @@ export function DashboardPage() {
const { t } = useI18n();
const { data, isPending, isError, refetch } = useWishDashboard();
const [selection, setSelection] = useState<Selection>({ type: 'all' });
const [hideCompleted, setHideCompleted] = useState(false);
const [creatingFolder, setCreatingFolder] = useState(false);
const [creatingWish, setCreatingWish] = useState(false);
const [editing, setEditing] = useState<Wish | null>(null);
@@ -62,11 +63,14 @@ export function DashboardPage() {
const selectedFolder = selection.type === 'folder'
? data?.folders.find(({ id }) => id === selection.id)
: undefined;
const wishes = data?.wishes.filter((wish) =>
selectedAuthor ? wish.userId === selectedAuthor.id
: selectedFolder ? wish.folderId === selectedFolder.id
const folderWishes = data?.wishes.filter((wish) =>
selectedAuthor ? wish.userId === selectedAuthor.id && wish.showInAuthorFolder !== false
: selectedFolder ? (wish.folderIds?.includes(selectedFolder.id) ?? wish.folderId === selectedFolder.id)
: true,
);
const wishes = hideCompleted
? folderWishes?.filter(({ status }) => status !== 'COMPLETED')
: folderWishes;
const canAddWish = !selectedAuthor || selectedAuthor.id === user?.id;
const sectionTitle = selectedAuthor?.displayName ?? selectedFolder?.name ?? t('folders.all');
@@ -175,17 +179,29 @@ export function DashboardPage() {
</p>
)}
</div>
{canAddWish && (
<Button onClick={() => setCreatingWish(true)}>
<Plus className="h-4 w-4" aria-hidden />
{t('dashboard.addWish')}
</Button>
)}
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<label className="wish-checkbox">
<input
type="checkbox"
checked={hideCompleted}
onChange={(event) => setHideCompleted(event.target.checked)}
/>
<span>{t('dashboard.hideCompleted')}</span>
</label>
{canAddWish && (
<Button onClick={() => setCreatingWish(true)}>
<Plus className="h-4 w-4" aria-hidden />
{t('dashboard.addWish')}
</Button>
)}
</div>
</div>
{wishes.length === 0 ? (
<div className="empty-state">
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
<h3 className="empty-state__title">{t('dashboard.emptyTitle')}</h3>
<h3 className="empty-state__title">
{t(folderWishes?.length ? 'dashboard.completedHidden' : 'dashboard.emptyTitle')}
</h3>
</div>
) : (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
@@ -215,17 +231,19 @@ export function DashboardPage() {
</section>
)}
{creatingWish && (
{creatingWish && user && (
<WishForm
mode="create"
authorName={user.displayName}
folders={data?.folders}
defaultFolderId={selectedFolder?.id}
onClose={() => setCreatingWish(false)}
/>
)}
{editing && (
{editing && user && (
<WishForm
mode="edit"
authorName={user.displayName}
initial={editing}
folders={data?.folders}
onClose={() => setEditing(null)}
+7
View File
@@ -152,6 +152,13 @@
.wish-folders__form {
@apply grid min-w-0 max-w-xl gap-4 rounded-md border border-border bg-surface p-4;
}
.wish-checkbox {
@apply inline-flex min-h-9 min-w-0 cursor-pointer items-center gap-2 text-sm text-ink;
overflow-wrap: anywhere;
}
.wish-checkbox input {
@apply h-4 w-4 shrink-0 accent-primary;
}
.public-profile {
@apply flex min-h-screen flex-col;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/shared",
"version": "0.4.0",
"version": "0.5.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
+4
View File
@@ -23,6 +23,8 @@ export const wishSchema = z.object({
deletedAt: z.string().nullable(),
sourceWishId: z.string().nullable(),
folderId: z.string().nullable().optional(),
folderIds: z.array(z.string()).optional(),
showInAuthorFolder: z.boolean().optional(),
isNewForGuest: z.boolean().optional(),
});
@@ -30,6 +32,8 @@ export type Wish = z.infer<typeof wishSchema>;
export const createWishSchema = z.object({
folderId: z.string().cuid().nullable().optional(),
folderIds: z.array(z.string().cuid()).optional(),
showInAuthorFolder: z.boolean().optional(),
title: z.string().trim().min(1).max(200),
price: z
.union([