diff --git a/.env.example b/.env.example index 04d5844..65949a5 100644 --- a/.env.example +++ b/.env.example @@ -11,8 +11,18 @@ BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32" BETTER_AUTH_URL="http://localhost:4100" # "development" enables pretty logs, "production" emits JSON NODE_ENV="development" -# Optional: Pino log level (defaults to "debug" outside production, "info" in production) +# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production) # LOG_LEVEL="info" +# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console. +# OPENOBSERVE_URL="http://localhost:5080" +# Optional: organization (defaults to "default") and stream (defaults to "superlist") +# OPENOBSERVE_ORG="default" +# OPENOBSERVE_STREAM="superlist" +# OpenObserve user email and password (sent as Basic auth) +# OPENOBSERVE_USER="root@example.com" +# OPENOBSERVE_PASSWORD="" +# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000) +# METRICS_EXPORT_INTERVAL_MS="15000" # Resend API key used to send invitation and password reset emails. Without it, emails are logged instead. # RESEND_API_KEY="re_xxxxxxxx" # From address for outgoing email (must be a verified Resend sender) diff --git a/AGENTS.md b/AGENTS.md index c8a55ce..8ecbbf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ The `health` module is the reference example. - Monorepo orchestrated with **Turborepo** (see the managed block at the end of this file) - Backend: **Bun** + **Hono**, **Prisma 7** against **Postgres** (via `@prisma/adapter-pg`), **Zod** for - validation, **Pino** for logging, **BetterAuth** for auth + validation, **LogTape** for logging (shipped to **OpenObserve**), **BetterAuth** for auth - Frontend: **React + Vite + TypeScript**, **Tailwind v4**, UI components from **shadcn/ui** - Frontend routing: **TanStack Router** (file-based) · server state: **TanStack Query** · forms: **React Hook Form + Zod** @@ -197,9 +197,26 @@ export class CreateAlert { (`problemResponse`, `notFoundHandler`, `errorHandler`) in `apps/api/src/lib/problem-details.ts`. - Zod is the only validation library, and Zod 4 is what is installed. Define schemas next to the feature that uses them (`schema.ts`); share them through `@superlist/shared` only when more than one module needs them. -- **Logging: Pino** — one shared logger in `apps/api/src/lib/logger.ts`, reachable from handlers as - `c.get('logger')` (already enriched with the request id); never `console.log` in the backend. Level comes from - `LOG_LEVEL`, defaulting to `debug` (pretty) outside production and `info` (JSON) in production. +- **Logging: LogTape** — root logger (`superlist` category) exported from `apps/api/src/lib/logger.ts`, reachable + from handlers as `c.get('logger')`; never `console.log` in the backend. The call shape is + `logger.info('message {prop}', { prop })` (message first, properties second; pass errors as `{ error }`). + `configureLogging()` runs once in `src/index.ts` (tests never call it, so logging is silent there) and + `dispose()` flushes on SIGINT/SIGTERM. Sinks: console (`@logtape/pretty` outside production, JSON lines in + production) plus OpenObserve over OTLP/HTTP (`@logtape/otel`, `/api//v1/logs`, Basic auth, `stream-name` + header) when `OPENOBSERVE_URL` is set (`OPENOBSERVE_ORG`, `OPENOBSERVE_STREAM`, `OPENOBSERVE_USER`, + `OPENOBSERVE_PASSWORD`). Level comes from `LOG_LEVEL` (`debug` in dev, `info` in production; `warn` is accepted + for `warning`). The request middleware in `app.ts` wraps each request in `withContext({ requestId })`, so every + record logged during it carries the request id, and logs one `superlist.http` record per request with + `method`, `path`, `route` (the Hono pattern, e.g. `/api/lists/:listId`), `status`, `durationMs`, `userId` and + `userAgent` — `error` for 5xx, `warning` for 4xx, `debug` for `/api/health`, `info` otherwise. SSE routes + return their `Response` immediately, so their duration is the time to open the stream. +- **Metrics: OpenTelemetry SDK** (`apps/api/src/lib/metrics.ts`), pushed to OpenObserve over OTLP/HTTP + (`/api//v1/metrics`, cumulative temporality) every `METRICS_EXPORT_INTERVAL_MS` (15 s) when + `OPENOBSERVE_URL` is set; otherwise the global meter is a no-op. The same request middleware records + `http.server.request.duration` (histogram, seconds; attributes `http.request.method`, `http.route`, + `http.response.status_code`) and `http.server.active_requests`. Always use the route pattern + (`routePath(c, -1)`), never the raw path, as an attribute. The OpenObserve settings live in + `lib/openobserve.ts`, shared by logs and metrics. Dashboard guide: `docs/openobserve-dashboard.md` (importable JSON: `docs/openobserve-dashboard.json`). - Unexpected throws are turned into Problem Details by `app.onError`; unmatched routes by `app.notFound` (both in `apps/api/src/lib/problem-details.ts`). - `createApp()` middleware order matters: `secureHeaders` → `cors` (origins from `CORS_ORIGIN`, credentials on) diff --git a/README.md b/README.md index 5574566..61fbf7f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Monorepo with a Bun + Hono API and a React + Vite admin app. | Workspace | What it is | | ----------------- | ----------------------------------------------------------------------- | -| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, Pino logging | +| `apps/api` | Bun + Hono backend, Prisma (Postgres), Zod validation, LogTape logging | | `apps/web` | React + Vite + TypeScript frontend, shadcn/ui, TanStack Router + Query | | `packages/shared` | `@superlist/shared` — Result pattern and RFC 9457 Problem Details types | diff --git a/STACK.md b/STACK.md index 66e313a..0f15af9 100644 --- a/STACK.md +++ b/STACK.md @@ -1,5 +1,5 @@ - Monorepo con TURBO -- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con Pino +- Backend en Bun con Hono. Acceso a DB Postgres con Prisma. Validación con Zod. Logging con LogTape (consola + OpenObserve vía OTLP) - Salidas del backend según RFC 9457 (Problem Details) - Frontend en React con vite y typescript. Componentes Shadcn - Rutas del frontend con TanStack Router usando file-based routing diff --git a/apps/api/.env.example b/apps/api/.env.example index d580278..c1a9b07 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -4,8 +4,18 @@ CORS_ORIGIN="http://localhost:7153" BETTER_AUTH_SECRET="change-me-with-openssl-rand-base64-32" BETTER_AUTH_URL="http://localhost:4100" NODE_ENV="development" -# Optional: Pino log level (defaults to "debug" outside production, "info" in production) +# Optional: log level (trace, debug, info, warning, error, fatal) (defaults to "debug" outside production, "info" in production) # LOG_LEVEL="info" +# Optional: ship logs to OpenObserve over OTLP/HTTP. Without OPENOBSERVE_URL logs only go to the console. +# OPENOBSERVE_URL="http://localhost:5080" +# Optional: organization (defaults to "default") and stream (defaults to "superlist") +# OPENOBSERVE_ORG="default" +# OPENOBSERVE_STREAM="superlist" +# OpenObserve user email and password (sent as Basic auth) +# OPENOBSERVE_USER="root@example.com" +# OPENOBSERVE_PASSWORD="" +# Optional: how often HTTP metrics are pushed to OpenObserve, in milliseconds (defaults to 15000) +# METRICS_EXPORT_INTERVAL_MS="15000" # Resend API key used to send invitation and password reset emails. Without it, emails are logged instead. # RESEND_API_KEY="re_xxxxxxxx" # From address for outgoing email (must be a verified Resend sender) diff --git a/apps/api/package.json b/apps/api/package.json index 31c150b..f2c63e9 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,14 +18,19 @@ "dependencies": { "@better-auth/passkey": "1.7.7", "@hono/zod-validator": "^0.9.1", + "@logtape/logtape": "^2.4.2", + "@logtape/otel": "^2.4.2", + "@logtape/pretty": "^2.4.2", + "@opentelemetry/api": "1.9.0", + "@opentelemetry/exporter-metrics-otlp-http": "0.208.0", + "@opentelemetry/resources": "2.2.0", + "@opentelemetry/sdk-metrics": "2.2.0", "@prisma/adapter-pg": "^7.10.0", "@prisma/client": "^7.10.0", "@superlist/shared": "workspace:*", "better-auth": "^1.7.7", "hono": "^4.13.13", "pg": "^8.23.1", - "pino": "^10.4.0", - "pino-pretty": "^13.2.0", "resend": "^6.32.1", "zod": "^4.6.7" }, diff --git a/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql b/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql new file mode 100644 index 0000000..9c6c955 --- /dev/null +++ b/apps/api/prisma/migrations/20261125121747_pinned_lists/migration.sql @@ -0,0 +1,7 @@ +-- AlterTable +ALTER TABLE "shopping_list_members" ADD COLUMN "icon" TEXT, +ADD COLUMN "is_pinned" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "pinned_order" INTEGER; + +-- CreateIndex +CREATE INDEX "shopping_list_members_user_id_is_pinned_idx" ON "shopping_list_members"("user_id", "is_pinned"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index e6f2267..63ad81c 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -168,11 +168,18 @@ model ShoppingListMember { user User @relation(fields: [userId], references: [id], onDelete: Cascade) role ListRole @default(collaborator) isPrimary Boolean @default(false) @map("is_primary") + /// Per user: the list is pinned to the always-visible bar (at most 4 per user). + isPinned Boolean @default(false) @map("is_pinned") + /// Position among the user's pinned lists (pin order); null when not pinned. + pinnedOrder Int? @map("pinned_order") + /// Per user: key of the icon chosen for the list (see `LIST_ICONS` in `@superlist/shared`). + icon String? createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") @@unique([listId, userId]) @@index([userId, isPrimary]) + @@index([userId, isPinned]) @@map("shopping_list_members") } diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 78d7579..938cdc7 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -1,16 +1,21 @@ +import { withContext } from '@logtape/logtape' import { Hono } from 'hono' import { cors } from 'hono/cors' import { requestId } from 'hono/request-id' +import { routePath } from 'hono/route' import { secureHeaders } from 'hono/secure-headers' import { auth } from '@/lib/auth' import { logger } from '@/lib/logger' +import { httpMetrics } from '@/lib/metrics' import { errorHandler, notFoundHandler } from '@/lib/problem-details' import { healthModule } from '@/modules/health' import { invitationsModule } from '@/modules/invitations' import { listsModule } from '@/modules/lists' import { voiceModule } from '@/modules/voice' -import type { AppEnv } from '@/types' +import type { AppEnv, SessionUser } from '@/types' + +const httpLogger = logger.getChild('http') const allowedOrigins = (process.env.CORS_ORIGIN ?? 'http://localhost:7153') .split(',') @@ -24,20 +29,53 @@ export function createApp() { app.use(cors({ origin: allowedOrigins, credentials: true })) app.use(requestId()) app.use(async (c, next) => { - const requestLogger = logger.child({ requestId: c.get('requestId') }) - c.set('logger', requestLogger) + const requestId = c.get('requestId') + c.set('logger', httpLogger.with({ requestId })) + + const http = httpMetrics() + const method = c.req.method + http.activeRequests.add(1, { 'http.request.method': method }) const start = performance.now() - await next() - requestLogger.info( - { - method: c.req.method, - path: c.req.path, - status: c.res.status, - durationMs: Math.round(performance.now() - start), - }, - 'request', - ) + try { + // Every record logged while the request runs (module loggers included) + // inherits the requestId through LogTape's implicit context. + await withContext({ requestId }, next) + } finally { + http.activeRequests.add(-1, { 'http.request.method': method }) + } + const elapsedMs = performance.now() - start + const durationMs = Math.round(elapsedMs * 10) / 10 + + const status = c.res.status + const route = routePath(c, -1) + // SSE streams (/events) return their Response right away, so for them this is + // the time to open the stream, not the lifetime of the connection. + http.duration.record(elapsedMs / 1000, { + 'http.request.method': method, + // The Hono pattern (/api/lists/:listId), never the raw path, to keep cardinality low. + 'http.route': route, + 'http.response.status_code': status, + }) + + const userId = (c.get('user') as SessionUser | undefined)?.id + const properties = { + requestId, + method, + path: c.req.path, + route, + status, + durationMs, + userAgent: c.req.header('user-agent'), + ...(userId && { userId }), + } + const message = '{method} {path} {status} in {durationMs} ms' + + if (status >= 500) httpLogger.error(message, properties) + else if (status >= 400) httpLogger.warn(message, properties) + // The container healthcheck hits /api/health every 10 s. + else if (c.req.path === '/api/health') httpLogger.debug(message, properties) + else httpLogger.info(message, properties) }) // Every API route lives under /api: in production nginx serves the SPA on the diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 04cbdb3..0b2ed5b 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,11 +1,25 @@ +import { dispose } from '@logtape/logtape' + import { createApp } from '@/app' -import { logger } from '@/lib/logger' +import { configureLogging, logger } from '@/lib/logger' +import { configureMetrics, shutdownMetrics } from '@/lib/metrics' + +await configureLogging() +const metricsEnabled = configureMetrics() const port = Number(process.env.PORT ?? 4100) const app = createApp() -logger.info({ port }, 'api listening') +logger.info('api listening on port {port}', { port, metricsEnabled }) + +// Flush buffered logs and the last metrics batch before exiting. +for (const signal of ['SIGINT', 'SIGTERM'] as const) { + process.once(signal, async () => { + await Promise.allSettled([shutdownMetrics(), dispose()]) + process.exit(0) + }) +} export default { port, diff --git a/apps/api/src/lib/auth.ts b/apps/api/src/lib/auth.ts index d28da11..9730dc2 100644 --- a/apps/api/src/lib/auth.ts +++ b/apps/api/src/lib/auth.ts @@ -55,7 +55,7 @@ export const auth = betterAuth({ to: email, ...passwordResetEmail({ otp, expiresInMinutes: OTP_EXPIRES_IN_SECONDS / 60 }), }).catch((error: unknown) => { - logger.error({ err: error, to: email }, 'failed to send the password reset email') + logger.error('failed to send the password reset email', { error, to: email }) }) }, }), diff --git a/apps/api/src/lib/logger.ts b/apps/api/src/lib/logger.ts index 03fda00..f8d43ad 100644 --- a/apps/api/src/lib/logger.ts +++ b/apps/api/src/lib/logger.ts @@ -1,21 +1,99 @@ -import { pino } from 'pino' +import { AsyncLocalStorage } from 'node:async_hooks' + +import { + configure, + getConsoleSink, + getLogger, + isLogLevel, + jsonLinesFormatter, + type Logger, + type LogLevel, + type Sink, +} from '@logtape/logtape' +import { getOpenTelemetrySink } from '@logtape/otel' +import { getPrettyFormatter } from '@logtape/pretty' + +import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve' + +export type { Logger } from '@logtape/logtape' const isProduction = process.env.NODE_ENV === 'production' /** - * Single logger instance for the whole API. Import it wherever you need to log — - * never use `console.log` in the backend. + * Root logger of the API (category `superlist`). Import it wherever you need to + * log — never use `console.log` in the backend. Inside a request, prefer + * `c.get('logger')`; either way every record emitted while the request runs + * carries its `requestId` (see `withContext` in `app.ts`). + * + * LogTape loggers are inert until `configureLogging()` runs (from `index.ts`), + * so tests that import modules using it stay silent. */ -export const logger = pino({ - level: process.env.LOG_LEVEL || (isProduction ? 'info' : 'debug'), - ...(isProduction - ? {} - : { - transport: { - target: 'pino-pretty', - options: { colorize: true, translateTime: 'HH:MM:ss', ignore: 'pid,hostname' }, - }, - }), -}) +export const logger: Logger = getLogger(['superlist']) -export type Logger = typeof logger +/** Accepts LogTape levels plus Pino-style aliases (`warn`) for `LOG_LEVEL`. */ +function resolveLevel(value: string | undefined): LogLevel { + const level = value?.trim().toLowerCase() + if (level === 'warn') return 'warning' + if (level && isLogLevel(level)) return level + + return isProduction ? 'info' : 'debug' +} + +/** + * Ships logs to OpenObserve over OTLP/HTTP (`/api//v1/logs`), routed to a + * stream by the `stream-name` header. Returns `null` when it is not configured. + */ +function openObserveSink(): Sink | null { + const config = getOpenObserveConfig() + if (!config) return null + + return getOpenTelemetrySink({ + serviceName: SERVICE_NAME, + // Nested property objects become JSON instead of util.inspect output. + objectRenderer: 'json', + otlpExporterConfig: { + url: `${config.otlpBaseUrl}/v1/logs`, + headers: { Authorization: config.authorization, 'stream-name': config.logStream }, + }, + }) +} + +/** + * Configures LogTape once, at startup: console output (pretty in development, + * JSON lines in production) plus OpenObserve when `OPENOBSERVE_URL` is set. + * Call `dispose()` from `@logtape/logtape` on shutdown to flush pending records. + */ +export async function configureLogging(): Promise { + const consoleSink = getConsoleSink({ + formatter: isProduction + ? jsonLinesFormatter + : getPrettyFormatter({ + properties: true, + categoryWidth: 16, + wordWrap: false, + // Interpolate strings bare ("GET /api/lists") instead of quoted. + value: 'bare', + }), + }) + const openObserve = openObserveSink() + + const sinks: Record = { console: consoleSink } + if (openObserve) sinks.openObserve = openObserve + + await configure({ + sinks, + contextLocalStorage: new AsyncLocalStorage(), + loggers: [ + { + category: ['superlist'], + sinks: Object.keys(sinks), + lowestLevel: resolveLevel(process.env.LOG_LEVEL), + }, + { category: ['logtape', 'meta'], sinks: ['console'], lowestLevel: 'warning' }, + ], + }) + + if (openObserve) { + logger.info('shipping logs to OpenObserve at {url}', { url: process.env.OPENOBSERVE_URL }) + } +} diff --git a/apps/api/src/lib/mailer.ts b/apps/api/src/lib/mailer.ts index b3fb2fb..c8f1896 100644 --- a/apps/api/src/lib/mailer.ts +++ b/apps/api/src/lib/mailer.ts @@ -24,17 +24,18 @@ function getClient(): Resend | null { /** * 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 + * it logs the message instead of sending it, so invitation links are * still discoverable in the terminal. */ export async function sendEmail(email: Email): Promise { 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', - ) + logger.info('email not sent (RESEND_API_KEY is not set) — logging payload instead', { + to: email.to, + subject: email.subject, + text: email.text, + }) return } diff --git a/apps/api/src/lib/metrics.ts b/apps/api/src/lib/metrics.ts new file mode 100644 index 0000000..c639ee1 --- /dev/null +++ b/apps/api/src/lib/metrics.ts @@ -0,0 +1,92 @@ +import { type Histogram, metrics, type UpDownCounter } from '@opentelemetry/api' +import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http' +import { resourceFromAttributes } from '@opentelemetry/resources' +import { + AggregationTemporality, + AggregationType, + MeterProvider, + PeriodicExportingMetricReader, +} from '@opentelemetry/sdk-metrics' + +import { getOpenObserveConfig, SERVICE_NAME } from '@/lib/openobserve' + +const DEFAULT_EXPORT_INTERVAL_MS = 15_000 + +/** Bucket bounds (seconds) of the request duration histogram: 5 ms … 10 s. */ +const DURATION_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] + +let provider: MeterProvider | null = null + +/** + * Starts exporting metrics to OpenObserve (`/api//v1/metrics`) every + * `METRICS_EXPORT_INTERVAL_MS` (15 s by default). Without `OPENOBSERVE_URL` the + * global meter stays a no-op, so instruments cost nothing in tests or locally. + */ +export function configureMetrics(): boolean { + const config = getOpenObserveConfig() + if (!config) return false + + const exporter = new OTLPMetricExporter({ + url: `${config.otlpBaseUrl}/v1/metrics`, + headers: { Authorization: config.authorization }, + // Cumulative is what OpenObserve's PromQL (rate, histogram_quantile) expects. + temporalityPreference: AggregationTemporality.CUMULATIVE, + }) + + provider = new MeterProvider({ + resource: resourceFromAttributes({ 'service.name': SERVICE_NAME }), + views: [ + { + instrumentName: 'http.server.request.duration', + aggregation: { + type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM, + options: { boundaries: DURATION_BUCKETS }, + }, + }, + ], + readers: [ + new PeriodicExportingMetricReader({ + exporter, + exportIntervalMillis: + Number(process.env.METRICS_EXPORT_INTERVAL_MS) || DEFAULT_EXPORT_INTERVAL_MS, + }), + ], + }) + metrics.setGlobalMeterProvider(provider) + + return true +} + +/** Flushes the last batch and stops the exporter (call on shutdown). */ +export async function shutdownMetrics(): Promise { + await provider?.shutdown() +} + +type HttpInstruments = { + duration: Histogram + activeRequests: UpDownCounter +} + +let http: HttpInstruments | null = null + +/** + * HTTP server instruments, following the OpenTelemetry semantic conventions. + * Created lazily so they bind to the provider set by `configureMetrics()`. + */ +export function httpMetrics(): HttpInstruments { + if (!http) { + const meter = metrics.getMeter(SERVICE_NAME) + http = { + duration: meter.createHistogram('http.server.request.duration', { + description: 'Duration of HTTP server requests.', + unit: 's', + }), + activeRequests: meter.createUpDownCounter('http.server.active_requests', { + description: 'Number of HTTP server requests in flight.', + unit: '{request}', + }), + } + } + + return http +} diff --git a/apps/api/src/lib/openobserve.ts b/apps/api/src/lib/openobserve.ts new file mode 100644 index 0000000..54402f3 --- /dev/null +++ b/apps/api/src/lib/openobserve.ts @@ -0,0 +1,30 @@ +/** Service name reported to OpenObserve for logs and metrics. */ +export const SERVICE_NAME = 'superlist-api' + +export type OpenObserveConfig = { + /** Base of the OTLP/HTTP endpoints: `/api/` (append `/v1/logs`, `/v1/metrics`). */ + otlpBaseUrl: string + /** Basic auth (user email + password) for every OTLP request. */ + authorization: string + /** Stream that receives the logs (`stream-name` header); metrics get one stream per metric. */ + logStream: string +} + +/** + * Reads the OpenObserve settings from the environment, or `null` when + * `OPENOBSERVE_URL` is not set (logs and metrics then stay local). + */ +export function getOpenObserveConfig(): OpenObserveConfig | null { + const baseUrl = process.env.OPENOBSERVE_URL?.trim().replace(/\/+$/, '') + if (!baseUrl) return null + + const org = process.env.OPENOBSERVE_ORG || 'default' + const user = process.env.OPENOBSERVE_USER ?? '' + const password = process.env.OPENOBSERVE_PASSWORD ?? '' + + return { + otlpBaseUrl: `${baseUrl}/api/${org}`, + authorization: `Basic ${btoa(`${user}:${password}`)}`, + logStream: process.env.OPENOBSERVE_STREAM || 'superlist', + } +} diff --git a/apps/api/src/lib/problem-details.ts b/apps/api/src/lib/problem-details.ts index 067dcd3..790d614 100644 --- a/apps/api/src/lib/problem-details.ts +++ b/apps/api/src/lib/problem-details.ts @@ -25,7 +25,7 @@ export function errorHandler(error: Error, c: Context) { ) } - logger.error({ err: error, path: c.req.path }, 'unhandled error') + logger.error('unhandled error on {path}', { error, path: c.req.path }) return problemResponse( c, diff --git a/apps/api/src/modules/invitations/create/use-case.ts b/apps/api/src/modules/invitations/create/use-case.ts index ea1bc77..cb351f4 100644 --- a/apps/api/src/modules/invitations/create/use-case.ts +++ b/apps/api/src/modules/invitations/create/use-case.ts @@ -137,7 +137,7 @@ export class CreateInvitation { // 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') + logger.warn('could not send the invitation email', { error, to: email }) }) return Ok({ status: 'added', email }) @@ -148,7 +148,7 @@ export class CreateInvitation { } 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') + logger.error('failed to send the invitation email', { error, to: email }) return Failure( problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'), diff --git a/apps/api/src/modules/lists/create/use-case.test.ts b/apps/api/src/modules/lists/create/use-case.test.ts index 8e72158..fe006a7 100644 --- a/apps/api/src/modules/lists/create/use-case.test.ts +++ b/apps/api/src/modules/lists/create/use-case.test.ts @@ -33,12 +33,14 @@ function createDb({ 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 }, + _count: { members: membershipsOnCreate, items: 0 }, members: [ { id: 'member-1', role: 'owner', isPrimary: input.data.members.create.isPrimary, + isPinned: false, + icon: null, }, ], } @@ -65,6 +67,9 @@ describe('CreateShoppingList', () => { name: 'Compra semanal', role: 'owner', isPrimary: true, + isPinned: false, + icon: null, + pendingCount: 0, memberCount: 1, createdAt: '2026-10-15T00:00:00.000Z', updatedAt: '2026-10-15T00:00:00.000Z', diff --git a/apps/api/src/modules/lists/create/use-case.ts b/apps/api/src/modules/lists/create/use-case.ts index 80c97b1..fa596ee 100644 --- a/apps/api/src/modules/lists/create/use-case.ts +++ b/apps/api/src/modules/lists/create/use-case.ts @@ -2,7 +2,7 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from ' import type { Database } from '@/lib/prisma' -import { toSummary } from '../serialize' +import { summaryCountInclude, toSummary } from '../serialize' /** Creates a shopping list owned by the user. The first list becomes primary. */ export class CreateShoppingList { @@ -29,7 +29,7 @@ export class CreateShoppingList { }, }, include: { - _count: { select: { members: true } }, + ...summaryCountInclude, members: { where: { userId: input.userId } }, }, }) @@ -44,6 +44,8 @@ export class CreateShoppingList { toSummary({ role: membership.role, isPrimary: membership.isPrimary, + isPinned: membership.isPinned, + icon: membership.icon, list: { id: list.id, name: list.name, diff --git a/apps/api/src/modules/lists/index.ts b/apps/api/src/modules/lists/index.ts index 59e5d78..fcb07bf 100644 --- a/apps/api/src/modules/lists/index.ts +++ b/apps/api/src/modules/lists/index.ts @@ -7,6 +7,7 @@ import { listEventsRoute } from './events/route' import { getListRoute } from './get/route' import { listItemsModule } from './items' import { listListsRoute } from './list/route' +import { updateListPreferencesRoute } from './preferences/route' import { setPrimaryListRoute } from './set-primary/route' import { updateListRoute } from './update/route' @@ -17,5 +18,6 @@ export const listsModule = new Hono() .route('/', getListRoute) .route('/', updateListRoute) .route('/', setPrimaryListRoute) + .route('/', updateListPreferencesRoute) .route('/:listId/items', listItemsModule) .route('/:listId/events', listEventsRoute) diff --git a/apps/api/src/modules/lists/list/use-case.test.ts b/apps/api/src/modules/lists/list/use-case.test.ts new file mode 100644 index 0000000..e147044 --- /dev/null +++ b/apps/api/src/modules/lists/list/use-case.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'bun:test' + +import type { Database } from '@/lib/prisma' + +import { ListShoppingLists } from './use-case' + +describe('ListShoppingLists', () => { + it('returns the pending count and the user preferences of each list', async () => { + const queries: unknown[] = [] + const db = { + shoppingListMember: { + findMany: async (args: unknown) => { + queries.push(args) + + return [ + { + role: 'owner', + isPrimary: false, + isPinned: true, + icon: 'unknown-icon', + list: { + id: 'list-1', + name: 'Verdulería', + createdAt: new Date('2026-11-01T00:00:00.000Z'), + updatedAt: new Date('2026-11-02T00:00:00.000Z'), + _count: { members: 1, items: 4 }, + }, + }, + ] + }, + }, + } + + const result = await new ListShoppingLists(db as unknown as Database).execute({ + userId: 'user-1', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(result.value).toEqual([ + { + id: 'list-1', + name: 'Verdulería', + role: 'owner', + isPrimary: false, + isPinned: true, + icon: null, + pendingCount: 4, + memberCount: 1, + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: '2026-11-02T00:00:00.000Z', + }, + ]) + expect(queries[0]).toMatchObject({ + include: { + list: { include: { _count: { select: { items: { where: { completed: false } } } } } }, + }, + }) + }) +}) diff --git a/apps/api/src/modules/lists/list/use-case.ts b/apps/api/src/modules/lists/list/use-case.ts index 6a12446..c0ed8cd 100644 --- a/apps/api/src/modules/lists/list/use-case.ts +++ b/apps/api/src/modules/lists/list/use-case.ts @@ -2,27 +2,27 @@ import { Ok, type ProblemDetails, type Result, type ShoppingListSummary } from ' import type { Database } from '@/lib/prisma' -/** Lists every shopping list the user belongs to (owned or shared). */ +import { summaryCountInclude, toSummary } from '../serialize' + +/** + * Lists every shopping list the user belongs to (owned or shared): the primary + * one first, then the pinned ones in pin order, then the rest, newest first. + */ export class ListShoppingLists { constructor(private readonly db: Database) {} async execute(input: { userId: string }): Promise> { const memberships = await this.db.shoppingListMember.findMany({ where: { userId: input.userId }, - include: { list: { include: { _count: { select: { members: true } } } } }, - orderBy: [{ isPrimary: 'desc' }, { list: { createdAt: 'desc' } }], + include: { list: { include: summaryCountInclude } }, + orderBy: [ + { isPrimary: 'desc' }, + { isPinned: 'desc' }, + { pinnedOrder: { sort: 'asc', nulls: 'last' } }, + { 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) + return Ok(memberships.map(toSummary)) } } diff --git a/apps/api/src/modules/lists/preferences/route.ts b/apps/api/src/modules/lists/preferences/route.ts new file mode 100644 index 0000000..61bf951 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/route.ts @@ -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 { UpdateListPreferencesSchema } from './schema' +import { UpdateListPreferences } from './use-case' + +/** PATCH /lists/:listId/preferences — pins the list or changes its icon (per user). */ +export const updateListPreferencesRoute = new Hono().patch( + '/:listId/preferences', + requireSession, + validate.param(ListParamsSchema), + validate.json(UpdateListPreferencesSchema), + async (c) => { + const { listId } = c.req.valid('param') + const body = c.req.valid('json') + const result = await new UpdateListPreferences(prisma).execute({ + listId, + userId: c.get('user').id, + ...body, + }) + + return resultJson(c, result) + }, +) diff --git a/apps/api/src/modules/lists/preferences/schema.ts b/apps/api/src/modules/lists/preferences/schema.ts new file mode 100644 index 0000000..f12bfe9 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/schema.ts @@ -0,0 +1,14 @@ +import { ListIconSchema } from '@superlist/shared' +import { z } from 'zod' + +/** Body of `PATCH /lists/:listId/preferences`: the user's own settings for the list. */ +export const UpdateListPreferencesSchema = z + .object({ + isPinned: z.boolean().optional(), + icon: ListIconSchema.nullable().optional(), + }) + .refine((body) => body.isPinned !== undefined || body.icon !== undefined, { + message: 'Indica al menos una preferencia para actualizar', + }) + +export type UpdateListPreferencesInput = z.infer diff --git a/apps/api/src/modules/lists/preferences/use-case.test.ts b/apps/api/src/modules/lists/preferences/use-case.test.ts new file mode 100644 index 0000000..07c4320 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/use-case.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from 'bun:test' + +import type { Database } from '@/lib/prisma' + +import { UpdateListPreferences } from './use-case' + +type Membership = { + role: 'owner' | 'collaborator' + isPrimary: boolean + isPinned: boolean + icon: string | null +} + +function createDb({ + membership, + pinnedCount = 0, + maxPinnedOrder = null, +}: { + membership: Membership | null + pinnedCount?: number + maxPinnedOrder?: number | null +}) { + const updates: Array<{ data: Record }> = [] + + const tx = { + shoppingListMember: { + findUnique: async () => membership, + aggregate: async () => ({ + _count: { _all: pinnedCount }, + _max: { pinnedOrder: maxPinnedOrder }, + }), + update: async (args: { data: Record }) => { + updates.push(args) + + return { + ...membership, + ...args.data, + list: { + id: 'list-1', + name: 'Casa de fin de semana', + createdAt: new Date('2026-11-01T00:00:00.000Z'), + updatedAt: new Date('2026-11-01T00:00:00.000Z'), + _count: { members: 2, items: 3 }, + }, + } + }, + }, + } + + const db = { $transaction: async (fn: (client: typeof tx) => unknown) => fn(tx) } + + return { db: db as unknown as Database, updates } +} + +const collaborator: Membership = { + role: 'collaborator', + isPrimary: false, + isPinned: false, + icon: null, +} + +describe('UpdateListPreferences', () => { + it('answers 404 when the user does not belong to the list', async () => { + const { db, updates } = createDb({ membership: null }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(404) + expect(updates).toHaveLength(0) + }) + + it('pins the list after the last pinned one and returns its pending count', async () => { + const { db, updates } = createDb({ + membership: collaborator, + pinnedCount: 2, + maxPinnedOrder: 5, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + icon: 'park', + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(updates[0]?.data).toEqual({ isPinned: true, pinnedOrder: 6, icon: 'park' }) + expect(result.value).toMatchObject({ + isPinned: true, + icon: 'park', + pendingCount: 3, + memberCount: 2, + }) + }) + + it('refuses to pin more than four lists', async () => { + const { db, updates } = createDb({ + membership: collaborator, + pinnedCount: 4, + maxPinnedOrder: 4, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(409) + expect(updates).toHaveLength(0) + }) + + it('unpins the list and clears its position', async () => { + const { db, updates } = createDb({ membership: { ...collaborator, isPinned: true } }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: false, + }) + + expect(result.ok).toBe(true) + expect(updates[0]?.data).toEqual({ isPinned: false, pinnedOrder: null }) + }) + + it('changes only the icon of an already pinned list', async () => { + const { db, updates } = createDb({ + membership: { ...collaborator, isPinned: true, icon: 'carrot' }, + }) + const result = await new UpdateListPreferences(db).execute({ + listId: 'list-1', + userId: 'user-1', + isPinned: true, + icon: null, + }) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + expect(updates[0]?.data).toEqual({ icon: null }) + expect(result.value.icon).toBeNull() + }) +}) diff --git a/apps/api/src/modules/lists/preferences/use-case.ts b/apps/api/src/modules/lists/preferences/use-case.ts new file mode 100644 index 0000000..493f325 --- /dev/null +++ b/apps/api/src/modules/lists/preferences/use-case.ts @@ -0,0 +1,76 @@ +import { + Failure, + type ListIcon, + MAX_PINNED_LISTS, + Ok, + type ProblemDetails, + problems, + type Result, + type ShoppingListSummary, +} from '@superlist/shared' + +import type { Database } from '@/lib/prisma' + +import { summaryCountInclude, toSummary } from '../serialize' + +/** + * Updates the user's own settings for a list: whether it is pinned to the + * always-visible bar and which icon it shows. Any member may do it, because + * the settings are per user (like the primary list), not shared with the list. + */ +export class UpdateListPreferences { + constructor(private readonly db: Database) {} + + async execute(input: { + listId: string + userId: string + isPinned?: boolean + icon?: ListIcon | null + }): Promise> { + const where = { listId_userId: { listId: input.listId, userId: input.userId } } + + return this.db.$transaction(async (tx) => { + const membership = await tx.shoppingListMember.findUnique({ where }) + + if (!membership) { + return Failure(problems.notFound('La lista no existe o no tienes acceso.')) + } + + const data: { isPinned?: boolean; pinnedOrder?: number | null; icon?: ListIcon | null } = {} + + if (input.icon !== undefined) data.icon = input.icon + + if (input.isPinned === true && !membership.isPinned) { + const pinned = await tx.shoppingListMember.aggregate({ + where: { userId: input.userId, isPinned: true }, + _count: { _all: true }, + _max: { pinnedOrder: true }, + }) + + if (pinned._count._all >= MAX_PINNED_LISTS) { + return Failure( + problems.conflict( + `Puedes fijar hasta ${MAX_PINNED_LISTS} listas. Desfija otra para fijar esta.`, + ), + ) + } + + data.isPinned = true + data.pinnedOrder = (pinned._max.pinnedOrder ?? 0) + 1 + } + + if (input.isPinned === false && membership.isPinned) { + data.isPinned = false + data.pinnedOrder = null + } + + const updated = await tx.shoppingListMember.update({ + where, + data, + include: { list: { include: summaryCountInclude } }, + }) + + return Ok(toSummary(updated)) + }) + } +} diff --git a/apps/api/src/modules/lists/serialize.ts b/apps/api/src/modules/lists/serialize.ts index 0a86889..60efa42 100644 --- a/apps/api/src/modules/lists/serialize.ts +++ b/apps/api/src/modules/lists/serialize.ts @@ -1,4 +1,17 @@ -import type { ListMember, ShoppingListDetail, ShoppingListSummary } from '@superlist/shared' +import { + type ListIcon, + ListIconSchema, + type ListMember, + type ShoppingListDetail, + type ShoppingListSummary, +} from '@superlist/shared' + +/** Reads a stored icon key; unknown keys (e.g. one removed from the set) fall back to none. */ +export function toListIcon(icon: string | null): ListIcon | null { + const parsed = ListIconSchema.safeParse(icon) + + return parsed.success ? parsed.data : null +} type ListRow = { id: string @@ -10,16 +23,29 @@ type ListRow = { type MemberRow = { role: 'owner' | 'collaborator' isPrimary: boolean - list: ListRow & { _count: { members: number } } + isPinned: boolean + icon: string | null + list: ListRow & { _count: { members: number; items: number } } } -/** Maps a membership (with its list and member count) to the summary DTO. */ +/** + * Prisma `include` for a summary: the member count plus the pending items + * (`items` counts only the ones not bought yet). + */ +export const summaryCountInclude = { + _count: { select: { members: true, items: { where: { completed: false } } } }, +} as const + +/** Maps a membership (with its list, member and pending counts) 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, + isPinned: member.isPinned, + icon: toListIcon(member.icon), + pendingCount: member.list._count.items, memberCount: member.list._count.members, createdAt: member.list.createdAt.toISOString(), updatedAt: member.list.updatedAt.toISOString(), @@ -29,6 +55,8 @@ export function toSummary(member: MemberRow): ShoppingListSummary { type DetailRow = { role: 'owner' | 'collaborator' isPrimary: boolean + isPinned: boolean + icon: string | null list: ListRow & { members: Array<{ id: string @@ -65,6 +93,8 @@ export function toDetail(member: DetailRow): ShoppingListDetail { name: member.list.name, role: member.role, isPrimary: member.isPrimary, + isPinned: member.isPinned, + icon: toListIcon(member.icon), members, invitations: member.list.invitations.map((invitation) => ({ id: invitation.id, diff --git a/apps/api/src/modules/lists/update/use-case.ts b/apps/api/src/modules/lists/update/use-case.ts index a78abe5..a39b1c4 100644 --- a/apps/api/src/modules/lists/update/use-case.ts +++ b/apps/api/src/modules/lists/update/use-case.ts @@ -10,6 +10,8 @@ import { import { type ListEvents, listEvents } from '@/lib/events' import type { Database } from '@/lib/prisma' +import { summaryCountInclude, toSummary } from '../serialize' + /** Renames a list. Only the owner (`role: owner`) may do it. */ export class UpdateShoppingList { constructor( @@ -37,19 +39,11 @@ export class UpdateShoppingList { const list = await this.db.shoppingList.update({ where: { id: input.listId }, data: { name: input.name }, - include: { _count: { select: { members: true } } }, + include: summaryCountInclude, }) this.events.publish({ type: 'list.updated', listId: list.id, name: list.name }) - 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(), - }) + return Ok(toSummary({ ...membership, list })) } } diff --git a/apps/api/src/modules/voice/split/use-case.ts b/apps/api/src/modules/voice/split/use-case.ts index 7893a88..4c8c6e0 100644 --- a/apps/api/src/modules/voice/split/use-case.ts +++ b/apps/api/src/modules/voice/split/use-case.ts @@ -47,7 +47,10 @@ export class SplitVoiceText { } private fallback(text: string, reason: string): Result { - this.logger.warn({ reason, textLength: text.length }, 'voice split: using the fallback split') + this.logger.warn('voice split: using the fallback split ({reason})', { + reason, + textLength: text.length, + }) return Ok({ items: fallbackSplit(text) }) } diff --git a/apps/web/src/components/install-prompt.tsx b/apps/web/src/components/install-prompt.tsx index 2036845..7546b77 100644 --- a/apps/web/src/components/install-prompt.tsx +++ b/apps/web/src/components/install-prompt.tsx @@ -9,7 +9,7 @@ export function InstallPrompt() { if (!visible) return null return ( -
+
{needsManualInstructions ? ( diff --git a/apps/web/src/components/items/dictate-fab.tsx b/apps/web/src/components/items/dictate-fab.tsx index 0161bbd..fe44548 100644 --- a/apps/web/src/components/items/dictate-fab.tsx +++ b/apps/web/src/components/items/dictate-fab.tsx @@ -57,7 +57,7 @@ export function DictateFab({ listId }: DictateFabProps) { aria-label="Dictar ítems" aria-haspopup="dialog" aria-expanded={open} - className="fixed right-4 bottom-[calc(4.5rem+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6" + className="fixed right-4 bottom-[calc(var(--bottom-nav-height,4.5rem)+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6" onClick={() => { setOpen(true) // Called right in the click, before any state update, so the browser still diff --git a/apps/web/src/components/layout/app-sidebar.tsx b/apps/web/src/components/layout/app-sidebar.tsx index 8fc79f1..ee81376 100644 --- a/apps/web/src/components/layout/app-sidebar.tsx +++ b/apps/web/src/components/layout/app-sidebar.tsx @@ -3,6 +3,7 @@ import { AppLogo } from '@/components/app-logo' import { focusNewItemInput } from '@/components/items/create-item-form' import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items' import { NavUser } from '@/components/layout/nav-user' +import { PinnedListsSidebarGroup } from '@/components/layout/pinned-lists' import { Sidebar, SidebarContent, @@ -60,6 +61,7 @@ export function AppSidebar() { ))} + diff --git a/apps/web/src/components/layout/bottom-nav.tsx b/apps/web/src/components/layout/bottom-nav.tsx index 54a6c6a..d338d7a 100644 --- a/apps/web/src/components/layout/bottom-nav.tsx +++ b/apps/web/src/components/layout/bottom-nav.tsx @@ -2,6 +2,7 @@ import { Link, useRouterState } from '@tanstack/react-router' import { focusNewItemInput } from '@/components/items/create-item-form' import { isNavItemActive, NAV_ITEMS } from '@/components/layout/nav-items' +import { PinnedListsBar } from '@/components/layout/pinned-lists' import { cn } from '@/lib/utils' export function BottomNav() { @@ -9,6 +10,7 @@ export function BottomNav() { return (