Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3c05c606a | ||
|
|
ebf8e3b5d4 | ||
|
|
aeedb6c753 | ||
|
|
d0fe2906c7 | ||
|
|
e9b2f76ee3 | ||
|
|
26cf978e3c | ||
|
|
dbffefc26f | ||
|
|
5ab8ef3ba8 | ||
|
|
235b40b326 | ||
|
|
13b3b1a257 | ||
|
|
fbf1d2d02f | ||
|
|
0ada42017f |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# Family Wishlist
|
||||
|
||||
A small, private wishlist app for two users. Each user has their own profile, slug, and independent wishlist. Guests see a public page at `/u/<slug>` and can view active and fulfilled wishes.
|
||||
A small, private wishlist app for two users. The signed-in dashboard shows both users' active and fulfilled wishes, with filters for each author and shared folders. Each user also has a public profile at `/u/<slug>` with their own active and fulfilled wishes.
|
||||
|
||||
- **Backend**: Node.js 20, Fastify 4, Prisma 5, PostgreSQL 16
|
||||
- **Frontend**: React 18, Vite 5, Tailwind CSS, TanStack Query, React Hook Form + Zod
|
||||
@@ -12,6 +12,7 @@ A small, private wishlist app for two users. Each user has their own profile, sl
|
||||
## 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. 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.
|
||||
@@ -59,7 +60,8 @@ 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`, `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.
|
||||
|
||||
### Password storage
|
||||
@@ -156,6 +158,16 @@ On first start, the backend:
|
||||
3. Starts Fastify on port 3000.
|
||||
4. Registers the daily trash-purge cron (runs at 03:17 UTC, also once on startup).
|
||||
|
||||
### 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 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. 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
|
||||
|
||||
> For a stricter migration workflow, switch to `prisma migrate dev` locally to produce
|
||||
> versioned migration files and change the Docker `CMD` to `prisma migrate deploy`.
|
||||
|
||||
@@ -203,6 +215,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
|
||||
| GET | `/api/auth/me` | owner | Current user. |
|
||||
| GET | `/api/profile` | owner | Own profile. |
|
||||
| PATCH | `/api/profile` | owner | Update slug/displayName/bio/avatar. |
|
||||
| GET | `/api/dashboard` | signed in | Shared folders, authors, and active and fulfilled wishes from both accounts. |
|
||||
| POST | `/api/folders` | signed in | Create a shared folder. Multipart fields: `name`, optional `description`, and optional `emoji` or `cover` file. |
|
||||
| GET | `/api/wishes?status=active\|archived\|completed\|deleted` | owner | List own wishes. |
|
||||
| POST | `/api/wishes` | owner | Create. |
|
||||
| GET | `/api/wishes/:id` | owner | Get own wish. |
|
||||
@@ -220,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
|
||||
@@ -227,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.1.0 · backend v0.1.0
|
||||
frontend v0.5.0 · backend v0.5.0
|
||||
```
|
||||
|
||||
Bump them per semver on each change:
|
||||
@@ -240,7 +256,7 @@ Bump them per semver on each change:
|
||||
## Security notes
|
||||
|
||||
- Cookies are `httpOnly`, `SameSite=Lax`, `Secure` in production.
|
||||
- All auth-scoped routes re-check ownership in the service layer (`userId` vs `req.user.id`).
|
||||
- Wish mutations check ownership in the service layer (`userId` vs `req.user.id`). The shared dashboard requires a signed-in account.
|
||||
- `/api/auth/login` is rate-limited; username enumeration is mitigated by a constant-time dummy compare.
|
||||
- Image fetcher has a 10s timeout, a 5 MB cap, and accepts only `image/jpeg|png|webp|gif`.
|
||||
- Multipart upload cap: 8 MB, one file per request.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@family-wishlist/backend",
|
||||
"version": "0.1.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -28,6 +28,20 @@ model User {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
wishes Wish[]
|
||||
folders WishFolder[]
|
||||
}
|
||||
|
||||
model WishFolder {
|
||||
id String @id @default(cuid())
|
||||
name String
|
||||
description String?
|
||||
emoji String?
|
||||
imageUrl String?
|
||||
creatorId String
|
||||
creator User @relation(fields: [creatorId], references: [id])
|
||||
createdAt DateTime @default(now())
|
||||
wishes Wish[]
|
||||
additionalWishes Wish[] @relation("AdditionalWishFolders")
|
||||
}
|
||||
|
||||
enum WishStatus {
|
||||
@@ -61,12 +75,17 @@ model Wish {
|
||||
completedAt DateTime?
|
||||
deletedAt DateTime?
|
||||
sourceWishId String?
|
||||
folderId String?
|
||||
folder WishFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
|
||||
additionalFolders WishFolder[] @relation("AdditionalWishFolders")
|
||||
showInAuthorFolder Boolean @default(true)
|
||||
|
||||
views GuestView[]
|
||||
|
||||
@@index([userId, status])
|
||||
@@index([deletedAt])
|
||||
@@index([createdAt])
|
||||
@@index([folderId])
|
||||
}
|
||||
|
||||
model GuestView {
|
||||
|
||||
@@ -16,6 +16,7 @@ import multipartPlugin from './plugins/multipart.js';
|
||||
import authRoutes from './modules/auth/auth.routes.js';
|
||||
import profileRoutes from './modules/profile/profile.routes.js';
|
||||
import wishesRoutes from './modules/wishes/wishes.routes.js';
|
||||
import dashboardRoutes from './modules/wishes/dashboard.routes.js';
|
||||
import imagesRoutes from './modules/images/images.routes.js';
|
||||
import publicRoutes from './modules/public/public.routes.js';
|
||||
import metaRoutes from './modules/meta/meta.routes.js';
|
||||
@@ -77,6 +78,7 @@ export async function buildApp(): Promise<FastifyInstance> {
|
||||
await app.register(authRoutes, { prefix: '/api/auth' });
|
||||
await app.register(profileRoutes, { prefix: '/api/profile' });
|
||||
await app.register(wishesRoutes, { prefix: '/api/wishes' });
|
||||
await app.register(dashboardRoutes, { prefix: '/api' });
|
||||
await app.register(imagesRoutes, { prefix: '/api/wishes' });
|
||||
await app.register(publicRoutes, { prefix: '/api/public' });
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ export default async function publicRoutes(app: FastifyInstance) {
|
||||
})
|
||||
: [];
|
||||
const seenSet = new Set(seen.map((s) => s.wishId));
|
||||
return wishes.map((w) => ({
|
||||
return wishes.map(({ folderId: _folderId, showInAuthorFolder: _showInAuthorFolder, ...w }) => ({
|
||||
...w,
|
||||
isNewForGuest: w.status === 'ACTIVE' && !seenSet.has(w.id),
|
||||
}));
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { createFolderSchema, NEW_BADGE_DAYS } from '@family-wishlist/shared';
|
||||
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'];
|
||||
|
||||
export default async function dashboardRoutes(app: FastifyInstance) {
|
||||
app.addHook('preHandler', async (request) => {
|
||||
await app.authenticate(request);
|
||||
if (!usersRegistry.findById(request.user.id)) throw new UnauthorizedError();
|
||||
});
|
||||
|
||||
app.get('/dashboard', async (_request, reply) => {
|
||||
const authorIds = usersRegistry.all().map((user) => user.id);
|
||||
const [users, folders, wishes] = await Promise.all([
|
||||
app.prisma.user.findMany({
|
||||
where: { id: { in: authorIds } },
|
||||
select: { id: true, displayName: true, avatarUrl: true },
|
||||
}),
|
||||
app.prisma.wishFolder.findMany({
|
||||
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
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;
|
||||
reply.header('Cache-Control', 'private, no-store');
|
||||
return {
|
||||
authors: users.sort((a, b) => authorIds.indexOf(a.id) - authorIds.indexOf(b.id)),
|
||||
folders,
|
||||
wishes: wishes.map((wish) => ({
|
||||
...withFolderIds(wish),
|
||||
isNewForOwner: wish.status === 'ACTIVE' && wish.createdAt.getTime() > newSince,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/folders', async (request, reply) => {
|
||||
if (!request.isMultipart()) throw new ValidationError('Expected form data');
|
||||
|
||||
const fields: Record<string, unknown> = {};
|
||||
let cover: { mime: string; buffer: Buffer } | undefined;
|
||||
try {
|
||||
for await (const part of request.parts({
|
||||
limits: { files: 1, fields: 3, fieldSize: 4096, fileSize: MAX_UPLOAD_BYTES },
|
||||
})) {
|
||||
if (part.type === 'file') {
|
||||
const buffer = await part.toBuffer();
|
||||
if (part.fieldname !== 'cover' || part.file.truncated || !buffer.length) {
|
||||
throw new ValidationError('Invalid cover');
|
||||
}
|
||||
cover = { mime: part.mimetype, buffer };
|
||||
} else if (folderFields.includes(part.fieldname) && !part.valueTruncated) {
|
||||
fields[part.fieldname] = part.value;
|
||||
} else {
|
||||
throw new ValidationError('Invalid folder field');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof app.multipartErrors.RequestFileTooLargeError) {
|
||||
throw new ValidationError('File too large');
|
||||
}
|
||||
if (error instanceof app.multipartErrors.FilesLimitError ||
|
||||
error instanceof app.multipartErrors.FieldsLimitError) {
|
||||
throw new ValidationError('Invalid folder form');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const input = createFolderSchema.parse(fields);
|
||||
if (input.emoji && cover) throw new ValidationError('Choose one cover type');
|
||||
const imageUrl = cover
|
||||
? (await saveUploadedImage(`folder-${randomUUID()}`, cover.mime, cover.buffer)).imageUrl
|
||||
: null;
|
||||
try {
|
||||
const folder = await app.prisma.wishFolder.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
description: input.description || null,
|
||||
emoji: input.emoji || null,
|
||||
imageUrl,
|
||||
creatorId: request.user.id,
|
||||
},
|
||||
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
|
||||
});
|
||||
reply.code(201);
|
||||
return folder;
|
||||
} catch (error) {
|
||||
await deleteLocalImageIfAny(imageUrl);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -15,45 +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);
|
||||
}
|
||||
|
||||
create(userId: string, input: CreateWishInput): Promise<Wish> {
|
||||
return this.prisma.wish.create({
|
||||
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) {
|
||||
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,
|
||||
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);
|
||||
const data: Record<string, unknown> = {};
|
||||
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> {
|
||||
@@ -98,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,
|
||||
@@ -111,7 +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,6 +1,6 @@
|
||||
{
|
||||
"name": "@family-wishlist/frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link, NavLink, useNavigate } from 'react-router-dom';
|
||||
import { Archive, CheckCircle2, Gift, LogOut, Sparkles, Trash2, UserCog, Users } from 'lucide-react';
|
||||
import { Archive, CheckCircle2, Gift, House, LogOut, Trash2, UserCog, Users } from 'lucide-react';
|
||||
import type { ComponentType } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Button } from '../ui/Button';
|
||||
@@ -18,7 +18,7 @@ interface FriendProfile {
|
||||
}
|
||||
|
||||
const links = [
|
||||
{ to: '/', label: 'header.active', icon: Sparkles, end: true },
|
||||
{ to: '/', label: 'header.home', icon: House, end: true },
|
||||
{ to: '/completed', label: 'header.fulfilled', icon: CheckCircle2 },
|
||||
{ to: '/archive', label: 'header.archive', icon: Archive },
|
||||
{ to: '/trash', label: 'header.trash', icon: Trash2 },
|
||||
@@ -58,62 +58,67 @@ export function Header() {
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<nav className="app-header__nav">
|
||||
{links.map((l) => (
|
||||
<NavLink
|
||||
key={l.to}
|
||||
to={l.to}
|
||||
end={l.end}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'app-header__nav-link',
|
||||
isActive && 'app-header__nav-link--active',
|
||||
)
|
||||
}
|
||||
>
|
||||
<l.icon className="h-4 w-4" />
|
||||
{t(l.label)}
|
||||
</NavLink>
|
||||
))}
|
||||
{friend.data && (
|
||||
<NavLink
|
||||
to={`/u/${friend.data.slug}`}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'app-header__nav-link',
|
||||
isActive && 'app-header__nav-link--active',
|
||||
)
|
||||
}
|
||||
>
|
||||
<Users className="h-4 w-4" />
|
||||
{t('header.friendWishes', { name: friend.data.displayName })}
|
||||
</NavLink>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="app-header__actions">
|
||||
<LanguageSwitcher />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="app-header__action"
|
||||
onClick={() => navigate('/settings')}
|
||||
title={t('header.profileSettings')}
|
||||
aria-label={t('header.profileSettings')}
|
||||
>
|
||||
<UserCog className="h-4 w-4" />
|
||||
{t('header.profile')}
|
||||
<span className="app-header__action-text">{t('header.profile')}</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="app-header__action"
|
||||
onClick={() => {
|
||||
void logout().then(() => navigate('/login'));
|
||||
}}
|
||||
title={t('header.logout')}
|
||||
aria-label={t('header.logout')}
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
{t('header.logout')}
|
||||
<span className="app-header__action-text">{t('header.logout')}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="app-header__nav">
|
||||
{links.map((l) => (
|
||||
<NavLink
|
||||
key={l.to}
|
||||
to={l.to}
|
||||
end={l.end}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'app-header__nav-link',
|
||||
isActive && 'app-header__nav-link--active',
|
||||
)
|
||||
}
|
||||
>
|
||||
<l.icon className="h-4 w-4" />
|
||||
{t(l.label)}
|
||||
</NavLink>
|
||||
))}
|
||||
{friend.data && (
|
||||
<NavLink
|
||||
to={`/u/${friend.data.slug}`}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'app-header__nav-link',
|
||||
isActive && 'app-header__nav-link--active',
|
||||
)
|
||||
}
|
||||
>
|
||||
<Users className="h-4 w-4" />
|
||||
{t('header.friendWishes', { name: friend.data.displayName })}
|
||||
</NavLink>
|
||||
)}
|
||||
</nav>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { createFolderSchema, type WishFolder } from '@family-wishlist/shared';
|
||||
import { FolderPlus } from 'lucide-react';
|
||||
import { useCreateFolder } from '@/features/wishes/wishes.hooks';
|
||||
import { useI18n } from '@/i18n/i18n';
|
||||
import { Button } from '../ui/Button';
|
||||
import { Input } from '../ui/Input';
|
||||
import { Label } from '../ui/Label';
|
||||
import { Textarea } from '../ui/Textarea';
|
||||
|
||||
const coverTypes = 'image/jpeg,image/png,image/webp,image/gif';
|
||||
|
||||
export function FolderForm({
|
||||
onCancel,
|
||||
onCreated,
|
||||
}: {
|
||||
onCancel: () => void;
|
||||
onCreated: (folder: WishFolder) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const create = useCreateFolder();
|
||||
const [coverType, setCoverType] = useState<'none' | 'emoji' | 'image'>('none');
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (create.isPending) return;
|
||||
const form = new FormData(event.currentTarget);
|
||||
const input = createFolderSchema.safeParse({
|
||||
name: form.get('name'),
|
||||
description: form.get('description'),
|
||||
emoji: form.get('emoji') ?? undefined,
|
||||
});
|
||||
const file = form.get('cover');
|
||||
const cover = file instanceof File && file.size > 0 ? file : null;
|
||||
|
||||
if (!input.success) {
|
||||
const errors = input.error.flatten().fieldErrors;
|
||||
setError(t(errors.emoji ? 'folders.invalidEmoji' : 'folders.invalidDetails'));
|
||||
return;
|
||||
}
|
||||
if (coverType === 'image' && (!cover || !coverTypes.split(',').includes(cover.type) ||
|
||||
cover.size > 8 * 1024 * 1024)) {
|
||||
setError(t('folders.invalidImage'));
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
try {
|
||||
onCreated(await create.mutateAsync({ input: input.data, cover }));
|
||||
} catch {
|
||||
setError(t('folders.saveError'));
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="wish-folders__form" onSubmit={submit} aria-busy={create.isPending}>
|
||||
<div className="field">
|
||||
<Label htmlFor="folder-name">{t('folders.name')}</Label>
|
||||
<Input id="folder-name" name="name" maxLength={80} autoFocus required />
|
||||
</div>
|
||||
<div className="field">
|
||||
<Label htmlFor="folder-description">{t('folders.description')}</Label>
|
||||
<Textarea id="folder-description" name="description" maxLength={500} rows={2} />
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="field">
|
||||
<Label htmlFor="folder-cover-type">{t('folders.cover')}</Label>
|
||||
<select
|
||||
id="folder-cover-type"
|
||||
className="field__select"
|
||||
value={coverType}
|
||||
onChange={(event) => {
|
||||
setCoverType(event.target.value as typeof coverType);
|
||||
setError(undefined);
|
||||
}}
|
||||
>
|
||||
<option value="none">{t('folders.noCover')}</option>
|
||||
<option value="emoji">{t('folders.emoji')}</option>
|
||||
<option value="image">{t('folders.image')}</option>
|
||||
</select>
|
||||
</div>
|
||||
{coverType === 'emoji' && (
|
||||
<div className="field">
|
||||
<Label htmlFor="folder-emoji">{t('folders.emoji')}</Label>
|
||||
<Input id="folder-emoji" name="emoji" placeholder="🎁" maxLength={32} required />
|
||||
</div>
|
||||
)}
|
||||
{coverType === 'image' && (
|
||||
<div className="field">
|
||||
<Label htmlFor="folder-cover-file">{t('folders.image')}</Label>
|
||||
<Input id="folder-cover-file" name="cover" type="file" accept={coverTypes} required />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{error && <p role="alert" className="field__error">{error}</p>}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="submit" disabled={create.isPending}>
|
||||
<FolderPlus className="h-4 w-4" aria-hidden />
|
||||
{t('folders.create')}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onCancel} disabled={create.isPending}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useRef } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { createWishSchema, type CreateWishInput, type Wish } from '@family-wishlist/shared';
|
||||
import { createWishSchema, type CreateWishInput, type Wish, type WishFolder } from '@family-wishlist/shared';
|
||||
import { Button } from '../ui/Button';
|
||||
import { Input } from '../ui/Input';
|
||||
import { Textarea } from '../ui/Textarea';
|
||||
@@ -18,13 +18,15 @@ import {
|
||||
import { translateValidation, useI18n } from '@/i18n/i18n';
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
mode: 'create' | 'edit';
|
||||
initial?: Wish;
|
||||
folders?: WishFolder[];
|
||||
authorName: string;
|
||||
defaultFolderId?: string;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function WishForm({ open, mode, initial, onClose }: Props) {
|
||||
export function WishForm({ mode, initial, folders, authorName, defaultFolderId, onClose }: Props) {
|
||||
const { t } = useI18n();
|
||||
const create = useCreateWish();
|
||||
const update = useUpdateWish();
|
||||
@@ -33,12 +35,11 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
|
||||
const resetImage = useResetWishImage();
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [pendingId, setPendingId] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<CreateWishInput>({
|
||||
resolver: zodResolver(createWishSchema),
|
||||
@@ -48,37 +49,31 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
|
||||
currency: initial?.currency ?? 'RUB',
|
||||
url: initial?.url ?? '',
|
||||
comment: initial?.comment ?? '',
|
||||
folderIds: initial?.folderIds ??
|
||||
(initial?.folderId ? [initial.folderId] : defaultFolderId ? [defaultFolderId] : []),
|
||||
showInAuthorFolder: initial?.showInAuthorFolder ?? true,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
reset({
|
||||
title: initial?.title ?? '',
|
||||
price: initial?.price ?? '',
|
||||
currency: initial?.currency ?? 'RUB',
|
||||
url: initial?.url ?? '',
|
||||
comment: initial?.comment ?? '',
|
||||
});
|
||||
setPendingId(initial?.id ?? null);
|
||||
}, [open, initial, reset]);
|
||||
|
||||
const submit = handleSubmit(async (values) => {
|
||||
if (mode === 'create') {
|
||||
const created = await create.mutateAsync(values);
|
||||
setPendingId(created.id);
|
||||
} else if (initial) {
|
||||
await update.mutateAsync({ id: initial.id, input: values });
|
||||
const input = { ...values, folderIds: folders ? values.folderIds : undefined };
|
||||
try {
|
||||
if (mode === 'create') {
|
||||
await create.mutateAsync(input);
|
||||
} else if (initial) {
|
||||
await update.mutateAsync({ id: initial.id, input });
|
||||
}
|
||||
onClose();
|
||||
} catch {
|
||||
// The mutation reports the error and the form retains the draft.
|
||||
}
|
||||
onClose();
|
||||
});
|
||||
|
||||
const activeId = pendingId ?? initial?.id ?? null;
|
||||
const canEditImage = activeId != null;
|
||||
const activeId = initial?.id;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
open
|
||||
onClose={onClose}
|
||||
title={mode === 'create' ? t('wishForm.addTitle') : t('wishForm.editTitle')}
|
||||
description={
|
||||
@@ -102,12 +97,52 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
|
||||
<form id="wish-form" className="grid gap-4" onSubmit={submit}>
|
||||
<div className="field">
|
||||
<Label htmlFor="title">{t('wishForm.title')}</Label>
|
||||
<Input id="title" placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
|
||||
<Input id="title" autoFocus placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
|
||||
{errors.title && (
|
||||
<span className="field__error">{translateValidation(t, errors.title.message)}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<Label htmlFor="price">{t('wishForm.price')}</Label>
|
||||
@@ -153,7 +188,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{canEditImage && activeId && (
|
||||
{activeId && (
|
||||
<section className="mt-6 rounded-md border border-border bg-surface-muted p-4">
|
||||
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-ink">
|
||||
<ImageIcon className="h-4 w-4" />
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { CreateWishInput, UpdateWishInput } from '@family-wishlist/shared';
|
||||
import type {
|
||||
CreateFolderInput,
|
||||
CreateWishInput,
|
||||
UpdateWishInput,
|
||||
WishDashboard,
|
||||
WishFolder,
|
||||
} from '@family-wishlist/shared';
|
||||
import { toast } from 'sonner';
|
||||
import { wishesApi, type OwnerStatus } from './wishes.api';
|
||||
import { ApiError } from '@/lib/api';
|
||||
import { api, ApiError } from '@/lib/api';
|
||||
import { useI18n } from '@/i18n/i18n';
|
||||
|
||||
const LIST_KEY = (status: OwnerStatus) => ['wishes', status] as const;
|
||||
const DASHBOARD_KEY = ['wishes', 'dashboard'] as const;
|
||||
|
||||
function invalidateAll(client: ReturnType<typeof useQueryClient>): void {
|
||||
void client.invalidateQueries({ queryKey: ['wishes'] });
|
||||
@@ -24,6 +31,36 @@ export function useWishes(status: OwnerStatus) {
|
||||
});
|
||||
}
|
||||
|
||||
export function useWishDashboard() {
|
||||
return useQuery({
|
||||
queryKey: DASHBOARD_KEY,
|
||||
queryFn: ({ signal }) => api.get<WishDashboard>('/api/dashboard', signal),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateFolder() {
|
||||
const client = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ input, cover }: { input: CreateFolderInput; cover: File | null }) => {
|
||||
const data = new FormData();
|
||||
data.append('name', input.name);
|
||||
if (input.description) data.append('description', input.description);
|
||||
if (input.emoji) data.append('emoji', input.emoji);
|
||||
if (cover) data.append('cover', cover);
|
||||
return api.upload<WishFolder>('/api/folders', data);
|
||||
},
|
||||
onSuccess: (folder) => {
|
||||
client.setQueryData<WishDashboard>(DASHBOARD_KEY, (current) =>
|
||||
current && {
|
||||
...current,
|
||||
folders: [...current.folders.filter(({ id }) => id !== folder.id), folder],
|
||||
},
|
||||
);
|
||||
void client.invalidateQueries({ queryKey: DASHBOARD_KEY });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateWish() {
|
||||
const client = useQueryClient();
|
||||
const { t } = useI18n();
|
||||
|
||||
@@ -29,7 +29,7 @@ const translations = {
|
||||
'common.days.many': '{count} дней',
|
||||
'footer.frontend': 'frontend v{version}',
|
||||
'footer.backend': 'backend v{version}',
|
||||
'header.active': 'Активные',
|
||||
'header.home': 'Главная',
|
||||
'header.fulfilled': 'Исполненные',
|
||||
'header.archive': 'Архив',
|
||||
'header.trash': 'Корзина',
|
||||
@@ -44,12 +44,29 @@ const translations = {
|
||||
'login.password': 'Пароль',
|
||||
'login.submit': 'Войти',
|
||||
'login.failed': 'Не удалось войти',
|
||||
'dashboard.title': 'Ваш список желаний',
|
||||
'dashboard.description': 'Добавляйте вещи, о которых мечтаете. Публичная страница доступна по адресу ',
|
||||
'dashboard.title': 'Семейный список желаний',
|
||||
'dashboard.publicPage': 'Моя публичная страница',
|
||||
'dashboard.addWish': 'Добавить желание',
|
||||
'dashboard.emptyTitle': 'Желаний пока нет',
|
||||
'dashboard.emptyText': 'Начните с того, что вам действительно хочется получить.',
|
||||
'dashboard.addFirstWish': 'Добавить первое желание',
|
||||
'dashboard.loadError': 'Не удалось загрузить список желаний.',
|
||||
'dashboard.retry': 'Повторить',
|
||||
'dashboard.hideCompleted': 'Скрыть исполненные',
|
||||
'dashboard.completedHidden': 'Исполненные желания скрыты',
|
||||
'folders.title': 'Папки желаний',
|
||||
'folders.all': 'Все',
|
||||
'folders.create': 'Создать папку',
|
||||
'folders.name': 'Название',
|
||||
'folders.description': 'Описание (необязательно)',
|
||||
'folders.cover': 'Обложка',
|
||||
'folders.noCover': 'Без обложки',
|
||||
'folders.emoji': 'Эмодзи',
|
||||
'folders.image': 'Изображение',
|
||||
'folders.field': 'В каких папках видно желание',
|
||||
'folders.alwaysVisible': 'Желание всегда видно во «Все».',
|
||||
'folders.invalidDetails': 'Проверьте название и описание папки.',
|
||||
'folders.invalidEmoji': 'Введите эмодзи для обложки.',
|
||||
'folders.invalidImage': 'Выберите файл JPEG, PNG, WebP или GIF размером до 8 МБ.',
|
||||
'folders.saveError': 'Не удалось создать папку. Попробуйте ещё раз.',
|
||||
'archive.title': 'Архив',
|
||||
'archive.description': 'Отложенные желания. Их видите только вы, и их можно вернуть в активный список.',
|
||||
'archive.emptyTitle': 'Архив пуст',
|
||||
@@ -146,7 +163,7 @@ const translations = {
|
||||
'common.days.many': '{count} days',
|
||||
'footer.frontend': 'frontend v{version}',
|
||||
'footer.backend': 'backend v{version}',
|
||||
'header.active': 'Active',
|
||||
'header.home': 'Home',
|
||||
'header.fulfilled': 'Fulfilled',
|
||||
'header.archive': 'Archive',
|
||||
'header.trash': 'Trash',
|
||||
@@ -161,12 +178,29 @@ const translations = {
|
||||
'login.password': 'Password',
|
||||
'login.submit': 'Sign in',
|
||||
'login.failed': 'Login failed',
|
||||
'dashboard.title': 'Your wishlist',
|
||||
'dashboard.description': 'Add things you dream of. Share your public page at ',
|
||||
'dashboard.title': 'Family wishlist',
|
||||
'dashboard.publicPage': 'My public page',
|
||||
'dashboard.addWish': 'Add wish',
|
||||
'dashboard.emptyTitle': 'No wishes yet',
|
||||
'dashboard.emptyText': "Start by adding something you'd love to receive.",
|
||||
'dashboard.addFirstWish': 'Add your first wish',
|
||||
'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',
|
||||
'folders.name': 'Name',
|
||||
'folders.description': 'Description (optional)',
|
||||
'folders.cover': 'Cover',
|
||||
'folders.noCover': 'No cover',
|
||||
'folders.emoji': 'Emoji',
|
||||
'folders.image': 'Image',
|
||||
'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.',
|
||||
'folders.saveError': "Couldn't create the folder. Try again.",
|
||||
'archive.title': 'Archive',
|
||||
'archive.description': 'Wishes you put aside. Only you see this. Restore them to your active list any time.',
|
||||
'archive.emptyTitle': 'Archive is empty',
|
||||
|
||||
@@ -1,104 +1,254 @@
|
||||
import { useState } from 'react';
|
||||
import { Plus, Sparkles } from 'lucide-react';
|
||||
import { useRef, useState, type ReactNode } from 'react';
|
||||
import { Folder, FolderPlus, LayoutGrid, Plus, UserRound } from 'lucide-react';
|
||||
import type { Wish } from '@family-wishlist/shared';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { WishCard } from '@/components/WishCard/WishCard';
|
||||
import { FolderForm } from '@/components/WishForm/FolderForm';
|
||||
import { WishForm } from '@/components/WishForm/WishForm';
|
||||
import {
|
||||
useArchiveWish,
|
||||
useCompleteWish,
|
||||
useDeleteWish,
|
||||
useWishes,
|
||||
useDuplicateWish,
|
||||
useWishDashboard,
|
||||
} from '@/features/wishes/wishes.hooks';
|
||||
import { useAuthStore } from '@/features/auth/authStore';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useI18n } from '@/i18n/i18n';
|
||||
|
||||
type Selection = { type: 'all' } | { type: 'author' | 'folder'; id: string };
|
||||
|
||||
function FolderButton({
|
||||
label,
|
||||
cover,
|
||||
selected,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
cover: ReactNode;
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
aria-pressed={selected}
|
||||
onClick={onClick}
|
||||
className="wish-folders__item"
|
||||
>
|
||||
<span className="wish-folders__cover" aria-hidden="true">{cover}</span>
|
||||
<span className="min-w-0 break-words text-left">{label}</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function DashboardPage() {
|
||||
const { t } = useI18n();
|
||||
const { data, isLoading } = useWishes('active');
|
||||
const [creating, setCreating] = useState(false);
|
||||
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);
|
||||
const createFolderButton = useRef<HTMLButtonElement>(null);
|
||||
const archive = useArchiveWish();
|
||||
const complete = useCompleteWish();
|
||||
const remove = useDeleteWish();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const duplicate = useDuplicateWish();
|
||||
const user = useAuthStore((state) => state.user);
|
||||
|
||||
const selectedAuthor = selection.type === 'author'
|
||||
? data?.authors.find(({ id }) => id === selection.id)
|
||||
: undefined;
|
||||
const selectedFolder = selection.type === 'folder'
|
||||
? data?.folders.find(({ id }) => id === selection.id)
|
||||
: undefined;
|
||||
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');
|
||||
|
||||
function closeFolderForm() {
|
||||
setCreatingFolder(false);
|
||||
createFolderButton.current?.focus();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-6">
|
||||
<section className="page-section flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="page-section__title">{t('dashboard.title')}</h1>
|
||||
<p className="page-section__text">
|
||||
{t('dashboard.description')}
|
||||
{user && (
|
||||
<Link
|
||||
to={`/u/${user.slug}`}
|
||||
className="font-medium text-primary hover:text-primary-600"
|
||||
>
|
||||
/u/{user.slug}
|
||||
</Link>
|
||||
)}
|
||||
.
|
||||
</p>
|
||||
{user && (
|
||||
<Link
|
||||
to={`/u/${user.slug}`}
|
||||
className="mt-1 inline-block text-sm font-medium text-ink underline underline-offset-4 hover:decoration-primary"
|
||||
>
|
||||
{t('dashboard.publicPage')}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<Button size="lg" onClick={() => setCreating(true)}>
|
||||
<Plus className="h-4 w-4" />
|
||||
{t('dashboard.addWish')}
|
||||
</Button>
|
||||
</section>
|
||||
|
||||
{isLoading && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{[0, 1, 2].map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="wish-card animate-pulse"
|
||||
style={{ minHeight: 320, background: 'rgb(var(--color-surface-muted))' }}
|
||||
{data && (
|
||||
<section className="wish-folders" aria-label={t('folders.title')}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="font-semibold text-ink">{t('folders.title')}</h2>
|
||||
<Button
|
||||
ref={createFolderButton}
|
||||
variant="ghost"
|
||||
aria-expanded={creatingFolder}
|
||||
onClick={() => setCreatingFolder(true)}
|
||||
>
|
||||
<FolderPlus className="h-4 w-4" aria-hidden />
|
||||
{t('folders.create')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="wish-folders__list">
|
||||
<FolderButton
|
||||
label={t('folders.all')}
|
||||
cover={<LayoutGrid className="h-4 w-4" />}
|
||||
selected={!selectedAuthor && !selectedFolder}
|
||||
onClick={() => setSelection({ type: 'all' })}
|
||||
/>
|
||||
{data.authors.map((author) => (
|
||||
<FolderButton
|
||||
key={author.id}
|
||||
label={author.displayName}
|
||||
cover={author.avatarUrl
|
||||
? <img src={author.avatarUrl} alt="" />
|
||||
: <UserRound className="h-4 w-4" />}
|
||||
selected={selectedAuthor?.id === author.id}
|
||||
onClick={() => setSelection({ type: 'author', id: author.id })}
|
||||
/>
|
||||
))}
|
||||
{data.folders.map((folder) => (
|
||||
<FolderButton
|
||||
key={folder.id}
|
||||
label={folder.name}
|
||||
cover={folder.imageUrl
|
||||
? <img src={folder.imageUrl} alt="" loading="lazy" />
|
||||
: folder.emoji ?? <Folder className="h-4 w-4" />}
|
||||
selected={selectedFolder?.id === folder.id}
|
||||
onClick={() => setSelection({ type: 'folder', id: folder.id })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{creatingFolder && (
|
||||
<FolderForm
|
||||
onCancel={closeFolderForm}
|
||||
onCreated={(folder) => {
|
||||
setSelection({ type: 'folder', id: folder.id });
|
||||
closeFolderForm();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{isPending && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true">
|
||||
{[0, 1, 2].map((i) => (
|
||||
<div key={i} className="wish-card min-h-80 animate-pulse bg-surface-muted" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && data && data.length === 0 && (
|
||||
{isError && (
|
||||
<div className="empty-state gap-4">
|
||||
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
|
||||
<div>
|
||||
<h2 className="empty-state__title">{t('dashboard.emptyTitle')}</h2>
|
||||
<p className="empty-state__text mt-1">
|
||||
{t('dashboard.emptyText')}
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setCreating(true)}>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
{t('dashboard.addFirstWish')}
|
||||
<p role="alert" className="empty-state__text">{t('dashboard.loadError')}</p>
|
||||
<Button variant="outline" onClick={() => void refetch()}>
|
||||
{t('dashboard.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && data && data.length > 0 && (
|
||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{data.map((wish) => (
|
||||
<WishCard
|
||||
key={wish.id}
|
||||
wish={wish}
|
||||
view="owner"
|
||||
onEdit={() => setEditing(wish)}
|
||||
onArchive={() => archive.mutate(wish.id)}
|
||||
onComplete={() => complete.mutate(wish.id)}
|
||||
onDelete={() => remove.mutate(wish.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{wishes && (
|
||||
<section className="grid min-w-0 gap-4" aria-label={sectionTitle}>
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h2 className="break-words text-xl font-semibold text-ink">{sectionTitle}</h2>
|
||||
{selectedFolder?.description && (
|
||||
<p className="mt-1 whitespace-pre-wrap break-words text-sm text-muted">
|
||||
{selectedFolder.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<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(folderWishes?.length ? 'dashboard.completedHidden' : 'dashboard.emptyTitle')}
|
||||
</h3>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{wishes.map((wish) => {
|
||||
const owned = wish.userId === user?.id;
|
||||
const author = data?.authors.find(({ id }) => id === wish.userId);
|
||||
return (
|
||||
<WishCard
|
||||
key={wish.id}
|
||||
wish={wish}
|
||||
view={owned ? 'owner' : 'guest'}
|
||||
onEdit={() => setEditing(wish)}
|
||||
onArchive={() => archive.mutate(wish.id)}
|
||||
onComplete={() => complete.mutate(wish.id)}
|
||||
onDelete={() => remove.mutate(wish.id)}
|
||||
onDuplicate={() => duplicate.mutate(wish.id)}
|
||||
footer={!selectedAuthor && author && (
|
||||
<p className="mt-auto break-words pt-2 text-xs text-muted">
|
||||
{author.displayName}
|
||||
</p>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
<WishForm open={creating} mode="create" onClose={() => setCreating(false)} />
|
||||
<WishForm
|
||||
open={editing !== null}
|
||||
mode="edit"
|
||||
initial={editing ?? undefined}
|
||||
onClose={() => setEditing(null)}
|
||||
/>
|
||||
{creatingWish && user && (
|
||||
<WishForm
|
||||
mode="create"
|
||||
authorName={user.displayName}
|
||||
folders={data?.folders}
|
||||
defaultFolderId={selectedFolder?.id}
|
||||
onClose={() => setCreatingWish(false)}
|
||||
/>
|
||||
)}
|
||||
{editing && user && (
|
||||
<WishForm
|
||||
mode="edit"
|
||||
authorName={user.displayName}
|
||||
initial={editing}
|
||||
folders={data?.folders}
|
||||
onClose={() => setEditing(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
@@ -25,6 +25,7 @@ export function ProfileSettingsPage() {
|
||||
const refresh = useAuthStore((s) => s.refresh);
|
||||
const queryClient = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['profile'],
|
||||
@@ -120,6 +121,10 @@ export function ProfileSettingsPage() {
|
||||
|
||||
const avatarPreview = watch('avatarUrl') || data?.avatarUrl;
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [avatarPreview]);
|
||||
|
||||
return (
|
||||
<div className="grid max-w-2xl gap-6">
|
||||
<section className="page-section">
|
||||
@@ -136,8 +141,13 @@ export function ProfileSettingsPage() {
|
||||
<form className="profile-form" onSubmit={submit}>
|
||||
<section className="profile-form__avatar-panel">
|
||||
<span className="profile-form__avatar-preview">
|
||||
{avatarPreview ? (
|
||||
<img src={avatarPreview} alt="" className="profile-form__avatar-image" />
|
||||
{avatarPreview && !avatarFailed ? (
|
||||
<img
|
||||
src={avatarPreview}
|
||||
alt=""
|
||||
className="profile-form__avatar-image"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<Gift className="h-6 w-6" />
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type {
|
||||
@@ -19,6 +19,7 @@ export function PublicProfilePage() {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const { slug = '' } = useParams<{ slug: string }>();
|
||||
const queryClient = useQueryClient();
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
|
||||
const profile = useQuery({
|
||||
queryKey: ['public-profile', slug],
|
||||
@@ -57,6 +58,10 @@ export function PublicProfilePage() {
|
||||
return () => window.clearTimeout(t);
|
||||
}, [wishes.data, markSeen, queryClient, slug]);
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [profile.data?.avatarUrl]);
|
||||
|
||||
return (
|
||||
<div className="public-profile">
|
||||
<div className="public-profile__toolbar">
|
||||
@@ -87,11 +92,12 @@ export function PublicProfilePage() {
|
||||
<>
|
||||
<section className="public-profile__hero">
|
||||
<span className="public-profile__avatar">
|
||||
{profile.data.avatarUrl ? (
|
||||
{profile.data.avatarUrl && !avatarFailed ? (
|
||||
<img
|
||||
src={profile.data.avatarUrl}
|
||||
alt=""
|
||||
className="public-profile__avatar-image"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<Gift className="h-6 w-6" />
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
@apply mx-auto w-full max-w-6xl px-4 pt-6 sm:px-6 lg:px-8;
|
||||
}
|
||||
.app-header__inner {
|
||||
@apply grid grid-cols-1 items-center gap-3 rounded-lg border border-border bg-surface/80 px-4 py-3 backdrop-blur lg:grid-cols-[auto_minmax(0,1fr)_auto];
|
||||
@apply flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-surface/80 px-4 py-3 backdrop-blur;
|
||||
}
|
||||
.app-header__brand {
|
||||
@apply flex min-w-0 items-center gap-2;
|
||||
@@ -55,7 +55,7 @@
|
||||
@apply truncate text-xs text-muted;
|
||||
}
|
||||
.app-header__nav {
|
||||
@apply flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap lg:justify-center;
|
||||
@apply mt-3 flex min-w-0 items-center gap-1 overflow-x-auto whitespace-nowrap rounded-lg border border-border bg-surface/80 px-4 py-2 backdrop-blur;
|
||||
}
|
||||
.app-header__nav-link {
|
||||
@apply inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium text-ink transition-colors hover:bg-ink/5;
|
||||
@@ -64,7 +64,13 @@
|
||||
@apply bg-primary text-primary-foreground shadow-card hover:bg-primary;
|
||||
}
|
||||
.app-header__actions {
|
||||
@apply flex shrink-0 items-center gap-1 justify-self-start lg:justify-self-end;
|
||||
@apply flex shrink-0 items-center gap-1 whitespace-nowrap;
|
||||
}
|
||||
.app-header__action {
|
||||
@apply shrink-0;
|
||||
}
|
||||
.app-header__action-text {
|
||||
@apply hidden xl:inline;
|
||||
}
|
||||
|
||||
.app-footer {
|
||||
@@ -125,6 +131,35 @@
|
||||
@apply text-sm text-muted;
|
||||
}
|
||||
|
||||
.wish-folders {
|
||||
@apply grid min-w-0 gap-3 border-b border-border pb-5;
|
||||
}
|
||||
.wish-folders__list {
|
||||
@apply flex flex-wrap gap-2;
|
||||
}
|
||||
.wish-folders .wish-folders__item {
|
||||
@apply h-auto min-h-11 max-w-full justify-start px-2.5 py-1.5 pr-3;
|
||||
}
|
||||
.wish-folders__item[aria-pressed='true'] {
|
||||
@apply border-primary bg-primary/10 text-ink;
|
||||
}
|
||||
.wish-folders__cover {
|
||||
@apply grid h-7 w-7 shrink-0 place-items-center overflow-hidden rounded-sm bg-surface-muted text-base;
|
||||
}
|
||||
.wish-folders__cover img {
|
||||
@apply h-full w-full object-cover;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -49,4 +49,4 @@ WORKDIR /app/apps/backend
|
||||
EXPOSE 3000
|
||||
# Apply schema (idempotent; uses `db push` so no prior migrations required) +
|
||||
# seed env users + start server.
|
||||
CMD ["sh", "-c", "pnpm exec prisma db push --accept-data-loss --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
|
||||
CMD ["sh", "-c", "pnpm exec prisma db push --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
|
||||
+8
-8
@@ -4,13 +4,6 @@ server {
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Static files with long cache
|
||||
location ~* \.(?:js|css|woff2?|svg|png|jpg|jpeg|gif|webp|ico)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# API proxy
|
||||
location /api/ {
|
||||
proxy_pass http://family-wishlist-backend:3000/api/;
|
||||
@@ -24,13 +17,20 @@ server {
|
||||
}
|
||||
|
||||
# Uploaded files (images)
|
||||
location /uploads/ {
|
||||
location ^~ /uploads/ {
|
||||
proxy_pass http://family-wishlist-backend:3000/uploads/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_cache_valid 200 1h;
|
||||
}
|
||||
|
||||
# Static files with long cache
|
||||
location ~* \.(?:js|css|woff2?|svg|png|jpg|jpeg|gif|webp|ico)$ {
|
||||
expires 7d;
|
||||
add_header Cache-Control "public";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# SPA fallback
|
||||
location / {
|
||||
try_files $uri /index.html;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@family-wishlist/shared",
|
||||
"version": "0.1.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from 'zod';
|
||||
import type { Wish } from './wish.schema.js';
|
||||
|
||||
export const createFolderSchema = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
description: z.string().trim().max(500).optional(),
|
||||
emoji: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(32)
|
||||
.regex(/^(?:(?:\p{Extended_Pictographic}|\p{Regional_Indicator})[\p{Extended_Pictographic}\p{Regional_Indicator}\p{Emoji_Modifier}\uFE0F\u200D]*|[#*0-9]\uFE0F?\u20E3)$/u)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export type CreateFolderInput = z.infer<typeof createFolderSchema>;
|
||||
|
||||
export interface WishFolder {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
emoji: string | null;
|
||||
imageUrl: string | null;
|
||||
}
|
||||
|
||||
export interface WishDashboard {
|
||||
authors: { id: string; displayName: string; avatarUrl: string | null }[];
|
||||
folders: WishFolder[];
|
||||
wishes: (Wish & { userId: string; isNewForOwner: boolean })[];
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
export * from './auth.schema.js';
|
||||
export * from './profile.schema.js';
|
||||
export * from './wish.schema.js';
|
||||
export * from './folder.schema.js';
|
||||
export * from './public.schema.js';
|
||||
export * from './types.js';
|
||||
@@ -22,12 +22,18 @@ export const wishSchema = z.object({
|
||||
completedAt: z.string().nullable(),
|
||||
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(),
|
||||
});
|
||||
|
||||
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([
|
||||
|
||||
Reference in new issue
Block a user