feat: add collaborative shopping lists with items and invitations
Some checks failed
CI / Verify (push) Has been cancelled
Some checks failed
CI / Verify (push) Has been cancelled
API: lists, items and invitations modules (list, create, get, update, set-primary, items create/list, invitation create/accept/list-pending), BetterAuth session helper, list membership, mailer and Prisma schema plus migrations. Web: lists overview, list detail (items) and list management (settings) views, item and invitation forms/hooks, sign-up and invitation accept pages. Shared: shopping list DTOs. Tooling: ignore the generated TanStack Router cache (apps/web/.tanstack).
This commit is contained in:
@@ -13,6 +13,12 @@ BETTER_AUTH_URL="http://localhost:4100"
|
|||||||
NODE_ENV="development"
|
NODE_ENV="development"
|
||||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||||
# LOG_LEVEL="info"
|
# LOG_LEVEL="info"
|
||||||
|
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||||
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
|
# Public URL of the web app, used to build the accept-invitation links
|
||||||
|
WEB_APP_URL="http://localhost:7153"
|
||||||
|
|
||||||
# --- apps/web ---
|
# --- apps/web ---
|
||||||
# Public URL of the API consumed by the frontend
|
# Public URL of the API consumed by the frontend
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -22,4 +22,5 @@ logs/
|
|||||||
|
|
||||||
# generated
|
# generated
|
||||||
apps/web/src/routeTree.gen.ts
|
apps/web/src/routeTree.gen.ts
|
||||||
|
apps/web/.tanstack/
|
||||||
apps/api/src/generated/
|
apps/api/src/generated/
|
||||||
|
|||||||
20
AGENTS.md
20
AGENTS.md
@@ -5,8 +5,8 @@
|
|||||||
Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`,
|
Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web` and `packages/shared`,
|
||||||
CI on GitHub Actions, Biome as the only JS/TS tool and the text Bun lockfile committed.
|
CI on GitHub Actions, Biome as the only JS/TS tool and the text Bun lockfile committed.
|
||||||
|
|
||||||
Not done yet: no database migrations (`prisma/migrations` does not exist — no Postgres has been run against
|
Not done yet: product features are just starting (sign-up, shopping lists, list items and invitations exist;
|
||||||
the schema) and no product features. The only backend module is `health`, used as the reference example.
|
there is no Google login and no email verification). The `health` module is the reference example.
|
||||||
|
|
||||||
## Stack (source of truth: `STACK.md`)
|
## Stack (source of truth: `STACK.md`)
|
||||||
|
|
||||||
@@ -82,6 +82,12 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
|||||||
- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and
|
- **TypeScript 6 specifics:** `baseUrl` no longer exists (aliases are declared with `paths` only), and
|
||||||
`apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter
|
`apps/web/tsconfig.app.json` enables `erasableSyntaxOnly` — no enums, namespaces or constructor parameter
|
||||||
properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`).
|
properties in the web app. Both apps use `@/*` → `src/*` and `verbatimModuleSyntax` (use `import type`).
|
||||||
|
- **Database naming (Prisma):** tables are **plural snake_case** (`shopping_lists`, `users`),
|
||||||
|
columns are **snake_case** (`owner_id`, `created_at`) and enum types are **snake_case** (`list_role`) — all
|
||||||
|
declared with `@@map` / `@map` in `schema.prisma`. The Prisma *model* and *field* names stay
|
||||||
|
PascalCase/camelCase, because BetterAuth and the generated client address models by those names, so a column
|
||||||
|
rename never changes the TypeScript API. Default constraint/index names follow the mapped names, so do not
|
||||||
|
set `map:` unless you have a reason to.
|
||||||
- CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`: `bun install --frozen-lockfile` →
|
- CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `main`: `bun install --frozen-lockfile` →
|
||||||
`db:generate` → `lint:ci` → `typecheck` → `test` → `build`, with Bun 1.4.0 and Node 22 for the Prisma CLI.
|
`db:generate` → `lint:ci` → `typecheck` → `test` → `build`, with Bun 1.4.0 and Node 22 for the Prisma CLI.
|
||||||
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||||
@@ -191,8 +197,9 @@ export class CreateAlert {
|
|||||||
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
||||||
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
||||||
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
||||||
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema with lowercase
|
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema and follow the
|
||||||
`@@map`ed table names; regenerate them with the BetterAuth CLI rather than by hand if the auth config changes.
|
naming convention above (`users`, `sessions`, `accounts`, `verifications` with snake_case columns); regenerate
|
||||||
|
them with the BetterAuth CLI rather than by hand if the auth config changes, then re-apply the mapping.
|
||||||
|
|
||||||
## Shared package (`@superlist/shared`)
|
## Shared package (`@superlist/shared`)
|
||||||
|
|
||||||
@@ -227,6 +234,11 @@ apps/web/src/
|
|||||||
prefetch), renders `QueryClientProvider` + `RouterProvider`, and registers the router type. `__root.tsx`
|
prefetch), renders `QueryClientProvider` + `RouterProvider`, and registers the router type. `__root.tsx`
|
||||||
wraps everything in `ThemeProvider` + `TooltipProvider`, mounts the Sonner `Toaster` and lazy-loads the router
|
wraps everything in `ThemeProvider` + `TooltipProvider`, mounts the Sonner `Toaster` and lazy-loads the router
|
||||||
and query devtools in development only.
|
and query devtools in development only.
|
||||||
|
- **Theme**: hand-rolled in `src/components/theme-provider.tsx` — `useTheme()` exposes `theme`, `resolvedTheme`
|
||||||
|
and `setTheme`, and the provider toggles the `.dark` class and `color-scheme` on `<html>`. The pre-paint script
|
||||||
|
in `apps/web/index.html` applies the stored theme before React mounts; both share the `superlist-theme`
|
||||||
|
storage key, so keep them in sync. Do not swap this for `next-themes`: it renders a `<script>` from React, and
|
||||||
|
React 19 never executes (and warns about) scripts rendered on the client.
|
||||||
- **Server state: TanStack Query only.** Never call `fetch` from a component; add a hook under `src/hooks` that
|
- **Server state: TanStack Query only.** Never call `fetch` from a component; add a hook under `src/hooks` that
|
||||||
exports `queryOptions` (`<entity>QueryOptions()`) plus a `use<Entity>()` wrapper, and use `apiFetch` from
|
exports `queryOptions` (`<entity>QueryOptions()`) plus a `use<Entity>()` wrapper, and use `apiFetch` from
|
||||||
`src/lib/api-client.ts` as the `queryFn`. Exporting the options lets route loaders prefetch with
|
`src/lib/api-client.ts` as the `queryFn`. Exporting the options lets route loaders prefetch with
|
||||||
|
|||||||
@@ -6,3 +6,9 @@ BETTER_AUTH_URL="http://localhost:4100"
|
|||||||
NODE_ENV="development"
|
NODE_ENV="development"
|
||||||
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
# Optional: Pino log level (defaults to "debug" outside production, "info" in production)
|
||||||
# LOG_LEVEL="info"
|
# LOG_LEVEL="info"
|
||||||
|
# Resend API key used to send invitation emails. Without it, emails are logged instead.
|
||||||
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
|
# Public URL of the web app, used to build the accept-invitation links
|
||||||
|
WEB_APP_URL="http://localhost:7153"
|
||||||
|
|||||||
@@ -25,6 +25,7 @@
|
|||||||
"pg": "^8.23.1",
|
"pg": "^8.23.1",
|
||||||
"pino": "^10.4.0",
|
"pino": "^10.4.0",
|
||||||
"pino-pretty": "^13.2.0",
|
"pino-pretty": "^13.2.0",
|
||||||
|
"resend": "^6.32.1",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
157
apps/api/prisma/migrations/20261015205940_init/migration.sql
Normal file
157
apps/api/prisma/migrations/20261015205940_init/migration.sql
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "list_role" AS ENUM ('owner', 'collaborator');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "invitation_status" AS ENUM ('pending', 'accepted', 'revoked', 'expired');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "users" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"email_verified" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"image" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "sessions" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"token" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"ip_address" TEXT,
|
||||||
|
"user_agent" TEXT,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "accounts" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"account_id" TEXT NOT NULL,
|
||||||
|
"provider_id" TEXT NOT NULL,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
"access_token" TEXT,
|
||||||
|
"refresh_token" TEXT,
|
||||||
|
"id_token" TEXT,
|
||||||
|
"access_token_expires_at" TIMESTAMP(3),
|
||||||
|
"refresh_token_expires_at" TIMESTAMP(3),
|
||||||
|
"scope" TEXT,
|
||||||
|
"password" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "verifications" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"identifier" TEXT NOT NULL,
|
||||||
|
"value" TEXT NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "verifications_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "shopping_lists" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"owner_id" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "shopping_lists_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "shopping_list_members" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"list_id" TEXT NOT NULL,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
"role" "list_role" NOT NULL DEFAULT 'collaborator',
|
||||||
|
"is_primary" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "shopping_list_members_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "shopping_list_invitations" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"list_id" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"token" TEXT NOT NULL,
|
||||||
|
"status" "invitation_status" NOT NULL DEFAULT 'pending',
|
||||||
|
"invited_by_id" TEXT NOT NULL,
|
||||||
|
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
"accepted_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "shopping_list_invitations_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "sessions_user_id_idx" ON "sessions"("user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "sessions_token_key" ON "sessions"("token");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "accounts_user_id_idx" ON "accounts"("user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "verifications_identifier_idx" ON "verifications"("identifier");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "shopping_lists_owner_id_idx" ON "shopping_lists"("owner_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "shopping_list_members_user_id_is_primary_idx" ON "shopping_list_members"("user_id", "is_primary");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "shopping_list_members_list_id_user_id_key" ON "shopping_list_members"("list_id", "user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "shopping_list_invitations_list_id_status_idx" ON "shopping_list_invitations"("list_id", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "shopping_list_invitations_email_status_idx" ON "shopping_list_invitations"("email", "status");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "shopping_list_invitations_token_key" ON "shopping_list_invitations"("token");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "shopping_lists" ADD CONSTRAINT "shopping_lists_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "shopping_list_members" ADD CONSTRAINT "shopping_list_members_list_id_fkey" FOREIGN KEY ("list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "shopping_list_members" ADD CONSTRAINT "shopping_list_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "shopping_list_invitations" ADD CONSTRAINT "shopping_list_invitations_list_id_fkey" FOREIGN KEY ("list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "shopping_list_invitations" ADD CONSTRAINT "shopping_list_invitations_invited_by_id_fkey" FOREIGN KEY ("invited_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "list_items" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"shopping_list_id" TEXT NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"completed" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"quantity" TEXT,
|
||||||
|
"notes" TEXT,
|
||||||
|
"order" INTEGER NOT NULL DEFAULT 0,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "list_items_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "list_items_shopping_list_id_order_idx" ON "list_items"("shopping_list_id", "order");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "list_items" ADD CONSTRAINT "list_items_shopping_list_id_fkey" FOREIGN KEY ("shopping_list_id") REFERENCES "shopping_lists"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
3
apps/api/prisma/migrations/migration_lock.toml
Normal file
3
apps/api/prisma/migrations/migration_lock.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
// Prisma schema. Docs: https://pris.ly/d/prisma-schema
|
// Prisma schema. Docs: https://pris.ly/d/prisma-schema
|
||||||
//
|
//
|
||||||
|
// Naming convention (see AGENTS.md): tables are plural snake_case
|
||||||
|
// (`shopping_lists`, `users`), columns are snake_case (`created_at`,
|
||||||
|
// `owner_id`) and enum types are snake_case (`list_role`), declared through
|
||||||
|
// `@@map` / `@map`. The Prisma *model* and *field* names stay PascalCase /
|
||||||
|
// camelCase because BetterAuth and the generated client address models by
|
||||||
|
// those names.
|
||||||
|
//
|
||||||
// After editing this file run `bun run db:migrate` (creates + applies a migration)
|
// After editing this file run `bun run db:migrate` (creates + applies a migration)
|
||||||
// and commit the generated migration under `prisma/migrations`.
|
// and commit the generated migration under `prisma/migrations`.
|
||||||
|
|
||||||
@@ -14,67 +21,164 @@ generator client {
|
|||||||
|
|
||||||
// --- BetterAuth core models -------------------------------------------------
|
// --- BetterAuth core models -------------------------------------------------
|
||||||
// Shape generated by `bunx @better-auth/cli generate`. Keep in sync with the
|
// Shape generated by `bunx @better-auth/cli generate`. Keep in sync with the
|
||||||
// fields the auth config expects.
|
// fields the auth config expects, and keep the snake_case mapping below if you
|
||||||
|
// regenerate it.
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id String @id
|
id String @id
|
||||||
name String
|
name String
|
||||||
email String
|
email String
|
||||||
emailVerified Boolean @default(false)
|
emailVerified Boolean @default(false) @map("email_verified")
|
||||||
image String?
|
image String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
accounts Account[]
|
accounts Account[]
|
||||||
|
ownedLists ShoppingList[] @relation("ListOwner")
|
||||||
|
memberships ShoppingListMember[]
|
||||||
|
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
||||||
|
|
||||||
@@unique([email])
|
@@unique([email])
|
||||||
@@map("user")
|
@@map("users")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Session {
|
model Session {
|
||||||
id String @id
|
id String @id
|
||||||
expiresAt DateTime
|
expiresAt DateTime @map("expires_at")
|
||||||
token String
|
token String
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
ipAddress String?
|
ipAddress String? @map("ip_address")
|
||||||
userAgent String?
|
userAgent String? @map("user_agent")
|
||||||
userId String
|
userId String @map("user_id")
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
@@unique([token])
|
@@unique([token])
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@map("session")
|
@@map("sessions")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Account {
|
model Account {
|
||||||
id String @id
|
id String @id
|
||||||
accountId String
|
accountId String @map("account_id")
|
||||||
providerId String
|
providerId String @map("provider_id")
|
||||||
userId String
|
userId String @map("user_id")
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
accessToken String?
|
accessToken String? @map("access_token")
|
||||||
refreshToken String?
|
refreshToken String? @map("refresh_token")
|
||||||
idToken String?
|
idToken String? @map("id_token")
|
||||||
accessTokenExpiresAt DateTime?
|
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
|
||||||
refreshTokenExpiresAt DateTime?
|
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
|
||||||
scope String?
|
scope String?
|
||||||
password String?
|
password String?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
@@map("account")
|
@@map("accounts")
|
||||||
}
|
}
|
||||||
|
|
||||||
model Verification {
|
model Verification {
|
||||||
id String @id
|
id String @id
|
||||||
identifier String
|
identifier String
|
||||||
value String
|
value String
|
||||||
expiresAt DateTime
|
expiresAt DateTime @map("expires_at")
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
@@index([identifier])
|
@@index([identifier])
|
||||||
@@map("verification")
|
@@map("verifications")
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Domain models ----------------------------------------------------------
|
||||||
|
|
||||||
|
/// A collaborative shopping list. Membership (and therefore access) lives in
|
||||||
|
/// `ShoppingListMember`, not in this table.
|
||||||
|
model ShoppingList {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
name String
|
||||||
|
ownerId String @map("owner_id")
|
||||||
|
owner User @relation("ListOwner", fields: [ownerId], references: [id], onDelete: Cascade)
|
||||||
|
members ShoppingListMember[]
|
||||||
|
invitations ShoppingListInvitation[]
|
||||||
|
items ListItem[]
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@index([ownerId])
|
||||||
|
@@map("shopping_lists")
|
||||||
|
}
|
||||||
|
|
||||||
|
model ListItem {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
shoppingListId String @map("shopping_list_id")
|
||||||
|
name String
|
||||||
|
completed Boolean @default(false)
|
||||||
|
quantity String? @map("quantity")
|
||||||
|
notes String? @map("notes")
|
||||||
|
order Int @default(0) @map("order")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
shoppingList ShoppingList @relation(fields: [shoppingListId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([shoppingListId, order])
|
||||||
|
@@map("list_items")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ListRole {
|
||||||
|
owner
|
||||||
|
collaborator
|
||||||
|
|
||||||
|
@@map("list_role")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Join table between a user and a list. `isPrimary` is per user: each person
|
||||||
|
/// picks their own main list among the ones they belong to.
|
||||||
|
model ShoppingListMember {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
listId String @map("list_id")
|
||||||
|
list ShoppingList @relation(fields: [listId], references: [id], onDelete: Cascade)
|
||||||
|
userId String @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
role ListRole @default(collaborator)
|
||||||
|
isPrimary Boolean @default(false) @map("is_primary")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@unique([listId, userId])
|
||||||
|
@@index([userId, isPrimary])
|
||||||
|
@@map("shopping_list_members")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum InvitationStatus {
|
||||||
|
pending
|
||||||
|
accepted
|
||||||
|
revoked
|
||||||
|
expired
|
||||||
|
|
||||||
|
@@map("invitation_status")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pending or historical invitation of an email address to a list. When the
|
||||||
|
/// email already belongs to a user the membership is created immediately and
|
||||||
|
/// this record is stored as `accepted` for history.
|
||||||
|
model ShoppingListInvitation {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
listId String @map("list_id")
|
||||||
|
list ShoppingList @relation(fields: [listId], references: [id], onDelete: Cascade)
|
||||||
|
email String
|
||||||
|
token String
|
||||||
|
status InvitationStatus @default(pending)
|
||||||
|
invitedById String @map("invited_by_id")
|
||||||
|
invitedBy User @relation("InvitedBy", fields: [invitedById], references: [id], onDelete: Cascade)
|
||||||
|
expiresAt DateTime @map("expires_at")
|
||||||
|
acceptedAt DateTime? @map("accepted_at")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@unique([token])
|
||||||
|
@@index([listId, status])
|
||||||
|
@@index([email, status])
|
||||||
|
@@map("shopping_list_invitations")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import { auth } from '@/lib/auth'
|
|||||||
import { logger } from '@/lib/logger'
|
import { logger } from '@/lib/logger'
|
||||||
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
import { errorHandler, notFoundHandler } from '@/lib/problem-details'
|
||||||
import { healthModule } from '@/modules/health'
|
import { healthModule } from '@/modules/health'
|
||||||
|
import { invitationsModule } from '@/modules/invitations'
|
||||||
|
import { listsModule } from '@/modules/lists'
|
||||||
import type { AppEnv } from '@/types'
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||||
@@ -41,6 +43,8 @@ export function createApp() {
|
|||||||
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
|
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
|
||||||
|
|
||||||
app.route('/health', healthModule)
|
app.route('/health', healthModule)
|
||||||
|
app.route('/lists', listsModule)
|
||||||
|
app.route('/invitations', invitationsModule)
|
||||||
|
|
||||||
app.notFound(notFoundHandler)
|
app.notFound(notFoundHandler)
|
||||||
app.onError(errorHandler)
|
app.onError(errorHandler)
|
||||||
|
|||||||
42
apps/api/src/lib/auth-session.ts
Normal file
42
apps/api/src/lib/auth-session.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { problems } from '@superlist/shared'
|
||||||
|
import type { Context, MiddlewareHandler } from 'hono'
|
||||||
|
|
||||||
|
import { auth } from '@/lib/auth'
|
||||||
|
import { problemResponse } from '@/lib/problem-details'
|
||||||
|
import type { AppEnv, SessionUser } from '@/types'
|
||||||
|
|
||||||
|
/** Reads the BetterAuth session for the current request, or `null`. */
|
||||||
|
export async function getSession(c: Context<AppEnv>) {
|
||||||
|
return auth.api.getSession({ headers: c.req.raw.headers })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middleware for protected routes: resolves the BetterAuth session, exposes the
|
||||||
|
* user/session on the context and answers `401` when there is none.
|
||||||
|
*
|
||||||
|
* ```ts
|
||||||
|
* app.get('/', requireSession, (c) => {
|
||||||
|
* const user = c.get('user')
|
||||||
|
* ...
|
||||||
|
* })
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export const requireSession: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||||
|
const session = await auth.api.getSession({ headers: c.req.raw.headers })
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return problemResponse(c, problems.unauthorized())
|
||||||
|
}
|
||||||
|
|
||||||
|
const user: SessionUser = {
|
||||||
|
id: session.user.id,
|
||||||
|
name: session.user.name,
|
||||||
|
email: session.user.email,
|
||||||
|
image: session.user.image,
|
||||||
|
}
|
||||||
|
|
||||||
|
c.set('user', user)
|
||||||
|
c.set('session', { id: session.session.id, userId: session.user.id })
|
||||||
|
|
||||||
|
await next()
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { betterAuth } from 'better-auth'
|
import { betterAuth } from 'better-auth'
|
||||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||||
|
|
||||||
|
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||||
import { prisma } from '@/lib/prisma'
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||||
@@ -15,6 +16,20 @@ export const auth = betterAuth({
|
|||||||
trustedOrigins,
|
trustedOrigins,
|
||||||
emailAndPassword: {
|
emailAndPassword: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
|
minPasswordLength: 8,
|
||||||
|
requireEmailVerification: false,
|
||||||
|
},
|
||||||
|
databaseHooks: {
|
||||||
|
user: {
|
||||||
|
create: {
|
||||||
|
// People invited before signing up get their shared lists on creation,
|
||||||
|
// and everyone ends up with at least one list of their own.
|
||||||
|
after: async (user) => {
|
||||||
|
await acceptPendingInvitations(prisma, { userId: user.id, email: user.email })
|
||||||
|
await ensurePrimaryList(prisma, { userId: user.id })
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
52
apps/api/src/lib/emails/invitation.ts
Normal file
52
apps/api/src/lib/emails/invitation.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import type { Email } from '@/lib/mailer'
|
||||||
|
|
||||||
|
type InvitationEmailInput = {
|
||||||
|
inviterName: string
|
||||||
|
listName: string
|
||||||
|
acceptUrl: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds the "you have been invited to a list" email (in Spanish). */
|
||||||
|
export function invitationEmail({
|
||||||
|
inviterName,
|
||||||
|
listName,
|
||||||
|
acceptUrl,
|
||||||
|
}: InvitationEmailInput): Omit<Email, 'to'> {
|
||||||
|
const subject = `${inviterName} te invitó a la lista «${listName}»`
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`${inviterName} te invitó a colaborar en la lista de compras «${listName}» en Superlist.`,
|
||||||
|
'',
|
||||||
|
'Abre este enlace para aceptar la invitación:',
|
||||||
|
acceptUrl,
|
||||||
|
'',
|
||||||
|
'Si no tienes cuenta, podrás crear una en el mismo enlace.',
|
||||||
|
].join('\n')
|
||||||
|
|
||||||
|
const html = `<!doctype html>
|
||||||
|
<html lang="es">
|
||||||
|
<body style="font-family: ui-sans-serif, system-ui, sans-serif; background:#f4f4f5; padding:32px;">
|
||||||
|
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:480px; margin:0 auto; background:#ffffff; border-radius:12px; padding:32px;">
|
||||||
|
<tr><td>
|
||||||
|
<h1 style="font-size:20px; margin:0 0 16px;">Te invitaron a una lista</h1>
|
||||||
|
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 8px;">
|
||||||
|
<strong>${inviterName}</strong> te invitó a colaborar en la lista de compras
|
||||||
|
<strong>«${listName}»</strong> en Superlist.
|
||||||
|
</p>
|
||||||
|
<p style="font-size:15px; line-height:1.5; color:#3f3f46; margin:0 0 24px;">
|
||||||
|
Si todavía no tienes cuenta, podrás crear una en el mismo enlace.
|
||||||
|
</p>
|
||||||
|
<a href="${acceptUrl}" style="display:inline-block; background:#18181b; color:#ffffff; text-decoration:none; padding:12px 20px; border-radius:8px; font-size:15px;">
|
||||||
|
Aceptar invitación
|
||||||
|
</a>
|
||||||
|
<p style="font-size:13px; line-height:1.5; color:#71717a; margin:24px 0 0;">
|
||||||
|
Si el botón no funciona, copia y pega este enlace en tu navegador:<br />
|
||||||
|
<a href="${acceptUrl}" style="color:#2563eb;">${acceptUrl}</a>
|
||||||
|
</p>
|
||||||
|
</td></tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
|
||||||
|
return { subject, html, text }
|
||||||
|
}
|
||||||
58
apps/api/src/lib/list-membership.ts
Normal file
58
apps/api/src/lib/list-membership.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grants membership for every `pending`, non-expired invitation that matches the
|
||||||
|
* email and marks those invitations as accepted.
|
||||||
|
*
|
||||||
|
* Called right after a BetterAuth user is created, so people who are invited
|
||||||
|
* before signing up see the shared lists as soon as they register.
|
||||||
|
*
|
||||||
|
* @returns how many invitations were accepted
|
||||||
|
*/
|
||||||
|
export async function acceptPendingInvitations(
|
||||||
|
db: Database,
|
||||||
|
{ userId, email }: { userId: string; email: string },
|
||||||
|
): Promise<number> {
|
||||||
|
const pending = await db.shoppingListInvitation.findMany({
|
||||||
|
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const invitation of pending) {
|
||||||
|
await db.$transaction([
|
||||||
|
db.shoppingListMember.upsert({
|
||||||
|
where: { listId_userId: { listId: invitation.listId, userId } },
|
||||||
|
update: {},
|
||||||
|
create: { listId: invitation.listId, userId, role: 'collaborator' },
|
||||||
|
}),
|
||||||
|
db.shoppingListInvitation.update({
|
||||||
|
where: { id: invitation.id },
|
||||||
|
data: { status: 'accepted', acceptedAt: new Date() },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
return pending.length
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guarantees the user has at least one list: when they belong to none, creates a
|
||||||
|
* "Lista principal" owned by them and marks it as their primary list. Called
|
||||||
|
* right after a BetterAuth user is created (after pending invitations are
|
||||||
|
* accepted) so every account has a starting point.
|
||||||
|
*/
|
||||||
|
export async function ensurePrimaryList(
|
||||||
|
db: Database,
|
||||||
|
{ userId }: { userId: string },
|
||||||
|
): Promise<void> {
|
||||||
|
const memberships = await db.shoppingListMember.count({ where: { userId } })
|
||||||
|
|
||||||
|
if (memberships > 0) return
|
||||||
|
|
||||||
|
await db.shoppingList.create({
|
||||||
|
data: {
|
||||||
|
name: 'Lista principal',
|
||||||
|
ownerId: userId,
|
||||||
|
members: { create: { userId, role: 'owner', isPrimary: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
46
apps/api/src/lib/mailer.ts
Normal file
46
apps/api/src/lib/mailer.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import { Resend } from 'resend'
|
||||||
|
|
||||||
|
import { logger } from '@/lib/logger'
|
||||||
|
|
||||||
|
/** Minimal email payload the API sends. */
|
||||||
|
export type Email = {
|
||||||
|
to: string
|
||||||
|
subject: string
|
||||||
|
html: string
|
||||||
|
text: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const apiKey = process.env.RESEND_API_KEY
|
||||||
|
const from = process.env.MAIL_FROM ?? 'Superlist <onboarding@resend.dev>'
|
||||||
|
|
||||||
|
let client: Resend | null = null
|
||||||
|
|
||||||
|
function getClient(): Resend | null {
|
||||||
|
if (!apiKey) return null
|
||||||
|
|
||||||
|
client ??= new Resend(apiKey)
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends an email through Resend. Without `RESEND_API_KEY` (local development)
|
||||||
|
* it logs the message with Pino instead of sending it, so invitation links are
|
||||||
|
* still discoverable in the terminal.
|
||||||
|
*/
|
||||||
|
export async function sendEmail(email: Email): Promise<void> {
|
||||||
|
const resend = getClient()
|
||||||
|
|
||||||
|
if (!resend) {
|
||||||
|
logger.info(
|
||||||
|
{ to: email.to, subject: email.subject, text: email.text },
|
||||||
|
'email not sent (RESEND_API_KEY is not set) — logging payload instead',
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const { error } = await resend.emails.send({ from, ...email })
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
throw new Error(`Resend failed to send the email: ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
13
apps/api/src/lib/web-app-url.ts
Normal file
13
apps/api/src/lib/web-app-url.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
const configured = process.env.WEB_APP_URL?.trim()
|
||||||
|
const corsOrigin = (process.env.CORS_ORIGIN ?? 'http://localhost:7153')
|
||||||
|
.split(',')
|
||||||
|
.map((origin) => origin.trim())
|
||||||
|
.filter(Boolean)[0]
|
||||||
|
|
||||||
|
/** Public URL of the web app, used to build links inside emails. */
|
||||||
|
export const webAppUrl = configured || corsOrigin || 'http://localhost:7153'
|
||||||
|
|
||||||
|
/** Deep link the invited user opens to accept an invitation. */
|
||||||
|
export function invitationUrl(token: string): string {
|
||||||
|
return `${webAppUrl}/invitations/${token}`
|
||||||
|
}
|
||||||
32
apps/api/src/modules/invitations/accept/route.ts
Normal file
32
apps/api/src/modules/invitations/accept/route.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { AcceptInvitation } from './use-case'
|
||||||
|
|
||||||
|
const TokenParamSchema = z.object({
|
||||||
|
token: z.uuid('El identificador de la invitación no es válido'),
|
||||||
|
})
|
||||||
|
|
||||||
|
/** POST /invitations/:token/accept — accepts an invitation for the signed-in user. */
|
||||||
|
export const acceptInvitationRoute = new Hono<AppEnv>().post(
|
||||||
|
'/:token/accept',
|
||||||
|
requireSession,
|
||||||
|
validate.param(TokenParamSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { token } = c.req.valid('param')
|
||||||
|
const user = c.get('user')
|
||||||
|
const result = await new AcceptInvitation(prisma).execute({
|
||||||
|
token,
|
||||||
|
userId: user.id,
|
||||||
|
email: user.email,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
133
apps/api/src/modules/invitations/accept/use-case.test.ts
Normal file
133
apps/api/src/modules/invitations/accept/use-case.test.ts
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { AcceptInvitation } from './use-case'
|
||||||
|
|
||||||
|
const NOW = new Date('2026-10-15T00:00:00.000Z')
|
||||||
|
|
||||||
|
const INVITATION = {
|
||||||
|
id: 'inv-1',
|
||||||
|
listId: 'list-1',
|
||||||
|
email: 'beto@ejemplo.com',
|
||||||
|
status: 'pending',
|
||||||
|
expiresAt: new Date('2026-10-20T00:00:00.000Z'),
|
||||||
|
list: { id: 'list-1', name: 'Compra semanal' },
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDb({
|
||||||
|
invitation,
|
||||||
|
membership = null,
|
||||||
|
}: {
|
||||||
|
invitation?: typeof INVITATION
|
||||||
|
membership?: unknown
|
||||||
|
}) {
|
||||||
|
const updates: unknown[] = []
|
||||||
|
const created: unknown[] = []
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListInvitation: {
|
||||||
|
findUnique: async () => invitation,
|
||||||
|
update: async (args: unknown) => {
|
||||||
|
updates.push(args)
|
||||||
|
return args
|
||||||
|
},
|
||||||
|
},
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async () => membership,
|
||||||
|
create: async (args: unknown) => {
|
||||||
|
created.push(args)
|
||||||
|
return args
|
||||||
|
},
|
||||||
|
},
|
||||||
|
$transaction: async (operations: Promise<unknown>[]) => Promise.all(operations),
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, updates, created }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AcceptInvitation', () => {
|
||||||
|
it('answers 404 for an unknown token', async () => {
|
||||||
|
const { db } = createDb({ invitation: undefined })
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||||
|
token: 'nope',
|
||||||
|
userId: 'user-1',
|
||||||
|
email: 'beto@ejemplo.com',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects an invitation addressed to another email', async () => {
|
||||||
|
const { db, created } = createDb({ invitation: INVITATION })
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||||
|
token: INVITATION.id,
|
||||||
|
userId: 'user-1',
|
||||||
|
email: 'ana@ejemplo.com',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(403)
|
||||||
|
expect(created).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is idempotent for somebody who is already a member', async () => {
|
||||||
|
const { db, updates } = createDb({
|
||||||
|
invitation: INVITATION,
|
||||||
|
membership: { id: 'member-1' },
|
||||||
|
})
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||||
|
token: INVITATION.id,
|
||||||
|
userId: 'user-1',
|
||||||
|
email: 'beto@ejemplo.com',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
|
||||||
|
expect(updates).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 400 and marks expired invitations', async () => {
|
||||||
|
const { db, updates, created } = createDb({
|
||||||
|
invitation: {
|
||||||
|
...INVITATION,
|
||||||
|
expiresAt: new Date('2026-10-01T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||||
|
token: INVITATION.id,
|
||||||
|
userId: 'user-1',
|
||||||
|
email: 'beto@ejemplo.com',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(400)
|
||||||
|
expect(updates).toHaveLength(1)
|
||||||
|
expect(created).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('grants access and marks the invitation as accepted', async () => {
|
||||||
|
const { db, updates, created } = createDb({ invitation: INVITATION })
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW).execute({
|
||||||
|
token: INVITATION.id,
|
||||||
|
userId: 'user-1',
|
||||||
|
// Compared in lower case, so the casing of the session email does not matter.
|
||||||
|
email: 'Beto@Ejemplo.com',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
|
||||||
|
expect(created).toEqual([
|
||||||
|
{
|
||||||
|
data: { listId: 'list-1', userId: 'user-1', role: 'collaborator' },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(updates).toHaveLength(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
71
apps/api/src/modules/invitations/accept/use-case.ts
Normal file
71
apps/api/src/modules/invitations/accept/use-case.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import {
|
||||||
|
type AcceptInvitationResult,
|
||||||
|
Failure,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/** Accepts an invitation for the signed-in user, matching it by token and email. */
|
||||||
|
export class AcceptInvitation {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly now: () => Date = () => new Date(),
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
token: string
|
||||||
|
userId: string
|
||||||
|
email: string
|
||||||
|
}): Promise<Result<AcceptInvitationResult, ProblemDetails>> {
|
||||||
|
const invitation = await this.db.shoppingListInvitation.findUnique({
|
||||||
|
where: { token: input.token },
|
||||||
|
include: { list: { select: { id: true, name: true } } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!invitation) {
|
||||||
|
return Failure(problems.notFound('La invitación no existe o fue cancelada.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitation.email !== input.email.trim().toLowerCase()) {
|
||||||
|
return Failure(problems.forbidden('Esta invitación pertenece a otro correo electrónico.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: invitation.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
// Already a member (e.g. accepted at signup): idempotent success.
|
||||||
|
if (membership) {
|
||||||
|
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitation.status !== 'pending') {
|
||||||
|
return Failure(problems.conflict('Esta invitación ya no está disponible.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitation.expiresAt.getTime() < this.now().getTime()) {
|
||||||
|
await this.db.shoppingListInvitation.update({
|
||||||
|
where: { id: invitation.id },
|
||||||
|
data: { status: 'expired' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return Failure(problems.badRequest('Esta invitación ha expirado.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.db.$transaction([
|
||||||
|
this.db.shoppingListMember.create({
|
||||||
|
data: { listId: invitation.listId, userId: input.userId, role: 'collaborator' },
|
||||||
|
}),
|
||||||
|
this.db.shoppingListInvitation.update({
|
||||||
|
where: { id: invitation.id },
|
||||||
|
data: { status: 'accepted', acceptedAt: this.now() },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
|
||||||
|
}
|
||||||
|
}
|
||||||
27
apps/api/src/modules/invitations/create/route.ts
Normal file
27
apps/api/src/modules/invitations/create/route.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { CreateInvitationSchema } from './schema'
|
||||||
|
import { CreateInvitation } from './use-case'
|
||||||
|
|
||||||
|
/** POST /invitations — invites an email address to a list. */
|
||||||
|
export const createInvitationRoute = new Hono<AppEnv>().post(
|
||||||
|
'/',
|
||||||
|
requireSession,
|
||||||
|
validate.json(CreateInvitationSchema),
|
||||||
|
async (c) => {
|
||||||
|
const body = c.req.valid('json')
|
||||||
|
const result = await new CreateInvitation(prisma).execute({
|
||||||
|
listId: body.listId,
|
||||||
|
email: body.email,
|
||||||
|
invitedById: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 201 })
|
||||||
|
},
|
||||||
|
)
|
||||||
9
apps/api/src/modules/invitations/create/schema.ts
Normal file
9
apps/api/src/modules/invitations/create/schema.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `POST /invitations`. */
|
||||||
|
export const CreateInvitationSchema = z.object({
|
||||||
|
listId: z.uuid('El identificador de la lista no es válido'),
|
||||||
|
email: z.email('Introduce un correo electrónico válido'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type CreateInvitationInput = z.infer<typeof CreateInvitationSchema>
|
||||||
154
apps/api/src/modules/invitations/create/use-case.ts
Normal file
154
apps/api/src/modules/invitations/create/use-case.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
|
||||||
|
import {
|
||||||
|
type CreateInvitationResult,
|
||||||
|
Failure,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { invitationEmail } from '@/lib/emails/invitation'
|
||||||
|
import { logger } from '@/lib/logger'
|
||||||
|
import { type Email, sendEmail } from '@/lib/mailer'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
import { invitationUrl } from '@/lib/web-app-url'
|
||||||
|
|
||||||
|
/** Invitations expire after seven days. */
|
||||||
|
const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
type Mailer = (email: Email) => Promise<void>
|
||||||
|
|
||||||
|
type CreateInvitationDependencies = {
|
||||||
|
mailer?: Mailer
|
||||||
|
now?: () => Date
|
||||||
|
generateToken?: () => string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invites an email address to collaborate on a list.
|
||||||
|
*
|
||||||
|
* - If the email already has an account, membership is granted immediately so
|
||||||
|
* the list shows up the next time they sign in.
|
||||||
|
* - Otherwise a `pending` invitation is stored and the accept link is emailed.
|
||||||
|
*/
|
||||||
|
export class CreateInvitation {
|
||||||
|
private readonly mailer: Mailer
|
||||||
|
private readonly now: () => Date
|
||||||
|
private readonly generateToken: () => string
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
dependencies: CreateInvitationDependencies = {},
|
||||||
|
) {
|
||||||
|
this.mailer = dependencies.mailer ?? sendEmail
|
||||||
|
this.now = dependencies.now ?? (() => new Date())
|
||||||
|
this.generateToken = dependencies.generateToken ?? (() => randomUUID())
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
email: string
|
||||||
|
invitedById: string
|
||||||
|
}): Promise<Result<CreateInvitationResult, ProblemDetails>> {
|
||||||
|
const email = input.email.trim().toLowerCase()
|
||||||
|
|
||||||
|
const inviterMembership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.invitedById } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!inviterMembership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inviterMembership.role !== 'owner') {
|
||||||
|
return Failure(problems.forbidden('Solo el propietario puede invitar colaboradores.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await this.db.shoppingList.findUnique({
|
||||||
|
where: { id: input.listId },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!list) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const invitedUser = await this.db.user.findUnique({ where: { email } })
|
||||||
|
|
||||||
|
if (invitedUser) {
|
||||||
|
const alreadyMember = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: invitedUser.id } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (alreadyMember) {
|
||||||
|
return Failure(problems.conflict('Esa persona ya colabora en la lista.'))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const pending = await this.db.shoppingListInvitation.findFirst({
|
||||||
|
where: { listId: input.listId, email, status: 'pending' },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (pending) {
|
||||||
|
return Failure(problems.conflict('Ya hay una invitación pendiente para ese correo.'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = this.generateToken()
|
||||||
|
const invitation = await this.db.shoppingListInvitation.create({
|
||||||
|
data: {
|
||||||
|
listId: input.listId,
|
||||||
|
email,
|
||||||
|
token,
|
||||||
|
invitedById: input.invitedById,
|
||||||
|
expiresAt: new Date(this.now().getTime() + INVITATION_TTL_MS),
|
||||||
|
status: invitedUser ? 'accepted' : 'pending',
|
||||||
|
acceptedAt: invitedUser ? this.now() : null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (invitedUser) {
|
||||||
|
await this.db.shoppingListMember.create({
|
||||||
|
data: { listId: input.listId, userId: invitedUser.id, role: 'collaborator' },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const inviter = await this.db.user.findUnique({
|
||||||
|
where: { id: input.invitedById },
|
||||||
|
select: { name: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const message = {
|
||||||
|
to: email,
|
||||||
|
...invitationEmail({
|
||||||
|
inviterName: inviter?.name ?? 'Alguien',
|
||||||
|
listName: list.name,
|
||||||
|
acceptUrl: invitationUrl(token),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
if (invitedUser) {
|
||||||
|
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
||||||
|
await this.mailer(message).catch((error: unknown) => {
|
||||||
|
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok({ status: 'added', email })
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.mailer(message)
|
||||||
|
} catch (error) {
|
||||||
|
// Without the email the invitee cannot know about the list: undo everything.
|
||||||
|
await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } })
|
||||||
|
logger.error({ err: error, to: email }, 'failed to send the invitation email')
|
||||||
|
|
||||||
|
return Failure(
|
||||||
|
problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok({ status: 'invited', email })
|
||||||
|
}
|
||||||
|
}
|
||||||
13
apps/api/src/modules/invitations/index.ts
Normal file
13
apps/api/src/modules/invitations/index.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { acceptInvitationRoute } from './accept/route'
|
||||||
|
import { createInvitationRoute } from './create/route'
|
||||||
|
import { listPendingInvitationsRoute } from './list-pending/route'
|
||||||
|
|
||||||
|
/** `invitations` module: every feature of the module is mounted here. */
|
||||||
|
export const invitationsModule = new Hono<AppEnv>()
|
||||||
|
.route('/', listPendingInvitationsRoute)
|
||||||
|
.route('/', createInvitationRoute)
|
||||||
|
.route('/', acceptInvitationRoute)
|
||||||
21
apps/api/src/modules/invitations/list-pending/route.ts
Normal file
21
apps/api/src/modules/invitations/list-pending/route.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListPendingInvitations } from './use-case'
|
||||||
|
|
||||||
|
/** GET /invitations/pending — pending invitations for the signed-in user. */
|
||||||
|
export const listPendingInvitationsRoute = new Hono<AppEnv>().get(
|
||||||
|
'/pending',
|
||||||
|
requireSession,
|
||||||
|
async (c) => {
|
||||||
|
const result = await new ListPendingInvitations(prisma).execute({
|
||||||
|
email: c.get('user').email,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
38
apps/api/src/modules/invitations/list-pending/use-case.ts
Normal file
38
apps/api/src/modules/invitations/list-pending/use-case.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { Ok, type PendingInvitation, type ProblemDetails, type Result } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/** Lists the still-pending invitations addressed to the signed-in user's email. */
|
||||||
|
export class ListPendingInvitations {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly now: () => Date = () => new Date(),
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(input: { email: string }): Promise<Result<PendingInvitation[], ProblemDetails>> {
|
||||||
|
const invitations = await this.db.shoppingListInvitation.findMany({
|
||||||
|
where: {
|
||||||
|
email: input.email.trim().toLowerCase(),
|
||||||
|
status: 'pending',
|
||||||
|
expiresAt: { gt: this.now() },
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
list: { select: { id: true, name: true } },
|
||||||
|
invitedBy: { select: { id: true, name: true } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
invitations.map((invitation) => ({
|
||||||
|
id: invitation.id,
|
||||||
|
email: invitation.email,
|
||||||
|
status: invitation.status,
|
||||||
|
expiresAt: invitation.expiresAt.toISOString(),
|
||||||
|
createdAt: invitation.createdAt.toISOString(),
|
||||||
|
list: { id: invitation.list.id, name: invitation.list.name },
|
||||||
|
invitedBy: { id: invitation.invitedBy.id, name: invitation.invitedBy.name },
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
26
apps/api/src/modules/lists/create/route.ts
Normal file
26
apps/api/src/modules/lists/create/route.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { CreateListSchema } from './schema'
|
||||||
|
import { CreateShoppingList } from './use-case'
|
||||||
|
|
||||||
|
/** POST /lists — creates a shopping list. */
|
||||||
|
export const createListRoute = new Hono<AppEnv>().post(
|
||||||
|
'/',
|
||||||
|
requireSession,
|
||||||
|
validate.json(CreateListSchema),
|
||||||
|
async (c) => {
|
||||||
|
const body = c.req.valid('json')
|
||||||
|
const result = await new CreateShoppingList(prisma).execute({
|
||||||
|
name: body.name,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 201 })
|
||||||
|
},
|
||||||
|
)
|
||||||
8
apps/api/src/modules/lists/create/schema.ts
Normal file
8
apps/api/src/modules/lists/create/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `POST /lists`. */
|
||||||
|
export const CreateListSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type CreateListInput = z.infer<typeof CreateListSchema>
|
||||||
84
apps/api/src/modules/lists/create/use-case.test.ts
Normal file
84
apps/api/src/modules/lists/create/use-case.test.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { CreateShoppingList } from './use-case'
|
||||||
|
|
||||||
|
type CreateInput = {
|
||||||
|
data: {
|
||||||
|
name: string
|
||||||
|
ownerId: string
|
||||||
|
members: { create: { isPrimary: boolean; userId: string; role: string } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDb({
|
||||||
|
existingMemberships,
|
||||||
|
membershipsOnCreate,
|
||||||
|
}: {
|
||||||
|
existingMemberships: number
|
||||||
|
membershipsOnCreate: number
|
||||||
|
}) {
|
||||||
|
const created: CreateInput[] = []
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: { count: async () => existingMemberships },
|
||||||
|
shoppingList: {
|
||||||
|
create: async (args: unknown) => {
|
||||||
|
const input = args as CreateInput
|
||||||
|
created.push(input)
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: 'list-1',
|
||||||
|
name: input.data.name,
|
||||||
|
createdAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-10-15T00:00:00.000Z'),
|
||||||
|
_count: { members: membershipsOnCreate },
|
||||||
|
members: [
|
||||||
|
{
|
||||||
|
id: 'member-1',
|
||||||
|
role: 'owner',
|
||||||
|
isPrimary: input.data.members.create.isPrimary,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, created }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CreateShoppingList', () => {
|
||||||
|
it('makes the first list the primary one', async () => {
|
||||||
|
const { db, created } = createDb({ existingMemberships: 0, membershipsOnCreate: 1 })
|
||||||
|
const result = await new CreateShoppingList(db).execute({
|
||||||
|
name: 'Compra semanal',
|
||||||
|
userId: 'user-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
|
expect(created[0]?.data.members.create.isPrimary).toBe(true)
|
||||||
|
expect(result.value).toEqual({
|
||||||
|
id: 'list-1',
|
||||||
|
name: 'Compra semanal',
|
||||||
|
role: 'owner',
|
||||||
|
isPrimary: true,
|
||||||
|
memberCount: 1,
|
||||||
|
createdAt: '2026-10-15T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-10-15T00:00:00.000Z',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not steal the primary flag from an existing list', async () => {
|
||||||
|
const { db, created } = createDb({ existingMemberships: 3, membershipsOnCreate: 4 })
|
||||||
|
const result = await new CreateShoppingList(db).execute({
|
||||||
|
name: 'Otra lista',
|
||||||
|
userId: 'user-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
expect(created[0]?.data.members.create.isPrimary).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
57
apps/api/src/modules/lists/create/use-case.ts
Normal file
57
apps/api/src/modules/lists/create/use-case.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { toSummary } from '../serialize'
|
||||||
|
|
||||||
|
/** Creates a shopping list owned by the user. The first list becomes primary. */
|
||||||
|
export class CreateShoppingList {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
name: string
|
||||||
|
userId: string
|
||||||
|
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
|
||||||
|
const existingCount = await this.db.shoppingListMember.count({
|
||||||
|
where: { userId: input.userId },
|
||||||
|
})
|
||||||
|
|
||||||
|
const list = await this.db.shoppingList.create({
|
||||||
|
data: {
|
||||||
|
name: input.name,
|
||||||
|
ownerId: input.userId,
|
||||||
|
members: {
|
||||||
|
create: {
|
||||||
|
userId: input.userId,
|
||||||
|
role: 'owner',
|
||||||
|
isPrimary: existingCount === 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
_count: { select: { members: true } },
|
||||||
|
members: { where: { userId: input.userId } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const membership = list.members[0]
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
throw new Error('Membership was not created for the new list')
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
toSummary({
|
||||||
|
role: membership.role,
|
||||||
|
isPrimary: membership.isPrimary,
|
||||||
|
list: {
|
||||||
|
id: list.id,
|
||||||
|
name: list.name,
|
||||||
|
createdAt: list.createdAt,
|
||||||
|
updatedAt: list.updatedAt,
|
||||||
|
_count: list._count,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
26
apps/api/src/modules/lists/get/route.ts
Normal file
26
apps/api/src/modules/lists/get/route.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListParamsSchema } from '../schema'
|
||||||
|
import { GetShoppingList } from './use-case'
|
||||||
|
|
||||||
|
/** GET /lists/:listId — list detail with its members. */
|
||||||
|
export const getListRoute = new Hono<AppEnv>().get(
|
||||||
|
'/:listId',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const result = await new GetShoppingList(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
46
apps/api/src/modules/lists/get/use-case.ts
Normal file
46
apps/api/src/modules/lists/get/use-case.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import {
|
||||||
|
Failure,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
type ShoppingListDetail,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { toDetail } from '../serialize'
|
||||||
|
|
||||||
|
/** Returns a list with its members. Only members can read it. */
|
||||||
|
export class GetShoppingList {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
userId: string
|
||||||
|
}): Promise<Result<ShoppingListDetail, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
include: {
|
||||||
|
list: {
|
||||||
|
include: {
|
||||||
|
members: {
|
||||||
|
include: { user: true },
|
||||||
|
orderBy: [{ role: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
},
|
||||||
|
invitations: {
|
||||||
|
where: { status: 'pending' },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(toDetail(membership))
|
||||||
|
}
|
||||||
|
}
|
||||||
19
apps/api/src/modules/lists/index.ts
Normal file
19
apps/api/src/modules/lists/index.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { createListRoute } from './create/route'
|
||||||
|
import { getListRoute } from './get/route'
|
||||||
|
import { listItemsModule } from './items'
|
||||||
|
import { listListsRoute } from './list/route'
|
||||||
|
import { setPrimaryListRoute } from './set-primary/route'
|
||||||
|
import { updateListRoute } from './update/route'
|
||||||
|
|
||||||
|
/** `lists` module: every feature of the module is mounted here. */
|
||||||
|
export const listsModule = new Hono<AppEnv>()
|
||||||
|
.route('/', listListsRoute)
|
||||||
|
.route('/', createListRoute)
|
||||||
|
.route('/', getListRoute)
|
||||||
|
.route('/', updateListRoute)
|
||||||
|
.route('/', setPrimaryListRoute)
|
||||||
|
.route('/:listId/items', listItemsModule)
|
||||||
32
apps/api/src/modules/lists/items/create/route.ts
Normal file
32
apps/api/src/modules/lists/items/create/route.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import { ListParamsSchema } from '@/modules/lists/schema'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { CreateItemSchema } from './schema'
|
||||||
|
import { CreateItem } from './use-case'
|
||||||
|
|
||||||
|
/** POST /lists/:listId/items — adds an item to a list the user belongs to. */
|
||||||
|
export const createItemRoute = new Hono<AppEnv>().post(
|
||||||
|
'/',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
validate.json(CreateItemSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const body = c.req.valid('json')
|
||||||
|
const result = await new CreateItem(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
name: body.name,
|
||||||
|
quantity: body.quantity,
|
||||||
|
notes: body.notes,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 201 })
|
||||||
|
},
|
||||||
|
)
|
||||||
10
apps/api/src/modules/lists/items/create/schema.ts
Normal file
10
apps/api/src/modules/lists/items/create/schema.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `POST /lists/:listId/items`. */
|
||||||
|
export const CreateItemSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(120, 'Máximo 120 caracteres'),
|
||||||
|
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').optional(),
|
||||||
|
notes: z.string().trim().max(280, 'Máximo 280 caracteres').optional(),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type CreateItemInput = z.infer<typeof CreateItemSchema>
|
||||||
44
apps/api/src/modules/lists/items/create/use-case.ts
Normal file
44
apps/api/src/modules/lists/items/create/use-case.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import {
|
||||||
|
Failure,
|
||||||
|
type ListItem,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { toListItem } from '../serialize'
|
||||||
|
|
||||||
|
/** Adds an item to a shopping list. Only members can add items. */
|
||||||
|
export class CreateItem {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
userId: string
|
||||||
|
name: string
|
||||||
|
quantity?: string
|
||||||
|
notes?: string
|
||||||
|
}): Promise<Result<ListItem, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.db.listItem.create({
|
||||||
|
data: {
|
||||||
|
shoppingListId: input.listId,
|
||||||
|
name: input.name,
|
||||||
|
quantity: input.quantity || null,
|
||||||
|
notes: input.notes || null,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok(toListItem(item))
|
||||||
|
}
|
||||||
|
}
|
||||||
11
apps/api/src/modules/lists/items/index.ts
Normal file
11
apps/api/src/modules/lists/items/index.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { createItemRoute } from './create/route'
|
||||||
|
import { listItemsRoute } from './list/route'
|
||||||
|
|
||||||
|
/** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */
|
||||||
|
export const listItemsModule = new Hono<AppEnv>()
|
||||||
|
.route('/', listItemsRoute)
|
||||||
|
.route('/', createItemRoute)
|
||||||
26
apps/api/src/modules/lists/items/list/route.ts
Normal file
26
apps/api/src/modules/lists/items/list/route.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import { ListParamsSchema } from '@/modules/lists/schema'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListItems } from './use-case'
|
||||||
|
|
||||||
|
/** GET /lists/:listId/items — every item of a list the user belongs to. */
|
||||||
|
export const listItemsRoute = new Hono<AppEnv>().get(
|
||||||
|
'/',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const result = await new ListItems(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
34
apps/api/src/modules/lists/items/list/use-case.ts
Normal file
34
apps/api/src/modules/lists/items/list/use-case.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import type { ListItem, ProblemDetails, Result } from '@superlist/shared'
|
||||||
|
import { Failure, Ok, problems } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { toListItem } from '../serialize'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lists every item of a shopping list, pending ones first.
|
||||||
|
* Only members of the list can read it.
|
||||||
|
*/
|
||||||
|
export class ListItems {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
userId: string
|
||||||
|
}): Promise<Result<ListItem[], ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = await this.db.listItem.findMany({
|
||||||
|
where: { shoppingListId: input.listId },
|
||||||
|
orderBy: [{ completed: 'asc' }, { order: 'asc' }, { createdAt: 'asc' }],
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok(items.map(toListItem))
|
||||||
|
}
|
||||||
|
}
|
||||||
28
apps/api/src/modules/lists/items/serialize.ts
Normal file
28
apps/api/src/modules/lists/items/serialize.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
|
||||||
|
type ItemRow = {
|
||||||
|
id: string
|
||||||
|
shoppingListId: string
|
||||||
|
name: string
|
||||||
|
completed: boolean
|
||||||
|
quantity: string | null
|
||||||
|
notes: string | null
|
||||||
|
order: number
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Maps a `ListItem` row to the DTO shared with the web app. */
|
||||||
|
export function toListItem(item: ItemRow): ListItem {
|
||||||
|
return {
|
||||||
|
id: item.id,
|
||||||
|
listId: item.shoppingListId,
|
||||||
|
name: item.name,
|
||||||
|
completed: item.completed,
|
||||||
|
quantity: item.quantity,
|
||||||
|
notes: item.notes,
|
||||||
|
order: item.order,
|
||||||
|
createdAt: item.createdAt.toISOString(),
|
||||||
|
updatedAt: item.updatedAt.toISOString(),
|
||||||
|
}
|
||||||
|
}
|
||||||
15
apps/api/src/modules/lists/list/route.ts
Normal file
15
apps/api/src/modules/lists/list/route.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListShoppingLists } from './use-case'
|
||||||
|
|
||||||
|
/** GET /lists — every list the signed-in user belongs to. */
|
||||||
|
export const listListsRoute = new Hono<AppEnv>().get('/', requireSession, async (c) => {
|
||||||
|
const result = await new ListShoppingLists(prisma).execute({ userId: c.get('user').id })
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
})
|
||||||
28
apps/api/src/modules/lists/list/use-case.ts
Normal file
28
apps/api/src/modules/lists/list/use-case.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/** Lists every shopping list the user belongs to (owned or shared). */
|
||||||
|
export class ListShoppingLists {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: { userId: string }): Promise<Result<ShoppingListSummary[], ProblemDetails>> {
|
||||||
|
const memberships = await this.db.shoppingListMember.findMany({
|
||||||
|
where: { userId: input.userId },
|
||||||
|
include: { list: { include: { _count: { select: { members: true } } } } },
|
||||||
|
orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }],
|
||||||
|
})
|
||||||
|
|
||||||
|
const lists = memberships.map((membership) => ({
|
||||||
|
id: membership.list.id,
|
||||||
|
name: membership.list.name,
|
||||||
|
role: membership.role,
|
||||||
|
isPrimary: membership.isPrimary,
|
||||||
|
memberCount: membership.list._count.members,
|
||||||
|
createdAt: membership.list.createdAt.toISOString(),
|
||||||
|
updatedAt: membership.list.updatedAt.toISOString(),
|
||||||
|
}))
|
||||||
|
|
||||||
|
return Ok(lists)
|
||||||
|
}
|
||||||
|
}
|
||||||
8
apps/api/src/modules/lists/schema.ts
Normal file
8
apps/api/src/modules/lists/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Path params shared by the list features: `/:listId`. */
|
||||||
|
export const ListParamsSchema = z.object({
|
||||||
|
listId: z.uuid('El identificador de la lista no es válido'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type ListParams = z.infer<typeof ListParamsSchema>
|
||||||
79
apps/api/src/modules/lists/serialize.ts
Normal file
79
apps/api/src/modules/lists/serialize.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared'
|
||||||
|
|
||||||
|
type ListRow = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
createdAt: Date
|
||||||
|
updatedAt: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
type MemberRow = {
|
||||||
|
role: 'owner' | 'collaborator'
|
||||||
|
isPrimary: boolean
|
||||||
|
list: ListRow & { _count: { members: number } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Maps a membership (with its list and member count) to the summary DTO. */
|
||||||
|
export function toSummary(member: MemberRow): ShoppingListSummary {
|
||||||
|
return {
|
||||||
|
id: member.list.id,
|
||||||
|
name: member.list.name,
|
||||||
|
role: member.role,
|
||||||
|
isPrimary: member.isPrimary,
|
||||||
|
memberCount: member.list._count.members,
|
||||||
|
createdAt: member.list.createdAt.toISOString(),
|
||||||
|
updatedAt: member.list.updatedAt.toISOString(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type DetailRow = {
|
||||||
|
role: 'owner' | 'collaborator'
|
||||||
|
isPrimary: boolean
|
||||||
|
list: ListRow & {
|
||||||
|
members: Array<{
|
||||||
|
id: string
|
||||||
|
role: 'owner' | 'collaborator'
|
||||||
|
isPrimary: boolean
|
||||||
|
user: { id: string; name: string; email: string; image: string | null }
|
||||||
|
}>
|
||||||
|
invitations: Array<{
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
status: 'pending' | 'accepted' | 'revoked' | 'expired'
|
||||||
|
expiresAt: Date
|
||||||
|
createdAt: Date
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Maps a membership (with its list and members) to the detail DTO. */
|
||||||
|
export function toDetail(member: DetailRow): ShoppingListDetail {
|
||||||
|
const members: ListMember[] = member.list.members.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
role: row.role,
|
||||||
|
isPrimary: row.isPrimary,
|
||||||
|
user: {
|
||||||
|
id: row.user.id,
|
||||||
|
name: row.user.name,
|
||||||
|
email: row.user.email,
|
||||||
|
image: row.user.image,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: member.list.id,
|
||||||
|
name: member.list.name,
|
||||||
|
role: member.role,
|
||||||
|
isPrimary: member.isPrimary,
|
||||||
|
members,
|
||||||
|
invitations: member.list.invitations.map((invitation) => ({
|
||||||
|
id: invitation.id,
|
||||||
|
email: invitation.email,
|
||||||
|
status: invitation.status,
|
||||||
|
expiresAt: invitation.expiresAt.toISOString(),
|
||||||
|
createdAt: invitation.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
createdAt: member.list.createdAt.toISOString(),
|
||||||
|
updatedAt: member.list.updatedAt.toISOString(),
|
||||||
|
}
|
||||||
|
}
|
||||||
26
apps/api/src/modules/lists/set-primary/route.ts
Normal file
26
apps/api/src/modules/lists/set-primary/route.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListParamsSchema } from '../schema'
|
||||||
|
import { SetPrimaryList } from './use-case'
|
||||||
|
|
||||||
|
/** POST /lists/:listId/primary — marks the list as the user's primary one. */
|
||||||
|
export const setPrimaryListRoute = new Hono<AppEnv>().post(
|
||||||
|
'/:listId/primary',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const result = await new SetPrimaryList(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 204 })
|
||||||
|
},
|
||||||
|
)
|
||||||
65
apps/api/src/modules/lists/set-primary/use-case.test.ts
Normal file
65
apps/api/src/modules/lists/set-primary/use-case.test.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { SetPrimaryList } from './use-case'
|
||||||
|
|
||||||
|
function createDb(membership: unknown) {
|
||||||
|
const calls: { cleared: unknown[]; marked: unknown[] } = { cleared: [], marked: [] }
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async () => membership,
|
||||||
|
updateMany: async (args: unknown) => {
|
||||||
|
calls.cleared.push(args)
|
||||||
|
return { count: 1 }
|
||||||
|
},
|
||||||
|
update: async (args: unknown) => {
|
||||||
|
calls.marked.push(args)
|
||||||
|
return args
|
||||||
|
},
|
||||||
|
},
|
||||||
|
$transaction: async (operations: Promise<unknown>[]) => Promise.all(operations),
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, calls }
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SetPrimaryList', () => {
|
||||||
|
it('answers 404 when the user does not belong to the list', async () => {
|
||||||
|
const { db, calls } = createDb(null)
|
||||||
|
const result = await new SetPrimaryList(db).execute({
|
||||||
|
listId: 'list-1',
|
||||||
|
userId: 'user-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(calls.cleared).toHaveLength(0)
|
||||||
|
expect(calls.marked).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clears the previous primary list and marks the new one', async () => {
|
||||||
|
const { db, calls } = createDb({ isPrimary: false })
|
||||||
|
const result = await new SetPrimaryList(db).execute({
|
||||||
|
listId: 'list-2',
|
||||||
|
userId: 'user-1',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
|
||||||
|
expect(calls.cleared).toEqual([
|
||||||
|
{
|
||||||
|
where: { userId: 'user-1', isPrimary: true, listId: { not: 'list-2' } },
|
||||||
|
data: { isPrimary: false },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
expect(calls.marked).toEqual([
|
||||||
|
{
|
||||||
|
where: { listId_userId: { listId: 'list-2', userId: 'user-1' } },
|
||||||
|
data: { isPrimary: true },
|
||||||
|
},
|
||||||
|
])
|
||||||
|
})
|
||||||
|
})
|
||||||
31
apps/api/src/modules/lists/set-primary/use-case.ts
Normal file
31
apps/api/src/modules/lists/set-primary/use-case.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/** Marks one list as the user's primary list (per user, not per list). */
|
||||||
|
export class SetPrimaryList {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: { listId: string; userId: string }): Promise<Result<void, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.db.$transaction([
|
||||||
|
this.db.shoppingListMember.updateMany({
|
||||||
|
where: { userId: input.userId, isPrimary: true, listId: { not: input.listId } },
|
||||||
|
data: { isPrimary: false },
|
||||||
|
}),
|
||||||
|
this.db.shoppingListMember.update({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
data: { isPrimary: true },
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
return Ok(undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
30
apps/api/src/modules/lists/update/route.ts
Normal file
30
apps/api/src/modules/lists/update/route.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ListParamsSchema } from '../schema'
|
||||||
|
import { UpdateListSchema } from './schema'
|
||||||
|
import { UpdateShoppingList } from './use-case'
|
||||||
|
|
||||||
|
/** PATCH /lists/:listId — renames a list (owner only). */
|
||||||
|
export const updateListRoute = new Hono<AppEnv>().patch(
|
||||||
|
'/:listId',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ListParamsSchema),
|
||||||
|
validate.json(UpdateListSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId } = c.req.valid('param')
|
||||||
|
const body = c.req.valid('json')
|
||||||
|
const result = await new UpdateShoppingList(prisma).execute({
|
||||||
|
listId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
name: body.name,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result)
|
||||||
|
},
|
||||||
|
)
|
||||||
8
apps/api/src/modules/lists/update/schema.ts
Normal file
8
apps/api/src/modules/lists/update/schema.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/** Body of `PATCH /lists/:listId`. */
|
||||||
|
export const UpdateListSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export type UpdateListInput = z.infer<typeof UpdateListSchema>
|
||||||
49
apps/api/src/modules/lists/update/use-case.ts
Normal file
49
apps/api/src/modules/lists/update/use-case.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import {
|
||||||
|
Failure,
|
||||||
|
Ok,
|
||||||
|
type ProblemDetails,
|
||||||
|
problems,
|
||||||
|
type Result,
|
||||||
|
type ShoppingListSummary,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||||
|
export class UpdateShoppingList {
|
||||||
|
constructor(private readonly db: Database) {}
|
||||||
|
|
||||||
|
async execute(input: {
|
||||||
|
listId: string
|
||||||
|
userId: string
|
||||||
|
name: string
|
||||||
|
}): Promise<Result<ShoppingListSummary, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (membership.role !== 'owner') {
|
||||||
|
return Failure(problems.forbidden('Solo el propietario puede renombrar la lista.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await this.db.shoppingList.update({
|
||||||
|
where: { id: input.listId },
|
||||||
|
data: { name: input.name },
|
||||||
|
include: { _count: { select: { members: true } } },
|
||||||
|
})
|
||||||
|
|
||||||
|
return Ok({
|
||||||
|
id: list.id,
|
||||||
|
name: list.name,
|
||||||
|
role: membership.role,
|
||||||
|
isPrimary: membership.isPrimary,
|
||||||
|
memberCount: list._count.members,
|
||||||
|
createdAt: list.createdAt.toISOString(),
|
||||||
|
updatedAt: list.updatedAt.toISOString(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,25 @@
|
|||||||
import type { Logger } from '@/lib/logger'
|
import type { Logger } from '@/lib/logger'
|
||||||
|
|
||||||
/** Hono environment shared by every route: `c.get('logger')`, `c.get('requestId')`. */
|
/** Authenticated user attached to a request by the `requireSession` middleware. */
|
||||||
|
export type SessionUser = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
image?: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Authenticated session attached to a request by the `requireSession` middleware. */
|
||||||
|
export type SessionContext = {
|
||||||
|
id: string
|
||||||
|
userId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hono environment shared by every route: `c.get('logger')`, `c.get('requestId')`, … */
|
||||||
export type AppEnv = {
|
export type AppEnv = {
|
||||||
Variables: {
|
Variables: {
|
||||||
logger: Logger
|
logger: Logger
|
||||||
requestId: string
|
requestId: string
|
||||||
|
user: SessionUser
|
||||||
|
session: SessionContext
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,34 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="es">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta
|
||||||
<title>Superlist</title>
|
name="viewport"
|
||||||
|
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
|
||||||
|
/>
|
||||||
|
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
|
||||||
|
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#0a0a0a" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="Superlist" />
|
||||||
|
<title>Superlist — Listas de compras compartidas</title>
|
||||||
|
<script>
|
||||||
|
// Applies the stored theme (or the OS one) before the first paint. It has
|
||||||
|
// to run in the HTML, outside React: React never executes scripts it
|
||||||
|
// renders on the client. Keep in sync with `theme-provider.tsx`.
|
||||||
|
(() => {
|
||||||
|
var stored = null
|
||||||
|
try {
|
||||||
|
stored = localStorage.getItem('superlist-theme')
|
||||||
|
} catch {}
|
||||||
|
var dark =
|
||||||
|
stored === 'dark' || (stored !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches)
|
||||||
|
document.documentElement.classList.toggle('dark', dark)
|
||||||
|
document.documentElement.style.colorScheme = dark ? 'dark' : 'light'
|
||||||
|
})()
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -25,7 +25,6 @@
|
|||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cn": "^0.4.0",
|
"cn": "^0.4.0",
|
||||||
"lucide-react": "^1.55.0",
|
"lucide-react": "^1.55.0",
|
||||||
"next-themes": "^0.4.6",
|
|
||||||
"radix-ui": "^1.8.0",
|
"radix-ui": "^1.8.0",
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.8",
|
"react-dom": "^19.2.8",
|
||||||
|
|||||||
55
apps/web/src/components/items/create-item-form.tsx
Normal file
55
apps/web/src/components/items/create-item-form.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import { PlusIcon } from 'lucide-react'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Field, FieldError } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { useCreateItem } from '@/hooks/use-items'
|
||||||
|
|
||||||
|
const createItemSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'Escribe un artículo').max(120, 'Máximo 120 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||||
|
|
||||||
|
type CreateItemFormProps = {
|
||||||
|
listId: string
|
||||||
|
/** Focus the input when the form mounts, so the user can type right away. */
|
||||||
|
autoFocus?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Input to add an item to a list. Submits with Enter or the button. */
|
||||||
|
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
|
||||||
|
const createItem = useCreateItem(listId)
|
||||||
|
|
||||||
|
const form = useForm<CreateItemValues>({
|
||||||
|
resolver: zodResolver(createItemSchema),
|
||||||
|
defaultValues: { name: '' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
createItem.mutate(values, { onSuccess: () => form.reset() })
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={onSubmit} className="flex items-start gap-2">
|
||||||
|
<Field className="flex-1" data-invalid={!!form.formState.errors.name}>
|
||||||
|
<Input
|
||||||
|
aria-label="Nuevo artículo"
|
||||||
|
autoComplete="off"
|
||||||
|
placeholder="Añade un artículo…"
|
||||||
|
autoFocus={autoFocus}
|
||||||
|
{...form.register('name')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Button type="submit" disabled={createItem.isPending}>
|
||||||
|
<PlusIcon />
|
||||||
|
{createItem.isPending ? 'Agregando…' : 'Agregar'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
93
apps/web/src/components/items/item-list.tsx
Normal file
93
apps/web/src/components/items/item-list.tsx
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import { CheckIcon, ShoppingBasketIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { useItems } from '@/hooks/use-items'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type ItemListProps = {
|
||||||
|
listId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Items loaded from the API, pending ones first. */
|
||||||
|
export function ItemList({ listId }: ItemListProps) {
|
||||||
|
const { data: items, isPending, error } = useItems(listId)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertTitle>No pudimos cargar los artículos</AlertTitle>
|
||||||
|
<AlertDescription>
|
||||||
|
{error instanceof ApiError
|
||||||
|
? (error.problem.detail ?? error.problem.title)
|
||||||
|
: 'Inténtalo de nuevo en unos segundos.'}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (items.length === 0) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
|
||||||
|
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
|
||||||
|
<ShoppingBasketIcon className="size-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">La lista está vacía</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Usa el campo de arriba para añadir tu primer artículo.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="flex flex-col gap-2">
|
||||||
|
{items.map((item) => (
|
||||||
|
<li key={item.id}>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex items-center gap-3 p-3">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'flex size-5 shrink-0 items-center justify-center rounded-full border',
|
||||||
|
item.completed
|
||||||
|
? 'bg-primary text-primary-foreground border-primary'
|
||||||
|
: 'border-muted-foreground/40 text-transparent',
|
||||||
|
)}
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3" />
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'min-w-0 flex-1 truncate',
|
||||||
|
item.completed && 'text-muted-foreground line-through',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</span>
|
||||||
|
{item.quantity && (
|
||||||
|
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,34 +1,35 @@
|
|||||||
import { useRouterState } from '@tanstack/react-router'
|
import { useRouterState } from '@tanstack/react-router'
|
||||||
import { SearchIcon } from 'lucide-react'
|
import { SearchIcon } from 'lucide-react'
|
||||||
|
|
||||||
import { ThemeToggle } from '@/components/theme-toggle'
|
import { ThemeToggle } from '@/components/theme-toggle'
|
||||||
import { Separator } from '@/components/ui/separator'
|
import { Separator } from '@/components/ui/separator'
|
||||||
import { SidebarTrigger } from '@/components/ui/sidebar'
|
import { SidebarTrigger } from '@/components/ui/sidebar'
|
||||||
|
|
||||||
function usePageTitle() {
|
function titleFor(pathname: string) {
|
||||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
if (pathname === '/') return 'Panel'
|
||||||
|
if (pathname.startsWith('/lists')) return 'Listas'
|
||||||
if (pathname === '/') return 'Dashboard'
|
if (pathname.startsWith('/tasks')) return 'Tareas'
|
||||||
|
if (pathname.startsWith('/settings')) return 'Ajustes'
|
||||||
const segment = pathname.split('/').filter(Boolean).at(0) ?? ''
|
return 'Superlist'
|
||||||
return segment.charAt(0).toUpperCase() + segment.slice(1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AppHeader() {
|
export function AppHeader() {
|
||||||
const title = usePageTitle()
|
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||||
|
const title = titleFor(pathname)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
|
<header className="bg-background/95 supports-[backdrop-filter]:bg-background/60 sticky top-0 z-10 flex h-16 shrink-0 items-center gap-2 border-b backdrop-blur">
|
||||||
<div className="flex w-full items-center gap-2 px-4">
|
<div className="flex w-full items-center gap-2 px-4">
|
||||||
<SidebarTrigger className="-ml-1" />
|
<SidebarTrigger className="-ml-1" />
|
||||||
<Separator orientation="vertical" className="mr-2 h-4" />
|
<Separator orientation="vertical" className="mr-2 h-4" />
|
||||||
<h1 className="text-sm font-medium">{title}</h1>
|
<h1 className="truncate text-sm font-medium">{title}</h1>
|
||||||
<div className="ml-auto flex items-center gap-1">
|
<div className="ml-auto flex items-center gap-1">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground mr-1 hidden items-center gap-2 rounded-md border px-3 py-1.5 text-xs md:flex"
|
className="text-muted-foreground hover:bg-accent hover:text-accent-foreground mr-1 hidden items-center gap-2 rounded-md border px-3 py-1.5 text-xs md:flex"
|
||||||
>
|
>
|
||||||
<SearchIcon className="size-3.5" />
|
<SearchIcon className="size-3.5" />
|
||||||
Search
|
Buscar
|
||||||
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]">
|
<kbd className="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-[10px]">
|
||||||
⌘K
|
⌘K
|
||||||
</kbd>
|
</kbd>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Link, useRouterState } from '@tanstack/react-router'
|
import { Link, useRouterState } from '@tanstack/react-router'
|
||||||
import type { LucideIcon } from 'lucide-react'
|
import type { LucideIcon } from 'lucide-react'
|
||||||
import { LayoutDashboardIcon, ListTodoIcon, SettingsIcon } from 'lucide-react'
|
import { HomeIcon, ListTodoIcon, SettingsIcon, ShoppingCartIcon } from 'lucide-react'
|
||||||
|
|
||||||
import { NavUser } from '@/components/layout/nav-user'
|
import { NavUser } from '@/components/layout/nav-user'
|
||||||
import {
|
import {
|
||||||
@@ -23,11 +23,17 @@ type NavItem = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const NAV_ITEMS: NavItem[] = [
|
const NAV_ITEMS: NavItem[] = [
|
||||||
{ title: 'Dashboard', to: '/', icon: LayoutDashboardIcon },
|
{ title: 'Principal', to: '/', icon: HomeIcon },
|
||||||
{ title: 'Tasks', to: '/tasks', icon: ListTodoIcon },
|
{ title: 'Listas', to: '/lists', icon: ShoppingCartIcon },
|
||||||
{ title: 'Settings', to: '/settings', icon: SettingsIcon },
|
{ title: 'Tareas', to: '/tasks', icon: ListTodoIcon },
|
||||||
|
{ title: 'Ajustes', to: '/settings', icon: SettingsIcon },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
function isActive(pathname: string, to: string) {
|
||||||
|
if (to === '/') return pathname === '/'
|
||||||
|
return pathname === to || pathname.startsWith(`${to}/`)
|
||||||
|
}
|
||||||
|
|
||||||
export function AppSidebar() {
|
export function AppSidebar() {
|
||||||
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
const pathname = useRouterState({ select: (state) => state.location.pathname })
|
||||||
|
|
||||||
@@ -43,7 +49,7 @@ export function AppSidebar() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||||
<span className="truncate font-medium">Superlist</span>
|
<span className="truncate font-medium">Superlist</span>
|
||||||
<span className="text-muted-foreground truncate text-xs">Admin</span>
|
<span className="text-muted-foreground truncate text-xs">Listas compartidas</span>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
@@ -53,11 +59,15 @@ export function AppSidebar() {
|
|||||||
|
|
||||||
<SidebarContent>
|
<SidebarContent>
|
||||||
<SidebarGroup>
|
<SidebarGroup>
|
||||||
<SidebarGroupLabel>Platform</SidebarGroupLabel>
|
<SidebarGroupLabel>Plataforma</SidebarGroupLabel>
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{NAV_ITEMS.map((item) => (
|
{NAV_ITEMS.map((item) => (
|
||||||
<SidebarMenuItem key={item.to}>
|
<SidebarMenuItem key={item.to}>
|
||||||
<SidebarMenuButton asChild isActive={pathname === item.to} tooltip={item.title}>
|
<SidebarMenuButton
|
||||||
|
asChild
|
||||||
|
isActive={isActive(pathname, item.to)}
|
||||||
|
tooltip={item.title}
|
||||||
|
>
|
||||||
<Link to={item.to}>
|
<Link to={item.to}>
|
||||||
<item.icon />
|
<item.icon />
|
||||||
<span>{item.title}</span>
|
<span>{item.title}</span>
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export function NavUser() {
|
|||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
const user = session?.user
|
const user = session?.user
|
||||||
const name = user?.name ?? 'Signed out'
|
const name = user?.name ?? 'Sin sesión'
|
||||||
const email = user?.email ?? ''
|
const email = user?.email ?? ''
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -79,7 +79,7 @@ export function NavUser() {
|
|||||||
<DropdownMenuGroup>
|
<DropdownMenuGroup>
|
||||||
<DropdownMenuItem onClick={() => void navigate({ to: '/settings' })}>
|
<DropdownMenuItem onClick={() => void navigate({ to: '/settings' })}>
|
||||||
<UserIcon />
|
<UserIcon />
|
||||||
Account
|
Cuenta
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuGroup>
|
</DropdownMenuGroup>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
@@ -90,7 +90,7 @@ export function NavUser() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<LogOutIcon />
|
<LogOutIcon />
|
||||||
Sign out
|
Cerrar sesión
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
|
|||||||
81
apps/web/src/components/lists/create-list-form.tsx
Normal file
81
apps/web/src/components/lists/create-list-form.tsx
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { useCreateList } from '@/hooks/use-lists'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
const createListSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
type CreateListValues = z.infer<typeof createListSchema>
|
||||||
|
|
||||||
|
type CreateListFormProps = {
|
||||||
|
onCreated?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inline form to create a shopping list. Used by the lists page. */
|
||||||
|
export function CreateListForm({ onCreated }: CreateListFormProps) {
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const createList = useCreateList()
|
||||||
|
|
||||||
|
const form = useForm<CreateListValues>({
|
||||||
|
resolver: zodResolver(createListSchema),
|
||||||
|
defaultValues: { name: '' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
createList.mutate(values, {
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset()
|
||||||
|
onCreated?.()
|
||||||
|
},
|
||||||
|
onError: (mutationError) => {
|
||||||
|
setError(
|
||||||
|
mutationError instanceof ApiError
|
||||||
|
? (mutationError.problem.detail ?? mutationError.problem.title)
|
||||||
|
: 'No pudimos crear la lista.',
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!form.formState.errors.name}>
|
||||||
|
<FieldLabel htmlFor="list-name">Nombre de la lista</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="list-name"
|
||||||
|
placeholder="Compra semanal"
|
||||||
|
autoComplete="off"
|
||||||
|
{...form.register('name')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full sm:w-auto sm:self-start"
|
||||||
|
disabled={createList.isPending}
|
||||||
|
>
|
||||||
|
{createList.isPending ? 'Creando…' : 'Crear lista'}
|
||||||
|
</Button>
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
)
|
||||||
|
}
|
||||||
55
apps/web/src/components/lists/list-card.tsx
Normal file
55
apps/web/src/components/lists/list-card.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
|
import { Link } from '@tanstack/react-router'
|
||||||
|
import { SettingsIcon, StarIcon, UsersIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { useSetPrimaryList } from '@/hooks/use-lists'
|
||||||
|
|
||||||
|
type ListCardProps = {
|
||||||
|
list: ShoppingListSummary
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A single list in the lists overview. Tapping it opens the list's items. */
|
||||||
|
export function ListCard({ list }: ListCardProps) {
|
||||||
|
const setPrimary = useSetPrimaryList()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex items-center gap-1 p-4">
|
||||||
|
<Link to="/lists/$listId" params={{ listId: list.id }} className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="truncate font-medium">{list.name}</span>
|
||||||
|
{list.isPrimary && <Badge>Principal</Badge>}
|
||||||
|
</div>
|
||||||
|
<div className="text-muted-foreground mt-1 flex items-center gap-3 text-xs">
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<UsersIcon className="size-3.5" />
|
||||||
|
{list.memberCount} {list.memberCount === 1 ? 'persona' : 'personas'}
|
||||||
|
</span>
|
||||||
|
<span>{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{!list.isPrimary && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={`Marcar ${list.name} como lista principal`}
|
||||||
|
disabled={setPrimary.isPending}
|
||||||
|
onClick={() => setPrimary.mutate(list.id)}
|
||||||
|
>
|
||||||
|
<StarIcon className="size-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button variant="ghost" size="icon" aria-label={`Editar o configurar ${list.name}`} asChild>
|
||||||
|
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
|
||||||
|
<SettingsIcon className="size-4" />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,11 +1,84 @@
|
|||||||
import { ThemeProvider as NextThemesProvider } from 'next-themes'
|
import type { ReactNode } from 'react'
|
||||||
import type { ComponentProps } from 'react'
|
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
|
||||||
|
|
||||||
/** Wraps `next-themes` so the theme is toggled by a class on `<html>`. */
|
export type Theme = 'light' | 'dark' | 'system'
|
||||||
export function ThemeProvider({ children, ...props }: ComponentProps<typeof NextThemesProvider>) {
|
|
||||||
return (
|
type ResolvedTheme = Exclude<Theme, 'system'>
|
||||||
<NextThemesProvider attribute="class" enableSystem disableTransitionOnChange {...props}>
|
|
||||||
{children}
|
type ThemeContextValue = {
|
||||||
</NextThemesProvider>
|
/** The preference the user picked, `system` included. */
|
||||||
)
|
theme: Theme
|
||||||
|
/** The preference already resolved against the OS setting. */
|
||||||
|
resolvedTheme: ResolvedTheme
|
||||||
|
setTheme: (theme: Theme) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'superlist-theme'
|
||||||
|
const DARK_QUERY = '(prefers-color-scheme: dark)'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This theme handling is hand-rolled on purpose. Libraries such as `next-themes`
|
||||||
|
* avoid the pre-paint flash by rendering a `<script>` from React, but React 19
|
||||||
|
* never executes scripts rendered by components (it even logs a warning). Since
|
||||||
|
* this app is client-rendered, the flash is prevented by the static script in
|
||||||
|
* `index.html`, which runs before React mounts and uses this same storage key
|
||||||
|
* and `.dark` class.
|
||||||
|
*/
|
||||||
|
const ThemeContext = createContext<ThemeContextValue>({
|
||||||
|
theme: 'system',
|
||||||
|
resolvedTheme: 'light',
|
||||||
|
setTheme: () => {},
|
||||||
|
})
|
||||||
|
|
||||||
|
function readStoredTheme(): Theme {
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(STORAGE_KEY)
|
||||||
|
if (stored === 'light' || stored === 'dark' || stored === 'system') return stored
|
||||||
|
} catch {
|
||||||
|
// Storage can be unavailable (private mode, blocked cookies); fall back to system.
|
||||||
|
}
|
||||||
|
return 'system'
|
||||||
|
}
|
||||||
|
|
||||||
|
function systemTheme(): ResolvedTheme {
|
||||||
|
return window.matchMedia(DARK_QUERY).matches ? 'dark' : 'light'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [theme, setThemeState] = useState<Theme>(readStoredTheme)
|
||||||
|
const [systemDark, setSystemDark] = useState(() => systemTheme() === 'dark')
|
||||||
|
const resolvedTheme: ResolvedTheme = theme === 'system' ? (systemDark ? 'dark' : 'light') : theme
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const media = window.matchMedia(DARK_QUERY)
|
||||||
|
const onChange = (event: MediaQueryListEvent) => setSystemDark(event.matches)
|
||||||
|
media.addEventListener('change', onChange)
|
||||||
|
return () => media.removeEventListener('change', onChange)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement
|
||||||
|
root.classList.toggle('dark', resolvedTheme === 'dark')
|
||||||
|
root.style.colorScheme = resolvedTheme
|
||||||
|
}, [resolvedTheme])
|
||||||
|
|
||||||
|
const setTheme = useCallback((next: Theme) => {
|
||||||
|
setThemeState(next)
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(STORAGE_KEY, next)
|
||||||
|
} catch {
|
||||||
|
// Ignore storage failures: the theme still applies for this session.
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const value = useMemo(
|
||||||
|
() => ({ theme, resolvedTheme, setTheme }),
|
||||||
|
[theme, resolvedTheme, setTheme],
|
||||||
|
)
|
||||||
|
|
||||||
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTheme() {
|
||||||
|
return useContext(ThemeContext)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
||||||
import { useTheme } from 'next-themes'
|
|
||||||
|
|
||||||
|
import { useTheme } from '@/components/theme-provider'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
@@ -10,9 +10,9 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu'
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
|
||||||
const OPTIONS = [
|
const OPTIONS = [
|
||||||
{ value: 'light', label: 'Light', icon: SunIcon },
|
{ value: 'light', label: 'Claro', icon: SunIcon },
|
||||||
{ value: 'dark', label: 'Dark', icon: MoonIcon },
|
{ value: 'dark', label: 'Oscuro', icon: MoonIcon },
|
||||||
{ value: 'system', label: 'System', icon: MonitorIcon },
|
{ value: 'system', label: 'Sistema', icon: MonitorIcon },
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export function ThemeToggle() {
|
export function ThemeToggle() {
|
||||||
@@ -21,7 +21,7 @@ export function ThemeToggle() {
|
|||||||
return (
|
return (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" size="icon" aria-label="Toggle theme">
|
<Button variant="ghost" size="icon" aria-label="Cambiar tema">
|
||||||
<SunIcon className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
<SunIcon className="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
|
||||||
<MoonIcon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
<MoonIcon className="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ import {
|
|||||||
OctagonXIcon,
|
OctagonXIcon,
|
||||||
TriangleAlertIcon,
|
TriangleAlertIcon,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { useTheme } from 'next-themes'
|
|
||||||
import { Toaster as Sonner, type ToasterProps } from 'sonner'
|
import { Toaster as Sonner, type ToasterProps } from 'sonner'
|
||||||
|
import { useTheme } from '@/components/theme-provider'
|
||||||
|
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
const { theme = 'system' } = useTheme()
|
const { theme = 'system' } = useTheme()
|
||||||
|
|||||||
41
apps/web/src/hooks/use-invitations.ts
Normal file
41
apps/web/src/hooks/use-invitations.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import type {
|
||||||
|
AcceptInvitationResult,
|
||||||
|
CreateInvitationResult,
|
||||||
|
PendingInvitation,
|
||||||
|
} from '@superlist/shared'
|
||||||
|
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
import { apiFetch } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const pendingInvitationsQueryOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ['invitations', 'pending'],
|
||||||
|
queryFn: () => apiFetch<PendingInvitation[]>('/invitations/pending'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export function usePendingInvitations() {
|
||||||
|
return useQuery(pendingInvitationsQueryOptions())
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateInvitation(listId: string) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (input: { email: string }) =>
|
||||||
|
apiFetch<CreateInvitationResult>('/invitations', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ listId, email: input.email }),
|
||||||
|
}),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAcceptInvitation() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (token: string) =>
|
||||||
|
apiFetch<AcceptInvitationResult>(`/invitations/${token}/accept`, { method: 'POST' }),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
27
apps/web/src/hooks/use-items.ts
Normal file
27
apps/web/src/hooks/use-items.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import type { ListItem } from '@superlist/shared'
|
||||||
|
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
import { apiFetch } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const itemsQueryOptions = (listId: string) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ['lists', listId, 'items'],
|
||||||
|
queryFn: () => apiFetch<ListItem[]>(`/lists/${listId}/items`),
|
||||||
|
})
|
||||||
|
|
||||||
|
export function useItems(listId: string) {
|
||||||
|
return useQuery(itemsQueryOptions(listId))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateItem(listId: string) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (input: { name: string; quantity?: string; notes?: string }) =>
|
||||||
|
apiFetch<ListItem>(`/lists/${listId}/items`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
}),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
14
apps/web/src/hooks/use-list.ts
Normal file
14
apps/web/src/hooks/use-list.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import type { ShoppingListDetail } from '@superlist/shared'
|
||||||
|
import { queryOptions, useQuery } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
import { apiFetch } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const listQueryOptions = (listId: string) =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ['lists', listId],
|
||||||
|
queryFn: () => apiFetch<ShoppingListDetail>(`/lists/${listId}`),
|
||||||
|
})
|
||||||
|
|
||||||
|
export function useList(listId: string) {
|
||||||
|
return useQuery(listQueryOptions(listId))
|
||||||
|
}
|
||||||
49
apps/web/src/hooks/use-lists.ts
Normal file
49
apps/web/src/hooks/use-lists.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
|
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
import { apiFetch } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const listsQueryOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: ['lists'],
|
||||||
|
queryFn: () => apiFetch<ShoppingListSummary[]>('/lists'),
|
||||||
|
})
|
||||||
|
|
||||||
|
export function useLists() {
|
||||||
|
return useQuery(listsQueryOptions())
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCreateList() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (input: { name: string }) =>
|
||||||
|
apiFetch<ShoppingListSummary>('/lists', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
}),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRenameList(listId: string) {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (input: { name: string }) =>
|
||||||
|
apiFetch<ShoppingListSummary>(`/lists/${listId}`, {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
}),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSetPrimaryList() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: (listId: string) => apiFetch<void>(`/lists/${listId}/primary`, { method: 'POST' }),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['lists'] }),
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
@@ -12,18 +12,22 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { signIn } from '@/lib/auth-client'
|
import { signIn } from '@/lib/auth-client'
|
||||||
|
|
||||||
export const Route = createFileRoute('/(auth)/sign-in')({
|
export const Route = createFileRoute('/(auth)/sign-in')({
|
||||||
|
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
||||||
|
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||||
|
}),
|
||||||
component: SignInPage,
|
component: SignInPage,
|
||||||
})
|
})
|
||||||
|
|
||||||
const signInSchema = z.object({
|
const signInSchema = z.object({
|
||||||
email: z.email('Enter a valid email address'),
|
email: z.email('Introduce un correo electrónico válido'),
|
||||||
password: z.string().min(8, 'Passwords are at least 8 characters long'),
|
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type SignInValues = z.infer<typeof signInSchema>
|
type SignInValues = z.infer<typeof signInSchema>
|
||||||
|
|
||||||
function SignInPage() {
|
function SignInPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const { redirect } = Route.useSearch()
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
const form = useForm<SignInValues>({
|
const form = useForm<SignInValues>({
|
||||||
@@ -37,7 +41,12 @@ function SignInPage() {
|
|||||||
const { error: signInError } = await signIn.email(values)
|
const { error: signInError } = await signIn.email(values)
|
||||||
|
|
||||||
if (signInError) {
|
if (signInError) {
|
||||||
setError(signInError.message ?? 'Could not sign you in')
|
setError(signInError.message ?? 'No pudimos iniciar tu sesión')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (redirect) {
|
||||||
|
window.location.assign(redirect)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,33 +57,33 @@ function SignInPage() {
|
|||||||
<div className="flex min-h-svh items-center justify-center p-6">
|
<div className="flex min-h-svh items-center justify-center p-6">
|
||||||
<Card className="w-full max-w-sm">
|
<Card className="w-full max-w-sm">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Sign in</CardTitle>
|
<CardTitle>Iniciar sesión</CardTitle>
|
||||||
<CardDescription>Use your Superlist account to continue.</CardDescription>
|
<CardDescription>Usa tu cuenta de Superlist para continuar.</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||||
{error && (
|
{error && (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertTitle>Sign in failed</AlertTitle>
|
<AlertTitle>No pudimos iniciar tu sesión</AlertTitle>
|
||||||
<AlertDescription>{error}</AlertDescription>
|
<AlertDescription>{error}</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<FieldGroup>
|
<FieldGroup>
|
||||||
<Field data-invalid={!!form.formState.errors.email}>
|
<Field data-invalid={!!form.formState.errors.email}>
|
||||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
autoComplete="email"
|
autoComplete="email"
|
||||||
placeholder="ada@example.com"
|
placeholder="ada@ejemplo.com"
|
||||||
{...form.register('email')}
|
{...form.register('email')}
|
||||||
/>
|
/>
|
||||||
<FieldError errors={[form.formState.errors.email]} />
|
<FieldError errors={[form.formState.errors.email]} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<Field data-invalid={!!form.formState.errors.password}>
|
<Field data-invalid={!!form.formState.errors.password}>
|
||||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
id="password"
|
id="password"
|
||||||
type="password"
|
type="password"
|
||||||
@@ -85,9 +94,20 @@ function SignInPage() {
|
|||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||||
{form.formState.isSubmitting ? 'Signing in…' : 'Sign in'}
|
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
|
||||||
</Button>
|
</Button>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
|
|
||||||
|
<p className="text-muted-foreground text-center text-sm">
|
||||||
|
¿Todavía no tienes cuenta?{' '}
|
||||||
|
<Link
|
||||||
|
to="/sign-up"
|
||||||
|
search={redirect ? { redirect } : {}}
|
||||||
|
className="text-foreground font-medium underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
Crea una
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
128
apps/web/src/routes/(auth)/sign-up.tsx
Normal file
128
apps/web/src/routes/(auth)/sign-up.tsx
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { signUp } from '@/lib/auth-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/(auth)/sign-up')({
|
||||||
|
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
||||||
|
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||||
|
}),
|
||||||
|
component: SignUpPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
const signUpSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'Escribe tu nombre').max(80),
|
||||||
|
email: z.email('Introduce un correo electrónico válido'),
|
||||||
|
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
type SignUpValues = z.infer<typeof signUpSchema>
|
||||||
|
|
||||||
|
function SignUpPage() {
|
||||||
|
const navigate = useNavigate()
|
||||||
|
const { redirect } = Route.useSearch()
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
||||||
|
const form = useForm<SignUpValues>({
|
||||||
|
resolver: zodResolver(signUpSchema),
|
||||||
|
defaultValues: { name: '', email: '', password: '' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit(async (values) => {
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
const { error: signUpError } = await signUp.email(values)
|
||||||
|
|
||||||
|
if (signUpError) {
|
||||||
|
setError(signUpError.message ?? 'No pudimos crear tu cuenta')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (redirect) {
|
||||||
|
window.location.assign(redirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await navigate({ to: '/' })
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh items-center justify-center p-6">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Crear cuenta</CardTitle>
|
||||||
|
<CardDescription>Empieza a compartir tus listas de compras.</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertTitle>No pudimos crear tu cuenta</AlertTitle>
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!form.formState.errors.name}>
|
||||||
|
<FieldLabel htmlFor="name">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
autoComplete="name"
|
||||||
|
placeholder="Ada Lovelace"
|
||||||
|
{...form.register('name')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!form.formState.errors.email}>
|
||||||
|
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
placeholder="ada@ejemplo.com"
|
||||||
|
{...form.register('email')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.email]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field data-invalid={!!form.formState.errors.password}>
|
||||||
|
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
{...form.register('password')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.password]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||||
|
{form.formState.isSubmitting ? 'Creando cuenta…' : 'Crear cuenta'}
|
||||||
|
</Button>
|
||||||
|
</FieldGroup>
|
||||||
|
|
||||||
|
<p className="text-muted-foreground text-center text-sm">
|
||||||
|
¿Ya tienes cuenta?{' '}
|
||||||
|
<Link
|
||||||
|
to="/sign-in"
|
||||||
|
search={redirect ? { redirect } : {}}
|
||||||
|
className="text-foreground font-medium underline-offset-4 hover:underline"
|
||||||
|
>
|
||||||
|
Inicia sesión
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -30,7 +30,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
|||||||
|
|
||||||
function RootLayout() {
|
function RootLayout() {
|
||||||
return (
|
return (
|
||||||
<ThemeProvider defaultTheme="system" storageKey="superlist-theme">
|
<ThemeProvider>
|
||||||
<TooltipProvider delayDuration={200}>
|
<TooltipProvider delayDuration={200}>
|
||||||
<Outlet />
|
<Outlet />
|
||||||
<Toaster richColors position="top-right" />
|
<Toaster richColors position="top-right" />
|
||||||
@@ -45,9 +45,9 @@ function NotFound() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
|
<div className="flex min-h-svh flex-col items-center justify-center gap-4 p-6 text-center">
|
||||||
<p className="text-muted-foreground text-sm font-medium">404</p>
|
<p className="text-muted-foreground text-sm font-medium">404</p>
|
||||||
<h1 className="text-2xl font-semibold">This page does not exist</h1>
|
<h1 className="text-2xl font-semibold">Esta página no existe</h1>
|
||||||
<Button asChild>
|
<Button asChild>
|
||||||
<Link to="/">Back to dashboard</Link>
|
<Link to="/">Volver al inicio</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,160 +1,98 @@
|
|||||||
import { createFileRoute } from '@tanstack/react-router'
|
import type { ShoppingListSummary } from '@superlist/shared'
|
||||||
import { ActivityIcon, CircleCheckIcon, ServerIcon, UsersIcon } from 'lucide-react'
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, XAxis, YAxis } from 'recharts'
|
import { PlusIcon, ShoppingCartIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { CreateItemForm } from '@/components/items/create-item-form'
|
||||||
|
import { ItemList } from '@/components/items/item-list'
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Button } from '@/components/ui/button'
|
||||||
import { useHealth } from '@/hooks/use-health'
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { listsQueryOptions, useLists } from '@/hooks/use-lists'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
const TRAFFIC = [
|
|
||||||
{ day: 'Mon', requests: 420 },
|
|
||||||
{ day: 'Tue', requests: 512 },
|
|
||||||
{ day: 'Wed', requests: 388 },
|
|
||||||
{ day: 'Thu', requests: 640 },
|
|
||||||
{ day: 'Fri', requests: 731 },
|
|
||||||
{ day: 'Sat', requests: 254 },
|
|
||||||
{ day: 'Sun', requests: 198 },
|
|
||||||
]
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/')({
|
export const Route = createFileRoute('/_authenticated/')({
|
||||||
component: DashboardPage,
|
loader: ({ context }) => context.queryClient.ensureQueryData(listsQueryOptions()),
|
||||||
|
component: HomePage,
|
||||||
})
|
})
|
||||||
|
|
||||||
function DashboardPage() {
|
/** The list a user lands on: their primary one, falling back to the first. */
|
||||||
return (
|
function pickPrimaryList(lists: ShoppingListSummary[]): ShoppingListSummary | undefined {
|
||||||
<div className="flex flex-col gap-4 md:gap-6">
|
return lists.find((list) => list.isPrimary) ?? lists[0]
|
||||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
|
|
||||||
<StatCard title="Users" value="2,481" description="+12% vs last month" icon={UsersIcon} />
|
|
||||||
<StatCard title="Active lists" value="318" description="+4 this week" icon={ActivityIcon} />
|
|
||||||
<StatCard
|
|
||||||
title="Tasks done"
|
|
||||||
value="9,204"
|
|
||||||
description="+18% vs last month"
|
|
||||||
icon={CircleCheckIcon}
|
|
||||||
/>
|
|
||||||
<ApiStatusCard />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid gap-4 lg:grid-cols-2">
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Requests</CardTitle>
|
|
||||||
<CardDescription>API requests over the last 7 days</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="h-72 pl-0">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<AreaChart data={TRAFFIC} margin={{ left: 12, right: 12, top: 8 }}>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="fillRequests" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="var(--color-primary)" stopOpacity={0.7} />
|
|
||||||
<stop offset="95%" stopColor="var(--color-primary)" stopOpacity={0.05} />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<CartesianGrid vertical={false} strokeDasharray="3 3" />
|
|
||||||
<XAxis dataKey="day" tickLine={false} axisLine={false} />
|
|
||||||
<YAxis tickLine={false} axisLine={false} width={40} />
|
|
||||||
<Area
|
|
||||||
dataKey="requests"
|
|
||||||
type="monotone"
|
|
||||||
stroke="var(--color-primary)"
|
|
||||||
fill="url(#fillRequests)"
|
|
||||||
strokeWidth={2}
|
|
||||||
/>
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Recent activity</CardTitle>
|
|
||||||
<CardDescription>What your team has been doing</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="flex flex-col gap-4">
|
|
||||||
{[
|
|
||||||
{ who: 'Ada Lovelace', what: 'created list "Q4 roadmap"', when: '2h ago' },
|
|
||||||
{ who: 'Alan Turing', what: 'completed 12 tasks', when: '5h ago' },
|
|
||||||
{ who: 'Grace Hopper', what: 'invited 3 teammates', when: 'yesterday' },
|
|
||||||
{ who: 'Linus Torvalds', what: 'archived "Sprint 41"', when: '2 days ago' },
|
|
||||||
].map((item) => (
|
|
||||||
<div key={item.what} className="flex items-start gap-3">
|
|
||||||
<div className="bg-muted text-muted-foreground flex size-9 shrink-0 items-center justify-center rounded-full text-xs font-medium">
|
|
||||||
{item.who.slice(0, 2).toUpperCase()}
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 text-sm">
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">{item.who}</span> {item.what}
|
|
||||||
</p>
|
|
||||||
<p className="text-muted-foreground text-xs">{item.when}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function StatCard({
|
function HomePage() {
|
||||||
title,
|
const { data: lists, isPending, error } = useLists()
|
||||||
value,
|
|
||||||
description,
|
|
||||||
icon: Icon,
|
|
||||||
}: {
|
|
||||||
title: string
|
|
||||||
value: string
|
|
||||||
description: string
|
|
||||||
icon: typeof UsersIcon
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<Card>
|
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
|
||||||
<CardTitle className="text-sm font-medium">{title}</CardTitle>
|
|
||||||
<Icon className="text-muted-foreground size-4" />
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="text-2xl font-semibold">{value}</div>
|
|
||||||
<p className="text-muted-foreground text-xs">{description}</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Pings `GET /health` through TanStack Query, proving the API wiring works. */
|
|
||||||
function ApiStatusCard() {
|
|
||||||
const { data, isPending, error } = useHealth()
|
|
||||||
|
|
||||||
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<Card>
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
<Alert variant="destructive">
|
||||||
<CardTitle className="text-sm font-medium">API</CardTitle>
|
<AlertTitle>No pudimos cargar tu lista</AlertTitle>
|
||||||
<ServerIcon className="text-muted-foreground size-4" />
|
<AlertDescription>
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
{isPending && <div className="text-2xl font-semibold">…</div>}
|
|
||||||
{data && (
|
|
||||||
<>
|
|
||||||
<div className="text-2xl font-semibold">
|
|
||||||
<Badge variant="secondary">online</Badge>
|
|
||||||
</div>
|
|
||||||
<p className="text-muted-foreground text-xs">up {data.uptimeSeconds}s</p>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{error && (
|
|
||||||
<>
|
|
||||||
<div className="text-2xl font-semibold">
|
|
||||||
<Badge variant="destructive">offline</Badge>
|
|
||||||
</div>
|
|
||||||
<p className="text-muted-foreground truncate text-xs">
|
|
||||||
{error instanceof ApiError
|
{error instanceof ApiError
|
||||||
? (error.problem.detail ?? error.message)
|
? (error.problem.detail ?? error.problem.title)
|
||||||
: 'API unreachable'}
|
: 'Inténtalo de nuevo en unos segundos.'}
|
||||||
</p>
|
</AlertDescription>
|
||||||
</>
|
</Alert>
|
||||||
)}
|
</div>
|
||||||
</CardContent>
|
)
|
||||||
</Card>
|
}
|
||||||
|
|
||||||
|
if (isPending || !lists) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
|
||||||
|
<Skeleton className="h-8 w-48" />
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const primaryList = pickPrimaryList(lists)
|
||||||
|
|
||||||
|
if (!primaryList) {
|
||||||
|
return <NoLists />
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h1 className="text-lg font-semibold">{primaryList.name}</h1>
|
||||||
|
{primaryList.isPrimary && <Badge>Principal</Badge>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CreateItemForm listId={primaryList.id} />
|
||||||
|
|
||||||
|
<ItemList listId={primaryList.id} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function NoLists() {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
|
||||||
|
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
|
||||||
|
<ShoppingCartIcon className="size-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">Todavía no tienes listas</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Crea tu primera lista para empezar a añadir artículos.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button asChild>
|
||||||
|
<Link to="/lists">
|
||||||
|
<PlusIcon className="size-4" />
|
||||||
|
Crear lista
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
86
apps/web/src/routes/_authenticated/lists/$listId/index.tsx
Normal file
86
apps/web/src/routes/_authenticated/lists/$listId/index.tsx
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeftIcon, SettingsIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
import { CreateItemForm } from '@/components/items/create-item-form'
|
||||||
|
import { ItemList } from '@/components/items/item-list'
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { itemsQueryOptions } from '@/hooks/use-items'
|
||||||
|
import { listQueryOptions, useList } from '@/hooks/use-list'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/lists/$listId/')({
|
||||||
|
loader: ({ context, params }) =>
|
||||||
|
Promise.all([
|
||||||
|
context.queryClient.ensureQueryData(listQueryOptions(params.listId)),
|
||||||
|
context.queryClient.ensureQueryData(itemsQueryOptions(params.listId)),
|
||||||
|
]),
|
||||||
|
component: ListItemsPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function problemMessage(error: unknown, fallback: string) {
|
||||||
|
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A list's items: the default view when a list is opened from the overview. */
|
||||||
|
function ListItemsPage() {
|
||||||
|
const { listId } = Route.useParams()
|
||||||
|
const { data: list, isPending, error } = useList(listId)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertTitle>No pudimos abrir la lista</AlertTitle>
|
||||||
|
<AlertDescription>{problemMessage(error, 'Inténtalo de nuevo.')}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isPending || !list) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
|
||||||
|
<Skeleton className="h-8 w-48" />
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
<Skeleton className="h-12 w-full" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Link
|
||||||
|
to="/lists"
|
||||||
|
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-sm"
|
||||||
|
>
|
||||||
|
<ArrowLeftIcon className="size-4" />
|
||||||
|
Listas
|
||||||
|
</Link>
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h1 className="text-lg font-semibold break-words">{list.name}</h1>
|
||||||
|
{list.isPrimary && <Badge>Principal</Badge>}
|
||||||
|
<Badge variant="secondary">
|
||||||
|
{list.role === 'owner' ? 'Propietario' : 'Colaborador'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" asChild>
|
||||||
|
<Link to="/lists/$listId/settings" params={{ listId: list.id }}>
|
||||||
|
<SettingsIcon className="size-4" />
|
||||||
|
Gestionar
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<CreateItemForm listId={list.id} autoFocus />
|
||||||
|
|
||||||
|
<ItemList listId={list.id} />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
300
apps/web/src/routes/_authenticated/lists/$listId/settings.tsx
Normal file
300
apps/web/src/routes/_authenticated/lists/$listId/settings.tsx
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
|
import type { ListMember, ShoppingListDetail } from '@superlist/shared'
|
||||||
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
|
import { ArrowLeftIcon, CheckIcon, MailIcon, StarIcon, UserPlusIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
import { useForm } from 'react-hook-form'
|
||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { useCreateInvitation } from '@/hooks/use-invitations'
|
||||||
|
import { listQueryOptions, useList } from '@/hooks/use-list'
|
||||||
|
import { useRenameList, useSetPrimaryList } from '@/hooks/use-lists'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/lists/$listId/settings')({
|
||||||
|
loader: ({ context, params }) =>
|
||||||
|
context.queryClient.ensureQueryData(listQueryOptions(params.listId)),
|
||||||
|
component: ListSettingsPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function problemMessage(error: unknown, fallback: string) {
|
||||||
|
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function ListSettingsPage() {
|
||||||
|
const { listId } = Route.useParams()
|
||||||
|
const { data: list, isPending, error } = useList(listId)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertTitle>No pudimos abrir la lista</AlertTitle>
|
||||||
|
<AlertDescription>{problemMessage(error, 'Inténtalo de nuevo.')}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isPending || !list) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4">
|
||||||
|
<Skeleton className="h-8 w-48" />
|
||||||
|
<Skeleton className="h-32 w-full" />
|
||||||
|
<Skeleton className="h-32 w-full" />
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Link
|
||||||
|
to="/lists/$listId"
|
||||||
|
params={{ listId: list.id }}
|
||||||
|
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-sm"
|
||||||
|
>
|
||||||
|
<ArrowLeftIcon className="size-4" />
|
||||||
|
{list.name}
|
||||||
|
</Link>
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h1 className="text-lg font-semibold break-words">Gestionar lista</h1>
|
||||||
|
<Badge variant="secondary">{list.role === 'owner' ? 'Propietario' : 'Colaborador'}</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!list.isPrimary && <SetPrimaryButton listId={list.id} />}
|
||||||
|
|
||||||
|
{list.role === 'owner' && <RenameListCard list={list} />}
|
||||||
|
|
||||||
|
{list.role === 'owner' && <InviteCollaboratorCard listId={list.id} />}
|
||||||
|
|
||||||
|
<MembersCard members={list.members} />
|
||||||
|
|
||||||
|
{list.invitations.length > 0 && <PendingInvitationsCard list={list} />}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SetPrimaryButton({ listId }: { listId: string }) {
|
||||||
|
const setPrimary = useSetPrimaryList()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full sm:w-auto sm:self-start"
|
||||||
|
disabled={setPrimary.isPending}
|
||||||
|
onClick={() => setPrimary.mutate(listId)}
|
||||||
|
>
|
||||||
|
<StarIcon className="size-4" />
|
||||||
|
{setPrimary.isPending ? 'Marcando…' : 'Marcar como lista principal'}
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const renameSchema = z.object({
|
||||||
|
name: z.string().trim().min(1, 'El nombre es obligatorio').max(80, 'Máximo 80 caracteres'),
|
||||||
|
})
|
||||||
|
|
||||||
|
function RenameListCard({ list }: { list: ShoppingListDetail }) {
|
||||||
|
const [saved, setSaved] = useState(false)
|
||||||
|
const renameList = useRenameList(list.id)
|
||||||
|
|
||||||
|
const form = useForm<z.infer<typeof renameSchema>>({
|
||||||
|
resolver: zodResolver(renameSchema),
|
||||||
|
defaultValues: { name: list.name },
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
setSaved(false)
|
||||||
|
renameList.mutate(values, { onSuccess: () => setSaved(true) })
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Nombre de la lista</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||||
|
{renameList.error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>
|
||||||
|
{problemMessage(renameList.error, 'No pudimos renombrar la lista.')}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!form.formState.errors.name}>
|
||||||
|
<FieldLabel htmlFor="rename-list">Nombre</FieldLabel>
|
||||||
|
<Input id="rename-list" {...form.register('name')} />
|
||||||
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Button type="submit" className="w-full sm:w-auto" disabled={renameList.isPending}>
|
||||||
|
{renameList.isPending ? 'Guardando…' : 'Guardar'}
|
||||||
|
</Button>
|
||||||
|
{saved && (
|
||||||
|
<span className="text-muted-foreground inline-flex items-center gap-1 text-sm">
|
||||||
|
<CheckIcon className="size-4" />
|
||||||
|
Guardado
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const inviteSchema = z.object({
|
||||||
|
email: z.email('Introduce un correo electrónico válido'),
|
||||||
|
})
|
||||||
|
|
||||||
|
function InviteCollaboratorCard({ listId }: { listId: string }) {
|
||||||
|
const [message, setMessage] = useState<string | null>(null)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const createInvitation = useCreateInvitation(listId)
|
||||||
|
|
||||||
|
const form = useForm<z.infer<typeof inviteSchema>>({
|
||||||
|
resolver: zodResolver(inviteSchema),
|
||||||
|
defaultValues: { email: '' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
|
setMessage(null)
|
||||||
|
setError(null)
|
||||||
|
|
||||||
|
createInvitation.mutate(values, {
|
||||||
|
onSuccess: (result) => {
|
||||||
|
form.reset()
|
||||||
|
setMessage(
|
||||||
|
result.status === 'added'
|
||||||
|
? `${result.email} ya tenía cuenta y ahora colabora en la lista.`
|
||||||
|
: `Invitación enviada a ${result.email}.`,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
onError: (mutationError) => {
|
||||||
|
setError(problemMessage(mutationError, 'No pudimos enviar la invitación.'))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Invitar a colaborar</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={onSubmit} className="flex flex-col gap-4">
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{message && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>{message}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<FieldGroup>
|
||||||
|
<Field data-invalid={!!form.formState.errors.email}>
|
||||||
|
<FieldLabel htmlFor="invite-email">Correo electrónico</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="invite-email"
|
||||||
|
type="email"
|
||||||
|
placeholder="persona@ejemplo.com"
|
||||||
|
autoComplete="off"
|
||||||
|
{...form.register('email')}
|
||||||
|
/>
|
||||||
|
<FieldError errors={[form.formState.errors.email]} />
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="w-full sm:w-auto sm:self-start"
|
||||||
|
disabled={createInvitation.isPending}
|
||||||
|
>
|
||||||
|
<UserPlusIcon className="size-4" />
|
||||||
|
{createInvitation.isPending ? 'Enviando…' : 'Enviar invitación'}
|
||||||
|
</Button>
|
||||||
|
</FieldGroup>
|
||||||
|
</form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function initials(name: string) {
|
||||||
|
return (
|
||||||
|
name
|
||||||
|
.split(' ')
|
||||||
|
.map((part) => part[0])
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 2)
|
||||||
|
.join('')
|
||||||
|
.toUpperCase() || '?'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function MembersCard({ members }: { members: ListMember[] }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Colaboradores ({members.length})</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
{members.map((member) => (
|
||||||
|
<div key={member.id} className="flex items-center gap-3">
|
||||||
|
<Avatar className="size-9">
|
||||||
|
<AvatarFallback>{initials(member.user.name)}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate text-sm font-medium">{member.user.name}</p>
|
||||||
|
<p className="text-muted-foreground truncate text-xs">{member.user.email}</p>
|
||||||
|
</div>
|
||||||
|
{member.role === 'owner' && <Badge variant="secondary">Propietario</Badge>}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function PendingInvitationsCard({ list }: { list: ShoppingListDetail }) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="text-base">Invitaciones pendientes</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
{list.invitations.map((invitation) => (
|
||||||
|
<div key={invitation.id} className="flex items-center gap-3">
|
||||||
|
<div className="bg-muted text-muted-foreground flex size-9 items-center justify-center rounded-full">
|
||||||
|
<MailIcon className="size-4" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate text-sm font-medium">{invitation.email}</p>
|
||||||
|
<p className="text-muted-foreground text-xs">
|
||||||
|
Caduca el {new Date(invitation.expiresAt).toLocaleDateString('es')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Badge variant="outline">Pendiente</Badge>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
87
apps/web/src/routes/_authenticated/lists/index.tsx
Normal file
87
apps/web/src/routes/_authenticated/lists/index.tsx
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { createFileRoute } from '@tanstack/react-router'
|
||||||
|
import { PlusIcon, ShoppingCartIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
import { CreateListForm } from '@/components/lists/create-list-form'
|
||||||
|
import { ListCard } from '@/components/lists/list-card'
|
||||||
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import { listsQueryOptions, useLists } from '@/hooks/use-lists'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/_authenticated/lists/')({
|
||||||
|
loader: ({ context }) => context.queryClient.ensureQueryData(listsQueryOptions()),
|
||||||
|
component: ListsPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function ListsPage() {
|
||||||
|
const [showCreate, setShowCreate] = useState(false)
|
||||||
|
const { data: lists, isPending, error } = useLists()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto flex w-full max-w-2xl flex-col gap-4 md:gap-6">
|
||||||
|
<div className="flex items-center justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold">Listas de compras</h1>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Tuyas y las que compartes con otras personas.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button size="sm" onClick={() => setShowCreate((open) => !open)} aria-expanded={showCreate}>
|
||||||
|
<PlusIcon className="size-4" />
|
||||||
|
Nueva
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showCreate && (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="p-4">
|
||||||
|
<CreateListForm onCreated={() => setShowCreate(false)} />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertTitle>No pudimos cargar tus listas</AlertTitle>
|
||||||
|
<AlertDescription>
|
||||||
|
{error instanceof ApiError
|
||||||
|
? (error.problem.detail ?? error.problem.title)
|
||||||
|
: 'Inténtalo de nuevo en unos segundos.'}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
) : isPending ? (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<Skeleton className="h-20 w-full" />
|
||||||
|
<Skeleton className="h-20 w-full" />
|
||||||
|
</div>
|
||||||
|
) : lists && lists.length > 0 ? (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{lists.map((list) => (
|
||||||
|
<ListCard key={list.id} list={list} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex flex-col items-center gap-3 py-10 text-center">
|
||||||
|
<div className="bg-muted text-muted-foreground flex size-12 items-center justify-center rounded-full">
|
||||||
|
<ShoppingCartIcon className="size-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="font-medium">Todavía no tienes listas</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Crea tu primera lista para empezar a organizar tus compras.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setShowCreate(true)}>
|
||||||
|
<PlusIcon className="size-4" />
|
||||||
|
Crear lista
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { createFileRoute, Navigate, Outlet } from '@tanstack/react-router'
|
import { createFileRoute, Navigate, Outlet, useRouterState } from '@tanstack/react-router'
|
||||||
|
|
||||||
import { AppHeader } from '@/components/layout/app-header'
|
import { AppHeader } from '@/components/layout/app-header'
|
||||||
import { AppSidebar } from '@/components/layout/app-sidebar'
|
import { AppSidebar } from '@/components/layout/app-sidebar'
|
||||||
@@ -13,17 +13,18 @@ export const Route = createFileRoute('/_authenticated')({
|
|||||||
/**
|
/**
|
||||||
* Layout for every authenticated page. The session lives in BetterAuth (Hono
|
* Layout for every authenticated page. The session lives in BetterAuth (Hono
|
||||||
* API); while it resolves we render a loader, and without a session we bounce
|
* API); while it resolves we render a loader, and without a session we bounce
|
||||||
* the user to `/sign-in`.
|
* the user to `/sign-in`, keeping the current URL so we can return after login.
|
||||||
*/
|
*/
|
||||||
function AuthenticatedLayout() {
|
function AuthenticatedLayout() {
|
||||||
const { data: session, isPending } = useSession()
|
const { data: session, isPending } = useSession()
|
||||||
|
const href = useRouterState({ select: (state) => state.location.href })
|
||||||
|
|
||||||
if (isPending) {
|
if (isPending) {
|
||||||
return <SessionLoading />
|
return <SessionLoading />
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!session) {
|
if (!session) {
|
||||||
return <Navigate to="/sign-in" replace />
|
return <Navigate to="/sign-in" search={{ redirect: href }} replace />
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ export const Route = createFileRoute('/_authenticated/settings')({
|
|||||||
})
|
})
|
||||||
|
|
||||||
const profileSchema = z.object({
|
const profileSchema = z.object({
|
||||||
name: z.string().min(1, 'Name is required').max(80),
|
name: z.string().min(1, 'El nombre es obligatorio').max(80),
|
||||||
email: z.email('Enter a valid email address'),
|
email: z.email('Introduce un correo electrónico válido'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type ProfileValues = z.infer<typeof profileSchema>
|
type ProfileValues = z.infer<typeof profileSchema>
|
||||||
@@ -38,8 +38,8 @@ function SettingsPage() {
|
|||||||
<div className="grid max-w-3xl gap-4 md:gap-6">
|
<div className="grid max-w-3xl gap-4 md:gap-6">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Profile</CardTitle>
|
<CardTitle>Perfil</CardTitle>
|
||||||
<CardDescription>This is how other people will see you.</CardDescription>
|
<CardDescription>Así es como te verán las demás personas.</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form
|
<form
|
||||||
@@ -50,28 +50,30 @@ function SettingsPage() {
|
|||||||
>
|
>
|
||||||
<FieldGroup>
|
<FieldGroup>
|
||||||
<Field data-invalid={!!form.formState.errors.name}>
|
<Field data-invalid={!!form.formState.errors.name}>
|
||||||
<FieldLabel htmlFor="name">Name</FieldLabel>
|
<FieldLabel htmlFor="name">Nombre</FieldLabel>
|
||||||
<Input id="name" placeholder="Ada Lovelace" {...form.register('name')} />
|
<Input id="name" placeholder="Ada Lovelace" {...form.register('name')} />
|
||||||
<FieldError errors={[form.formState.errors.name]} />
|
<FieldError errors={[form.formState.errors.name]} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<Field data-invalid={!!form.formState.errors.email}>
|
<Field data-invalid={!!form.formState.errors.email}>
|
||||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
placeholder="ada@example.com"
|
placeholder="ada@ejemplo.com"
|
||||||
{...form.register('email')}
|
{...form.register('email')}
|
||||||
/>
|
/>
|
||||||
<FieldDescription>We only use it to sign you in.</FieldDescription>
|
<FieldDescription>Solo lo usamos para iniciar tu sesión.</FieldDescription>
|
||||||
<FieldError errors={[form.formState.errors.email]} />
|
<FieldError errors={[form.formState.errors.email]} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||||
Save changes
|
Guardar cambios
|
||||||
</Button>
|
</Button>
|
||||||
{saved && <span className="text-muted-foreground text-sm">Saved locally.</span>}
|
{saved && (
|
||||||
|
<span className="text-muted-foreground text-sm">Guardado localmente.</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
</form>
|
</form>
|
||||||
@@ -80,13 +82,21 @@ function SettingsPage() {
|
|||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Appearance</CardTitle>
|
<CardTitle>Apariencia</CardTitle>
|
||||||
<CardDescription>Notifications and display preferences.</CardDescription>
|
<CardDescription>Notificaciones y preferencias de visualización.</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="flex flex-col gap-4">
|
<CardContent className="flex flex-col gap-4">
|
||||||
{[
|
{[
|
||||||
{ id: 'digest', label: 'Weekly digest', hint: 'A summary of your lists every Monday.' },
|
{
|
||||||
{ id: 'mentions', label: 'Mentions', hint: 'Ping me when someone mentions my name.' },
|
id: 'digest',
|
||||||
|
label: 'Resumen semanal',
|
||||||
|
hint: 'Un resumen de tus listas cada lunes.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'mentions',
|
||||||
|
label: 'Menciones',
|
||||||
|
hint: 'Avísame cuando alguien mencione mi nombre.',
|
||||||
|
},
|
||||||
].map((option) => (
|
].map((option) => (
|
||||||
<div key={option.id} className="flex items-center justify-between gap-4">
|
<div key={option.id} className="flex items-center justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
@@ -22,17 +22,37 @@ export const Route = createFileRoute('/_authenticated/tasks')({
|
|||||||
type Task = {
|
type Task = {
|
||||||
title: string
|
title: string
|
||||||
list: string
|
list: string
|
||||||
status: 'todo' | 'in progress' | 'done'
|
status: 'pendiente' | 'en curso' | 'hecha'
|
||||||
priority: 'low' | 'medium' | 'high'
|
priority: 'baja' | 'media' | 'alta'
|
||||||
}
|
}
|
||||||
|
|
||||||
const TASKS: Task[] = [
|
const TASKS: Task[] = [
|
||||||
{ title: 'Design onboarding flow', list: 'Q4 roadmap', status: 'in progress', priority: 'high' },
|
{
|
||||||
{ title: 'Write API docs', list: 'Docs', status: 'todo', priority: 'medium' },
|
title: 'Diseñar el flujo de registro',
|
||||||
{ title: 'Review Prisma migrations', list: 'Backend', status: 'todo', priority: 'high' },
|
list: 'Hoja de ruta Q4',
|
||||||
{ title: 'Ship dark mode', list: 'Design system', status: 'done', priority: 'low' },
|
status: 'en curso',
|
||||||
{ title: 'Migrate to Turborepo', list: 'Infra', status: 'done', priority: 'medium' },
|
priority: 'alta',
|
||||||
{ title: 'Add e2e smoke test', list: 'Quality', status: 'in progress', priority: 'low' },
|
},
|
||||||
|
{
|
||||||
|
title: 'Escribir la documentación de la API',
|
||||||
|
list: 'Docs',
|
||||||
|
status: 'pendiente',
|
||||||
|
priority: 'media',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Revisar migraciones de Prisma',
|
||||||
|
list: 'Backend',
|
||||||
|
status: 'pendiente',
|
||||||
|
priority: 'alta',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Publicar el modo oscuro',
|
||||||
|
list: 'Sistema de diseño',
|
||||||
|
status: 'hecha',
|
||||||
|
priority: 'baja',
|
||||||
|
},
|
||||||
|
{ title: 'Migrar a Turborepo', list: 'Infra', status: 'hecha', priority: 'media' },
|
||||||
|
{ title: 'Añadir prueba e2e', list: 'Calidad', status: 'en curso', priority: 'baja' },
|
||||||
]
|
]
|
||||||
|
|
||||||
// `tableFeatures` and the columns live at module scope so row models stay stable.
|
// `tableFeatures` and the columns live at module scope so row models stay stable.
|
||||||
@@ -40,16 +60,16 @@ const features = tableFeatures({})
|
|||||||
const columnHelper = createColumnHelper<typeof features, Task>()
|
const columnHelper = createColumnHelper<typeof features, Task>()
|
||||||
|
|
||||||
const columns = columnHelper.columns([
|
const columns = columnHelper.columns([
|
||||||
columnHelper.accessor('title', { header: 'Task' }),
|
columnHelper.accessor('title', { header: 'Tarea' }),
|
||||||
columnHelper.accessor('list', { header: 'List' }),
|
columnHelper.accessor('list', { header: 'Lista' }),
|
||||||
columnHelper.accessor('status', { header: 'Status' }),
|
columnHelper.accessor('status', { header: 'Estado' }),
|
||||||
columnHelper.accessor('priority', { header: 'Priority' }),
|
columnHelper.accessor('priority', { header: 'Prioridad' }),
|
||||||
])
|
])
|
||||||
|
|
||||||
const STATUS_VARIANT = {
|
const STATUS_VARIANT = {
|
||||||
todo: 'outline',
|
pendiente: 'outline',
|
||||||
'in progress': 'secondary',
|
'en curso': 'secondary',
|
||||||
done: 'default',
|
hecha: 'default',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
function TasksPage() {
|
function TasksPage() {
|
||||||
@@ -68,21 +88,21 @@ function TasksPage() {
|
|||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Tasks</CardTitle>
|
<CardTitle>Tareas</CardTitle>
|
||||||
<CardDescription>Every task across your lists.</CardDescription>
|
<CardDescription>Todas las tareas de tus listas.</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="flex flex-col gap-4">
|
<CardContent className="flex flex-col gap-4">
|
||||||
<div className="relative max-w-sm">
|
<div className="relative w-full sm:max-w-sm">
|
||||||
<SearchIcon className="text-muted-foreground absolute top-2.5 left-2.5 size-4" />
|
<SearchIcon className="text-muted-foreground absolute top-2.5 left-2.5 size-4" />
|
||||||
<Input
|
<Input
|
||||||
value={query}
|
value={query}
|
||||||
onChange={(event) => setQuery(event.target.value)}
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
placeholder="Filter tasks…"
|
placeholder="Filtrar tareas…"
|
||||||
className="pl-8"
|
className="pl-8"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-md border">
|
<div className="overflow-x-auto rounded-md border">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
{table.getHeaderGroups().map((headerGroup) => (
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
@@ -102,7 +122,7 @@ function TasksPage() {
|
|||||||
colSpan={columns.length}
|
colSpan={columns.length}
|
||||||
className="text-muted-foreground h-24 text-center"
|
className="text-muted-foreground h-24 text-center"
|
||||||
>
|
>
|
||||||
No tasks match your filter.
|
Ninguna tarea coincide con el filtro.
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
)}
|
)}
|
||||||
|
|||||||
131
apps/web/src/routes/invitations/$token.tsx
Normal file
131
apps/web/src/routes/invitations/$token.tsx
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import type { AcceptInvitationResult } from '@superlist/shared'
|
||||||
|
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||||
|
import { CheckCircle2Icon, Loader2Icon, XCircleIcon } from 'lucide-react'
|
||||||
|
import { useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { useAcceptInvitation } from '@/hooks/use-invitations'
|
||||||
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
import { useSession } from '@/lib/auth-client'
|
||||||
|
|
||||||
|
export const Route = createFileRoute('/invitations/$token')({
|
||||||
|
component: AcceptInvitationPage,
|
||||||
|
})
|
||||||
|
|
||||||
|
function problemMessage(error: unknown, fallback: string) {
|
||||||
|
return error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function AcceptInvitationPage() {
|
||||||
|
const { token } = Route.useParams()
|
||||||
|
const { data: session, isPending } = useSession()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-svh items-center justify-center p-6">
|
||||||
|
<Card className="w-full max-w-sm">
|
||||||
|
{isPending ? (
|
||||||
|
<CardContent className="flex items-center justify-center gap-2 py-10">
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
<span className="text-muted-foreground text-sm">Cargando…</span>
|
||||||
|
</CardContent>
|
||||||
|
) : session ? (
|
||||||
|
<AcceptInvitation token={token} />
|
||||||
|
) : (
|
||||||
|
<SignedOut token={token} />
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SignedOut({ token }: { token: string }) {
|
||||||
|
const redirect = `/invitations/${token}`
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Te invitaron a una lista</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Inicia sesión o crea una cuenta con tu correo para unirte a la lista compartida.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
<Button asChild>
|
||||||
|
<Link to="/sign-up" search={{ redirect }}>
|
||||||
|
Crear cuenta
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<Button variant="outline" asChild>
|
||||||
|
<Link to="/sign-in" search={{ redirect }}>
|
||||||
|
Iniciar sesión
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function AcceptInvitation({ token }: { token: string }) {
|
||||||
|
const { mutate } = useAcceptInvitation()
|
||||||
|
const [result, setResult] = useState<AcceptInvitationResult | null>(null)
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const started = useRef(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (started.current) return
|
||||||
|
started.current = true
|
||||||
|
|
||||||
|
mutate(token, {
|
||||||
|
onSuccess: (accepted) => setResult(accepted),
|
||||||
|
onError: (mutationError) =>
|
||||||
|
setError(problemMessage(mutationError, 'No pudimos aceptar la invitación.')),
|
||||||
|
})
|
||||||
|
}, [mutate, token])
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CardHeader>
|
||||||
|
<CheckCircle2Icon className="text-primary size-8" />
|
||||||
|
<CardTitle>Invitación aceptada</CardTitle>
|
||||||
|
<CardDescription>Ya formas parte de «{result.listName}».</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button className="w-full" asChild>
|
||||||
|
<Link to="/lists/$listId" params={{ listId: result.listId }}>
|
||||||
|
Ir a la lista
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<CardHeader>
|
||||||
|
<XCircleIcon className="text-destructive size-8" />
|
||||||
|
<CardTitle>No pudimos aceptar la invitación</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{error}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
<Button variant="outline" asChild>
|
||||||
|
<Link to="/lists">Ver mis listas</Link>
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CardContent className="flex items-center justify-center gap-2 py-10">
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
<span className="text-muted-foreground text-sm">Aceptando invitación…</span>
|
||||||
|
</CardContent>
|
||||||
|
)
|
||||||
|
}
|
||||||
14
bun.lock
14
bun.lock
@@ -23,6 +23,7 @@
|
|||||||
"pg": "^8.23.1",
|
"pg": "^8.23.1",
|
||||||
"pino": "^10.4.0",
|
"pino": "^10.4.0",
|
||||||
"pino-pretty": "^13.2.0",
|
"pino-pretty": "^13.2.0",
|
||||||
|
"resend": "^6.32.1",
|
||||||
"zod": "^4.6.7",
|
"zod": "^4.6.7",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -49,7 +50,6 @@
|
|||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cn": "^0.4.0",
|
"cn": "^0.4.0",
|
||||||
"lucide-react": "^1.55.0",
|
"lucide-react": "^1.55.0",
|
||||||
"next-themes": "^0.4.6",
|
|
||||||
"radix-ui": "^1.8.0",
|
"radix-ui": "^1.8.0",
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.8",
|
"react-dom": "^19.2.8",
|
||||||
@@ -457,6 +457,8 @@
|
|||||||
|
|
||||||
"@solid-primitives/utils": ["@solid-primitives/utils@6.4.1", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-ISSB5QX1qP2ynrheIpYwc4oKR5Ny4siNuUyf1qZniy+Il+p/PtDB0QK1Dnle8noiHpwRD3gpPdubOC3qI/Zamg=="],
|
"@solid-primitives/utils": ["@solid-primitives/utils@6.4.1", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-ISSB5QX1qP2ynrheIpYwc4oKR5Ny4siNuUyf1qZniy+Il+p/PtDB0QK1Dnle8noiHpwRD3gpPdubOC3qI/Zamg=="],
|
||||||
|
|
||||||
|
"@stablelib/base64": ["@stablelib/base64@1.0.1", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="],
|
||||||
|
|
||||||
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||||
|
|
||||||
"@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
|
"@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
|
||||||
@@ -881,6 +883,8 @@
|
|||||||
|
|
||||||
"fast-safe-stringify": ["fast-safe-stringify@2.1.1", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="],
|
"fast-safe-stringify": ["fast-safe-stringify@2.1.1", "", {}, "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="],
|
||||||
|
|
||||||
|
"fast-sha256": ["fast-sha256@1.3.0", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],
|
||||||
|
|
||||||
"fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],
|
"fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="],
|
||||||
|
|
||||||
"fastq": ["fastq@1.20.3", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="],
|
"fastq": ["fastq@1.20.3", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="],
|
||||||
@@ -1105,8 +1109,6 @@
|
|||||||
|
|
||||||
"negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="],
|
"negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="],
|
||||||
|
|
||||||
"next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="],
|
|
||||||
|
|
||||||
"node-releases": ["node-releases@2.0.58", "", {}, "sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg=="],
|
"node-releases": ["node-releases@2.0.58", "", {}, "sha512-BdiKAgbfRlvfMq/XzO/AF9NPmaA8a+YpLAyAFTVFBj3gARrAIfWvNq7Q7NE4se3KgFu0KkrvQMxTS0XVnsGzHg=="],
|
||||||
|
|
||||||
"npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
|
"npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="],
|
||||||
@@ -1189,6 +1191,8 @@
|
|||||||
|
|
||||||
"pkg-up": ["pkg-up@3.1.0", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="],
|
"pkg-up": ["pkg-up@3.1.0", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="],
|
||||||
|
|
||||||
|
"postal-mime": ["postal-mime@2.7.6", "", {}, "sha512-UUlyE2KlxmvwMGq060onF/VWU3zD6dVW31FwokQ5v26jWd35fbs2MoTFzh+jXnPwAyV2MULMKXcBInGOl5TO6Q=="],
|
||||||
|
|
||||||
"postcss": ["postcss@8.5.29", "", { "dependencies": { "nanoid": "^3.3.19", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ=="],
|
"postcss": ["postcss@8.5.29", "", { "dependencies": { "nanoid": "^3.3.19", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ=="],
|
||||||
|
|
||||||
"postcss-selector-parser": ["postcss-selector-parser@7.1.6", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="],
|
"postcss-selector-parser": ["postcss-selector-parser@7.1.6", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="],
|
||||||
@@ -1275,6 +1279,8 @@
|
|||||||
|
|
||||||
"reselect": ["reselect@5.2.0", "", {}, "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="],
|
"reselect": ["reselect@5.2.0", "", {}, "sha512-AgZ3UOZm3YndfrJ4OYjgrT7bmCm/1iqkjvEfH/oYjzh6PD2qw4QuT3jjnXIrpdt4MTpMXclMT3lXbmRY+XRakw=="],
|
||||||
|
|
||||||
|
"resend": ["resend@6.32.1", "", { "dependencies": { "postal-mime": "2.7.6", "standardwebhooks": "1.1.1" }, "peerDependencies": { "@react-email/render": "*" }, "optionalPeers": ["@react-email/render"] }, "sha512-Z9DxkIZt5uvVNkjxjc+r4rCPI0MdDIJ7H+GvU50o9GkhrD0tVTwP6caE8KYEco90sos312l6R72jAEMCBFBiFQ=="],
|
||||||
|
|
||||||
"restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
|
"restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
|
||||||
|
|
||||||
"ret": ["ret@0.5.0", "", {}, "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw=="],
|
"ret": ["ret@0.5.0", "", {}, "sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw=="],
|
||||||
@@ -1363,6 +1369,8 @@
|
|||||||
|
|
||||||
"sqlstring": ["sqlstring@2.3.3", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
|
"sqlstring": ["sqlstring@2.3.3", "", {}, "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg=="],
|
||||||
|
|
||||||
|
"standardwebhooks": ["standardwebhooks@1.1.1", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ=="],
|
||||||
|
|
||||||
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
|
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
|
||||||
|
|
||||||
"std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="],
|
"std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="],
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
export * from './problem-details'
|
export * from './problem-details'
|
||||||
export * from './result'
|
export * from './result'
|
||||||
|
export * from './shopping-list'
|
||||||
|
|||||||
99
packages/shared/src/shopping-list.ts
Normal file
99
packages/shared/src/shopping-list.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* Shared DTOs for collaborative shopping lists. The API serializes these shapes
|
||||||
|
* and the web app consumes them, so they live here instead of being duplicated.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type ListRole = 'owner' | 'collaborator'
|
||||||
|
|
||||||
|
export type InvitationStatus = 'pending' | 'accepted' | 'revoked' | 'expired'
|
||||||
|
|
||||||
|
/** A member of a list, as seen in the list detail. */
|
||||||
|
export type ListMember = {
|
||||||
|
id: string
|
||||||
|
role: ListRole
|
||||||
|
isPrimary: boolean
|
||||||
|
user: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
image: string | null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A list as returned by the collection endpoint (`GET /lists`). */
|
||||||
|
export type ShoppingListSummary = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
role: ListRole
|
||||||
|
isPrimary: boolean
|
||||||
|
memberCount: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A list with its members, as returned by `GET /lists/:listId`. */
|
||||||
|
export type ShoppingListDetail = {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
role: ListRole
|
||||||
|
isPrimary: boolean
|
||||||
|
members: ListMember[]
|
||||||
|
invitations: ListInvitation[]
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An invitation attached to a list (pending or historical). */
|
||||||
|
export type ListInvitation = {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
status: InvitationStatus
|
||||||
|
expiresAt: string
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A pending invitation from the invited user's point of view. */
|
||||||
|
export type PendingInvitation = {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
status: InvitationStatus
|
||||||
|
expiresAt: string
|
||||||
|
createdAt: string
|
||||||
|
list: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
invitedBy: {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Result of creating an invitation: `added` when the email already had an
|
||||||
|
* account (membership granted immediately) or `invited` when a pending
|
||||||
|
* invitation was emailed.
|
||||||
|
*/
|
||||||
|
export type CreateInvitationResult = {
|
||||||
|
status: 'added' | 'invited'
|
||||||
|
email: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Result of accepting an invitation, used to navigate to the shared list. */
|
||||||
|
export type AcceptInvitationResult = {
|
||||||
|
listId: string
|
||||||
|
listName: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An item inside a shopping list, as returned by the items endpoints. */
|
||||||
|
export type ListItem = {
|
||||||
|
id: string
|
||||||
|
listId: string
|
||||||
|
name: string
|
||||||
|
completed: boolean
|
||||||
|
quantity: string | null
|
||||||
|
notes: string | null
|
||||||
|
order: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
16
turbo.json
16
turbo.json
@@ -9,7 +9,16 @@
|
|||||||
"lint": {},
|
"lint": {},
|
||||||
"typecheck": {},
|
"typecheck": {},
|
||||||
"test": {
|
"test": {
|
||||||
"env": ["NODE_ENV", "DATABASE_URL", "BETTER_AUTH_SECRET", "BETTER_AUTH_URL", "CORS_ORIGIN"]
|
"env": [
|
||||||
|
"NODE_ENV",
|
||||||
|
"DATABASE_URL",
|
||||||
|
"BETTER_AUTH_SECRET",
|
||||||
|
"BETTER_AUTH_URL",
|
||||||
|
"CORS_ORIGIN",
|
||||||
|
"RESEND_API_KEY",
|
||||||
|
"MAIL_FROM",
|
||||||
|
"WEB_APP_URL"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"dev": {
|
"dev": {
|
||||||
"cache": false,
|
"cache": false,
|
||||||
@@ -20,7 +29,10 @@
|
|||||||
"CORS_ORIGIN",
|
"CORS_ORIGIN",
|
||||||
"BETTER_AUTH_SECRET",
|
"BETTER_AUTH_SECRET",
|
||||||
"BETTER_AUTH_URL",
|
"BETTER_AUTH_URL",
|
||||||
"NODE_ENV"
|
"NODE_ENV",
|
||||||
|
"RESEND_API_KEY",
|
||||||
|
"MAIL_FROM",
|
||||||
|
"WEB_APP_URL"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"db:generate": {
|
"db:generate": {
|
||||||
|
|||||||
Reference in New Issue
Block a user