Compare commits

..
17 Commits
Author SHA1 Message Date
davide 1247608441 update claude plugin 2026-05-25 17:09:25 +02:00
davide aac4ee6e43 chore(docker): use local bind mount for uploads
Store uploaded files under data/uploads for both the app and Caddy instead of the named Docker volume. Update .gitignore to keep runtime data out of Git while preserving the uploads directory placeholder.
2026-05-25 17:09:16 +02:00
davide 126a74cddb docs: rewrite setup guide with Stripe webhook and bug fix notes
- Clarify that STRIPE_SECRET_KEY is required from step 2
- Document --profile dev as the recommended local startup command
- Replace manual stripe listen instructions with docker-compose service
- Add Stripe test cards and payment verification checklist
- Fix docker compose restart → --force-recreate in webhook setup steps
- Add troubleshooting entries for PENDING orders and .env not reloading
2026-05-19 16:05:37 +02:00
davide 982c268acc feat(dev): add stripe-cli service for local webhook forwarding
Adds a stripe-cli container under the 'dev' profile that forwards
Stripe webhook events directly to app:3000, bypassing Caddy. Start
with: docker compose --profile dev up -d
2026-05-19 16:05:13 +02:00
davide c966797073 test(product): add cart behavior tests for ProductDetailPage
Covers: Add to Cart, Add to Cart twice (quantity increment), Buy Now
standalone, and Add to Cart followed by Buy Now (no duplication).
2026-05-19 16:04:58 +02:00
davide 8bfd7afdcb fix(product): fix cart deduplication for products without variants
addToCart() compared item.variantId === selectedVariant where
selectedVariant is null but saved items store variantId: undefined.
null !== undefined caused findIndex to never match, always inserting
a duplicate instead of incrementing quantity. Normalised with || undefined.
2026-05-19 16:04:25 +02:00
davide 2526cf9543 fix(cart): use session-based auth instead of localStorage for checkout
Cart page checked localStorage.getItem('user') which is never set by
the cookie-based auth system. Replaced with useUser() context and
corrected redirect target from /cart to /checkout.
2026-05-19 16:04:12 +02:00
davide c7d2713c23 docs(test): document expected stderr/stdout output during test runs
Explains that the Stripe webhook stderr log, the unhandled event stdout,
and the Vite CJS deprecation warning are all normal and expected.
2026-05-19 14:18:26 +02:00
davide b9ebd250e7 chore: ignore app/public/uploads/ and remove spurious root package-lock.json
uploads/ is generated at runtime by Docker and must not be tracked.
package-lock.json in the repo root was created by accident.
2026-05-19 14:11:01 +02:00
davide db6b727902 test: add component tests (Button, ProductCard) and test suite README
20 component tests covering Button (variants, disabled state, event handlers) and
ProductCard (rendering, price formatting, sale badge, image fallback). README
documents the full suite: 151 tests across 10 files, how to run, mock patterns,
and what's missing by priority (checkout flow, admin routes, more components).
2026-05-19 14:08:07 +02:00
davide 6a5d5a6119 test: add integration tests for API routes (auth, Stripe webhook)
27 tests covering POST /api/auth/login (9), POST /api/auth/register (9), and
POST /api/webhooks/stripe (11). Routes are tested by importing handlers directly
as functions, no HTTP server needed. Stripe false-positive fixed: thrown error
message now differs from the hardcoded 400 response to verify sanitization.
2026-05-19 14:07:53 +02:00
davide 5428eeccc1 test: add unit tests for lib/ (validate, auth, storage, email, rate-limit)
49 tests for all 10 Zod schemas in validate.ts, 26 tests for auth (hashPassword,
verifyPassword, createSession, getSession, getCurrentUser, deleteSession), 11 for
storage (magic-byte validation, saveImage, deleteImageFile), 9 for email (sendMail
scenarios), and 6 for rate limiting logic.
2026-05-19 14:07:38 +02:00
davide b93f5d5bdf test: add Vitest infrastructure (config, setup, mocks, fixtures)
Adds test harness for the suite:
- vitest.config.ts: happy-dom env, @/* alias, v8 coverage with 70% thresholds
- setup.ts: env vars, global next/headers and next/navigation mocks
- tsconfig.json: IDE alias resolution for test/
- __mocks__/prisma.ts: centralised Prisma mock auto-registered via vi.mock
- fixtures/users.ts, fixtures/orders.ts: typed test data
2026-05-19 14:07:22 +02:00
davide ed7faa3be5 build: add Vitest test dependencies and fix Docker build type error
Added devDependencies: vitest, @vitest/coverage-v8, happy-dom, @testing-library/react,
jest-dom, user-event, and test scripts (test, test:watch, test:coverage).
Removed @types/testing-library__jest-dom (redundant with jest-dom v6+, caused
Docker build to fail with "Cannot find type definition file" error).
2026-05-19 14:07:09 +02:00
davide 93cfe1ad5e docs: update CLAUDE.md with Italian rule, error workflow, and full data model
Added Italian communication requirement, error-first workflow (report then wait),
and missing Prisma models: ProductVariant, PasswordResetToken, Page/PageSection,
SiteSettings, AuditLog. Added app/coverage/ to .gitignore.
2026-05-19 14:05:34 +02:00
davide ea5fca6561 fix: replace hardcoded site name with dynamic settings
- Add public /api/settings endpoint (force-dynamic, no auth) exposing
  site_name, site_description, footer_copyright, footer_links
- Navbar, login, register pages fetch site_name via useEffect
- Homepage hero and footer read site_name and site_description from DB
- Fix admin settings form silently ignoring API errors on save
2026-05-19 11:30:15 +02:00
davide 9797519e5c fix: use named Docker volume for uploads to fix permission errors
Bind-mounting ./data/uploads caused EACCES errors because Docker creates
the host directory as root, while the container runs as nextjs (UID 1001).
A named volume is initialized from the image where chown is already set correctly.
2026-05-19 10:54:45 +02:00
33 changed files with 4899 additions and 52 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"enabledPlugins": {
"stripe@claude-plugins-official": true,
"superpowers@claude-plugins-official": true,
"security-guidance@claude-plugins-official": true,
"ui-ux-pro-max@ui-ux-pro-max-skill": true,
"claude-md-management@claude-plugins-official": true,
"figma@claude-plugins-official": true,
"frontend-design@claude-plugins-official":true
}
}
+9 -2
View File
@@ -6,11 +6,15 @@
# Node # Node
app/node_modules/ app/node_modules/
node_modules/ node_modules/
test/node_modules
# Next.js build output # Next.js build output
app/.next/ app/.next/
app/out/ app/out/
# Test coverage report
app/coverage/
# Prisma generated client (rebuilt on npm install) # Prisma generated client (rebuilt on npm install)
app/node_modules/.prisma/ app/node_modules/.prisma/
@@ -24,8 +28,11 @@ Thumbs.db
*.swp *.swp
*.swo *.swo
# Dati locali (bind mount Docker) # Dati locali (bind mount Docker) — ignora contenuto, traccia solo struttura
data/ data/db/
data/caddy/
data/uploads/*
!data/uploads/.gitkeep
# Backup # Backup
backups/ backups/
+135
View File
@@ -0,0 +1,135 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## How to work with the user
Before implementing any new feature, **always discuss it first**: explain whether it makes sense professionally, how it is typically done in production e-commerce platforms, and propose alternatives if there is a better approach. Only proceed with implementation after the user confirms.
**Communicate in Italian.** The user speaks Italian — all responses, explanations, and questions must be in Italian.
**Error handling workflow:** When you find an error (in logs, code, or output), report what you found and stop. Do not propose or implement a fix until the user explicitly asks. Present: what the error is, where it occurs, and what likely caused it — then wait for instructions.
## Running the project
```bash
# Start everything (first run takes a few minutes to build)
docker compose up -d --build
# Check logs
docker compose logs -f app
# Stop
docker compose down
```
The app is available at http://localhost. Admin panel at http://localhost/admin.
Default credentials are in `.env` (`INITIAL_ADMIN_EMAIL` / `INITIAL_ADMIN_PASSWORD`).
Test emails are visible at http://localhost:8025 (Mailpit).
## Development commands (run inside `app/`)
```bash
npm run dev # local dev server (port 3000, no Docker)
npm run build # production build
npx prisma studio # visual DB browser
npx prisma migrate dev --name <name> # create a new migration
npx prisma migrate deploy # apply migrations (done automatically on container start)
```
## Architecture
**Stack:** Next.js 14 App Router · PostgreSQL 16 · Prisma 5 · Stripe · Nodemailer · TailwindCSS · Zod · Docker + Caddy
**Source root:** `app/src/`
| Directory | Purpose |
|---|---|
| `app/api/` | REST API routes — one folder per resource |
| `app/admin/` | Admin dashboard pages (role-gated at layout level) |
| `app/(storefront)/` | Public-facing pages |
| `components/` | Shared React components and UI primitives |
| `lib/` | Core utilities (auth, email, storage, Stripe, validation, rate limiting) |
| `context/` | Client-side UserContext |
## Key patterns
**API routes** follow a consistent shape: validate input with Zod → check auth/role via `getCurrentUser()` → query Prisma → return JSON. Copy an existing route as a starting point.
**Auth** is session-based (no NextAuth). `lib/auth.ts` handles token creation, hashing (SHA256), and the `getCurrentUser()` helper used in every protected route. Sessions expire after 30 days.
**Admin protection** is enforced in the admin layout: `CUSTOMER` role is blocked, `ADMIN` and `OWNER` are allowed. A `mustChangePassword` flag redirects new owners to a password-change page before anything else.
**Validation schemas** live in `lib/validate.ts` (Zod). Add new schemas there; never validate inline in routes.
**Image uploads** go through `lib/storage.ts`, which validates magic bytes (JPEG/PNG/WebP/ICO) before writing to `/app/public/uploads/<productId>/`. Uploads are stored in a named Docker volume (`uploads`) shared between the `app` and `caddy` containers.
**Emails** are sent via `lib/email.ts` (Nodemailer). Locally they land in Mailpit; in production, configure SMTP env vars.
**Rate limiting** is IP-based and backed by the `LoginAttempt` DB table (10 attempts / 15 min). Logic is in `lib/rate-limit.ts`.
## Data model (high level)
- **User** → has role (`CUSTOMER` / `ADMIN` / `OWNER`), sessions, orders, reviews
- **Product** → belongs to one **ProductType** (defines the attribute schema), many-to-many with **Category**, has **MediaAsset**, **ProductVariant**, **Review**
- **ProductType** → defines a JSON schema for product attributes (e.g. "clothing" has size/color)
- **ProductVariant** → SKU, price, stock per variante (es. taglia/colore di un prodotto)
- **Category** → hierarchical (self-referential `parentId`), many-to-many with Product
- **Order** → status state machine (`PENDING → PAID → FULFILLED`, `CANCELLED`, `REFUNDED`), has **OrderItem** and **Payment**
- **PasswordResetToken** → token hashed con scadenza per il flusso reset password
- **Page** / **PageSection** → CMS minimale per pagine statiche (slug, titolo, sezioni JSON ordinate)
- **SiteSettings** — key/value store for shop configuration (branding, etc.)
- **AuditLog** — tracks admin actions
## Environment variables
Copy `.env.example` to `.env`. For production, generate a strong `AUTH_SECRET` with `openssl rand -hex 32` and replace all placeholder values. The `DATABASE_URL` uses the Docker service name `db` as host — do not change it for containerised deployments.
## Debugging
**Check app logs (first thing to do):**
```bash
docker compose logs -f app # live
docker compose logs app --tail=100 # last 100 lines
```
**Common error patterns to look for in logs:**
- `EACCES: permission denied` → volume/filesystem permissions issue
- `PrismaClientKnownRequestError` → DB constraint violation or bad query
- `401 / 403` in API → session expired or role check failing
- Silent form failures → always check `res.ok` in `fetch` calls; UI may show success even on API error
**API errors not surfacing in the UI** are almost always caused by a missing `res.ok` check in the frontend `fetch` call. The pattern to use in every form submit:
```ts
const res = await fetch('/api/...', { method: 'POST', ... })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error || `Errore (${res.status})`)
return
}
```
**Database inspection:**
```bash
# Open Prisma Studio (visual DB browser)
cd app && npx prisma studio
# Or connect directly
docker compose exec db psql -U ecommerce ecommerce
```
**Rebuild after code changes:**
```bash
docker compose up -d --build app # rebuild only the app container
```
**TypeScript errors in IDE but not in build:** likely a missing `node_modules` or stale tsconfig in the IDE. Run `npm install` inside `app/` and restart the IDE TypeScript server.
## Deployment
1. Point your domain DNS to the server.
2. Set `APP_URL` to `https://yourdomain.com` in `.env`.
3. Edit `Caddyfile`: replace `localhost` with your domain.
4. `docker compose up -d --build`
Caddy handles TLS automatically via Let's Encrypt. Ports 80 and 443 must be open on the firewall.
+76 -31
View File
@@ -12,6 +12,7 @@ Piattaforma e-commerce containerizzata, avviabile con un singolo comando.
- [Docker Desktop](https://docs.docker.com/get-docker/) installato e avviato - [Docker Desktop](https://docs.docker.com/get-docker/) installato e avviato
- Porta **80** libera (nessun altro web server in esecuzione) - Porta **80** libera (nessun altro web server in esecuzione)
- Account [Stripe](https://stripe.com) gratuito (necessario per i pagamenti)
### 1. Clona il repository ### 1. Clona il repository
@@ -26,14 +27,28 @@ cd ecommerce-platform
cp .env.example .env cp .env.example .env
``` ```
Il file `.env` di default è già configurato per localhost. **Non serve modificare nulla** per i primi test. Apri `.env` e inserisci la tua chiave Stripe test (gratuita, dalla [Stripe Dashboard → API keys](https://dashboard.stripe.com/test/apikeys)):
```env
STRIPE_SECRET_KEY=sk_test_la_tua_chiave
```
Il resto dei valori è già preconfigurato per localhost e non va modificato.
### 3. Avvia la piattaforma ### 3. Avvia la piattaforma
**Senza pagamenti** (admin, catalogo, email):
```bash ```bash
docker compose up -d docker compose up -d
``` ```
**Con pagamenti e webhook Stripe attivi** (consigliato):
```bash
docker compose --profile dev up -d
```
Il primo avvio richiede **510 minuti**: Docker scarica le immagini, installa le dipendenze npm, compila Next.js, esegue le migrazioni e crea l'utente admin. Il primo avvio richiede **510 minuti**: Docker scarica le immagini, installa le dipendenze npm, compila Next.js, esegue le migrazioni e crea l'utente admin.
Segui il progresso con: Segui il progresso con:
@@ -76,33 +91,57 @@ Al primo accesso il sistema ti obbliga a cambiare la password.
3. **Products** → crea un prodotto, assegna tipo e categoria, impostalo su **Published** 3. **Products** → crea un prodotto, assegna tipo e categoria, impostalo su **Published**
4. Apri http://localhost → il prodotto appare in homepage 4. Apri http://localhost → il prodotto appare in homepage
### 7. Cosa funziona in locale senza configurazione extra ### 7. Setup webhook Stripe (una tantum per macchina)
| Funzionalità | Stato | Il profilo `dev` include un container `stripe-cli` che riceve i webhook da Stripe e li inoltra all'app. Senza di esso, dopo il pagamento l'ordine resta in `PENDING` e nessuna email viene inviata.
|---|---|
| Admin dashboard completa | ✅ |
| Gestione prodotti, categorie, ordini | ✅ |
| Registrazione e login clienti | ✅ |
| Email (reset password, ecc.) | ✅ visibili su http://localhost:8025 |
| Pagamenti Stripe | ⚠️ richiede chiavi reali (vedi sotto) |
**Per testare i pagamenti Stripe** in locale, inserisci una chiave `sk_test_...` reale nel `.env` (gratuita, modalità test su [dashboard.stripe.com](https://dashboard.stripe.com/test/apikeys)): **Al primo avvio con `--profile dev`, recupera il webhook secret dai log:**
```bash
docker compose logs stripe-cli | grep "webhook signing secret"
```
Copia il valore `whsec_...` nel `.env`:
```env ```env
STRIPE_SECRET_KEY=sk_test_la_tua_chiave STRIPE_WEBHOOK_SECRET=whsec_abc123...
``` ```
Poi riavvia l'app: Poi ricrea il container app per applicare la variabile (`restart` non ricarica il `.env`):
```bash ```bash
docker compose restart app docker compose up -d --force-recreate app
``` ```
### 8. Ferma la piattaforma Da questo momento `docker compose --profile dev up -d` avvia tutto inclusi i webhook — non serve altro.
### 8. Testa i pagamenti
**Carte di test Stripe:**
| Carta | Risultato |
|-------|-----------|
| `4242 4242 4242 4242` | Pagamento riuscito |
| `4000 0000 0000 0002` | Carta rifiutata |
| `4000 0025 0000 3155` | Richiede autenticazione 3D Secure |
Scadenza: qualsiasi data futura · CVC: qualsiasi 3 cifre
**Verifica che tutto funzioni dopo un pagamento:**
```bash ```bash
docker compose down # ferma i container, i dati restano docker compose logs stripe-cli --tail=20
docker compose down -v # ferma e cancella anche il database # deve mostrare [200] per checkout.session.completed
```
1. L'ordine nel pannello admin passa da `PENDING` a `PAID`
2. L'email di conferma appare su http://localhost:8025
### 9. Ferma la piattaforma
```bash
docker compose --profile dev down # ferma tutto (con stripe-cli), i dati restano
docker compose down -v # ferma e cancella anche il database
``` ```
--- ---
@@ -133,13 +172,13 @@ Cinque variabili da aggiornare nel `.env`:
|-----------|-----------|------------| |-----------|-----------|------------|
| `APP_URL` | `http://localhost` | `https://tuodominio.com` | | `APP_URL` | `http://localhost` | `https://tuodominio.com` |
| `AUTH_SECRET` | qualsiasi stringa | `openssl rand -hex 32` | | `AUTH_SECRET` | qualsiasi stringa | `openssl rand -hex 32` |
| `STRIPE_SECRET_KEY` | `sk_test_...` (gratuita) | `sk_live_...` | | `STRIPE_SECRET_KEY` | `sk_test_...` | `sk_live_...` |
| `STRIPE_WEBHOOK_SECRET` | opzionale | obbligatorio | | `STRIPE_WEBHOOK_SECRET` | dal container stripe-cli | dal dashboard Stripe |
| `SMTP_*` | Mailpit locale (porta 8025) | provider reale (Resend, Mailgun, SendGrid…) | | `SMTP_*` | Mailpit locale (porta 8025) | provider reale (Resend, Mailgun, SendGrid…) |
### 3 — Server ### 3 — Server
Serve un VPS Linux con Docker installato (DigitalOcean, Hetzner, OVH, ecc.) e il record DNS del dominio puntato all'IP del server. Il comando di avvio è identico: `docker compose up -d`. Serve un VPS Linux con Docker installato (DigitalOcean, Hetzner, OVH, ecc.) e il record DNS del dominio puntato all'IP del server. Il comando di avvio è identico: `docker compose up -d` (senza `--profile dev`).
### 4 — Backup ### 4 — Backup
@@ -221,8 +260,6 @@ tuodominio.com {
} }
``` ```
Caddy ottiene e rinnova automaticamente il certificato HTTPS tramite Let's Encrypt. Non serve nessuna configurazione SSL manuale.
### 5. Avvia ### 5. Avvia
```bash ```bash
@@ -251,10 +288,10 @@ Eventi da ascoltare:
- payment_intent.payment_failed - payment_intent.payment_failed
``` ```
Copia il **Signing secret** (`whsec_...`) nel `.env` come `STRIPE_WEBHOOK_SECRET`, poi: Copia il **Signing secret** (`whsec_...`) nel `.env` come `STRIPE_WEBHOOK_SECRET`, poi ricrea il container per applicarlo:
```bash ```bash
docker compose restart app docker compose up -d --force-recreate app
``` ```
### 7. Primo accesso e configurazione negozio ### 7. Primo accesso e configurazione negozio
@@ -290,8 +327,6 @@ docker compose restart app
| **5432** | PostgreSQL (db) | Accessibile solo dall'app tramite `DATABASE_URL` | | **5432** | PostgreSQL (db) | Accessibile solo dall'app tramite `DATABASE_URL` |
| **1025** | Mailpit SMTP | Accessibile solo dall'app per l'invio email | | **1025** | Mailpit SMTP | Accessibile solo dall'app per l'invio email |
Queste porte non sono pubblicate nel `docker-compose.yml` (`expose``ports`) e non raggiungibili dall'esterno del server.
### Porta solo per sviluppo locale (non aprire in produzione) ### Porta solo per sviluppo locale (non aprire in produzione)
| Porta | Servizio | Note | | Porta | Servizio | Note |
@@ -301,13 +336,9 @@ Queste porte non sono pubblicate nel `docker-compose.yml` (`expose` ≠ `ports`)
### Riepilogo comandi firewall (UFW — Ubuntu/Debian) ### Riepilogo comandi firewall (UFW — Ubuntu/Debian)
```bash ```bash
# Abilita solo HTTP e HTTPS
sudo ufw allow 80/tcp sudo ufw allow 80/tcp
sudo ufw allow 443/tcp sudo ufw allow 443/tcp
# Blocca esplicitamente Mailpit dall'esterno (già bloccata di default se non aperta)
sudo ufw deny 8025/tcp sudo ufw deny 8025/tcp
sudo ufw enable sudo ufw enable
sudo ufw status sudo ufw status
``` ```
@@ -362,6 +393,20 @@ docker compose logs -f app
**Errore "port 80 already in use"** **Errore "port 80 already in use"**
Un altro servizio usa la porta 80 (Apache, Nginx, ecc.). Fermalo o cambia la porta nel `docker-compose.yml`. Un altro servizio usa la porta 80 (Apache, Nginx, ecc.). Fermalo o cambia la porta nel `docker-compose.yml`.
**L'ordine resta in PENDING dopo il pagamento**
Il container `stripe-cli` non è in esecuzione o `STRIPE_WEBHOOK_SECRET` non è configurato. Verifica:
```bash
docker compose --profile dev ps # stripe-cli deve essere "running"
docker compose logs stripe-cli --tail=10
```
Se il `whsec_...` manca nel `.env`, segui lo step 7 del setup locale.
**Le variabili del `.env` non vengono applicate dopo la modifica**
`docker compose restart` non ricarica il `.env`. Usa sempre:
```bash
docker compose up -d --force-recreate app
```
**Dimentico la password admin** **Dimentico la password admin**
Resetta direttamente nel database: Resetta direttamente nel database:
```bash ```bash
@@ -381,7 +426,7 @@ docker compose exec db psql -U ecommerce ecommerce -c \
``` ```
ecommerce-platform/ ecommerce-platform/
├── docker-compose.yml Orchestrazione: db, app, caddy, mailpit ├── docker-compose.yml Orchestrazione: db, app, caddy, mailpit, stripe-cli (profilo dev)
├── Caddyfile Reverse proxy — modifica qui il dominio ├── Caddyfile Reverse proxy — modifica qui il dominio
├── .env Variabili d'ambiente (non committare) ├── .env Variabili d'ambiente (non committare)
├── .env.example Template da copiare ├── .env.example Template da copiare
@@ -413,7 +458,7 @@ ecommerce-platform/
| `INITIAL_ADMIN_EMAIL` | Email primo admin | qualsiasi | la tua email | | `INITIAL_ADMIN_EMAIL` | Email primo admin | qualsiasi | la tua email |
| `INITIAL_ADMIN_PASSWORD` | Password primo admin | qualsiasi | sicura | | `INITIAL_ADMIN_PASSWORD` | Password primo admin | qualsiasi | sicura |
| `STRIPE_SECRET_KEY` | Chiave Stripe | `sk_test_...` | `sk_live_...` | | `STRIPE_SECRET_KEY` | Chiave Stripe | `sk_test_...` | `sk_live_...` |
| `STRIPE_WEBHOOK_SECRET` | Segreto webhook Stripe | opzionale | obbligatorio | | `STRIPE_WEBHOOK_SECRET` | Segreto webhook Stripe | dal container stripe-cli | dal dashboard Stripe |
| `SMTP_HOST` | Server SMTP | `mailpit` | provider reale | | `SMTP_HOST` | Server SMTP | `mailpit` | provider reale |
| `SMTP_PORT` | Porta SMTP | `1025` | `587` | | `SMTP_PORT` | Porta SMTP | `1025` | `587` |
| `SMTP_USER` | Utente SMTP | vuoto | obbligatorio | | `SMTP_USER` | Utente SMTP | vuoto | obbligatorio |
+2453 -1
View File
File diff suppressed because it is too large Load Diff
+11 -2
View File
@@ -6,7 +6,10 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"postinstall": "prisma generate" "postinstall": "prisma generate",
"test": "vitest run --config ../test/vitest.config.ts",
"test:watch": "vitest --config ../test/vitest.config.ts",
"test:coverage": "vitest run --config ../test/vitest.config.ts --coverage"
}, },
"dependencies": { "dependencies": {
"next": "14.2.5", "next": "14.2.5",
@@ -26,6 +29,12 @@
"typescript": "^5", "typescript": "^5",
"tailwindcss": "^3.4.1", "tailwindcss": "^3.4.1",
"postcss": "^8", "postcss": "^8",
"autoprefixer": "^10.0.1" "autoprefixer": "^10.0.1",
"vitest": "^1.6.0",
"@vitest/coverage-v8": "^1.6.0",
"happy-dom": "^14.12.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.4.0",
"@testing-library/user-event": "^14.5.2"
} }
} }
+8 -1
View File
@@ -52,12 +52,19 @@ export default function AdminSettingsPage() {
e.preventDefault() e.preventDefault()
setSaving(true) setSaving(true)
setError('') setError('')
setMessage('')
for (const key of ALL_KEYS) { for (const key of ALL_KEYS) {
await fetch('/api/admin/settings', { const res = await fetch('/api/admin/settings', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key, value: values[key] }), body: JSON.stringify({ key, value: values[key] }),
}) })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setSaving(false)
setError(data.error || `Errore nel salvare "${key}" (${res.status})`)
return
}
} }
setSaving(false) setSaving(false)
setMessage('Impostazioni salvate!') setMessage('Impostazioni salvate!')
+14
View File
@@ -0,0 +1,14 @@
import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
export const dynamic = 'force-dynamic'
const PUBLIC_KEYS = ['site_name', 'site_description', 'footer_copyright', 'footer_links'] as const
export async function GET() {
const rows = await prisma.siteSettings.findMany({
where: { key: { in: [...PUBLIC_KEYS] } },
})
const settings = Object.fromEntries(rows.map((r) => [r.key, r.value]))
return NextResponse.json({ settings })
}
+4 -3
View File
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation'
import Link from 'next/link' import Link from 'next/link'
import { Navbar } from '@/components/storefront/Navbar' import { Navbar } from '@/components/storefront/Navbar'
import { Button } from '@/components/ui/Button' import { Button } from '@/components/ui/Button'
import { useUser } from '@/context/UserContext'
interface CartItem { interface CartItem {
productId: string productId: string
@@ -18,6 +19,7 @@ interface CartItem {
export default function CartPage() { export default function CartPage() {
const [cart, setCart] = useState<CartItem[]>([]) const [cart, setCart] = useState<CartItem[]>([])
const router = useRouter() const router = useRouter()
const { user } = useUser()
useEffect(() => { useEffect(() => {
const stored = JSON.parse(localStorage.getItem('cart') || '[]') const stored = JSON.parse(localStorage.getItem('cart') || '[]')
@@ -51,10 +53,9 @@ export default function CartPage() {
const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0) const subtotal = cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
async function handleCheckout() { function handleCheckout() {
const user = localStorage.getItem('user')
if (!user) { if (!user) {
router.push('/login?redirect=/cart') router.push('/login?redirect=/checkout')
return return
} }
router.push('/checkout') router.push('/checkout')
+10 -2
View File
@@ -1,6 +1,6 @@
'use client' 'use client'
import { Suspense, useState } from 'react' import { Suspense, useState, useEffect } from 'react'
import Link from 'next/link' import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation' import { useRouter, useSearchParams } from 'next/navigation'
import { Input } from '@/components/ui/Input' import { Input } from '@/components/ui/Input'
@@ -21,11 +21,19 @@ function LoginForm() {
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [siteName, setSiteName] = useState('ShopX')
const router = useRouter() const router = useRouter()
const searchParams = useSearchParams() const searchParams = useSearchParams()
const redirect = searchParams.get('redirect') || '/' const redirect = searchParams.get('redirect') || '/'
const { refreshUser } = useUser() const { refreshUser } = useUser()
useEffect(() => {
fetch('/api/settings')
.then((r) => r.json())
.then((data) => { if (data.settings?.site_name) setSiteName(data.settings.site_name as string) })
.catch(() => {})
}, [])
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
setError('') setError('')
@@ -66,7 +74,7 @@ function LoginForm() {
<div className="w-full max-w-md"> <div className="w-full max-w-md">
<div className="bg-white rounded-lg border border-gray-200 shadow-sm p-8"> <div className="bg-white rounded-lg border border-gray-200 shadow-sm p-8">
<div className="text-center mb-8"> <div className="text-center mb-8">
<Link href="/" className="text-2xl font-bold text-gray-900">ShopX</Link> <Link href="/" className="text-2xl font-bold text-gray-900">{siteName}</Link>
<h1 className="text-xl font-semibold mt-4">Welcome back</h1> <h1 className="text-xl font-semibold mt-4">Welcome back</h1>
<p className="text-gray-600 text-sm mt-1">Sign in to your account</p> <p className="text-gray-600 text-sm mt-1">Sign in to your account</p>
</div> </div>
+13 -4
View File
@@ -14,8 +14,17 @@ async function getFeaturedProducts() {
}) })
} }
async function getSiteSettings() {
const rows = await prisma.siteSettings.findMany({
where: { key: { in: ['site_name', 'site_description'] } },
})
return Object.fromEntries(rows.map((r) => [r.key, r.value as string]))
}
export default async function HomePage() { export default async function HomePage() {
const products = await getFeaturedProducts() const [products, settings] = await Promise.all([getFeaturedProducts(), getSiteSettings()])
const siteName = settings.site_name || 'ShopX'
const siteDescription = settings.site_description || 'Discover our curated collection of products'
return ( return (
<div> <div>
@@ -24,9 +33,9 @@ export default async function HomePage() {
{/* Hero */} {/* Hero */}
<section className="bg-blue-600 text-white py-20"> <section className="bg-blue-600 text-white py-20">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
<h1 className="text-4xl font-bold mb-4">Welcome to ShopX</h1> <h1 className="text-4xl font-bold mb-4">Welcome to {siteName}</h1>
<p className="text-xl text-blue-100 mb-8"> <p className="text-xl text-blue-100 mb-8">
Discover our curated collection of products {siteDescription}
</p> </p>
<Link <Link
href="/products" href="/products"
@@ -90,7 +99,7 @@ export default async function HomePage() {
<footer className="bg-gray-800 text-gray-300 py-8"> <footer className="bg-gray-800 text-gray-300 py-8">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-sm"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-sm">
<p>&copy; {new Date().getFullYear()} ShopX. All rights reserved.</p> <p>&copy; {new Date().getFullYear()} {siteName}. All rights reserved.</p>
</div> </div>
</footer> </footer>
</div> </div>
+7 -2
View File
@@ -54,7 +54,7 @@ export default function ProductDetailPage() {
const cart = JSON.parse(localStorage.getItem('cart') || '[]') const cart = JSON.parse(localStorage.getItem('cart') || '[]')
const existingIndex = cart.findIndex( const existingIndex = cart.findIndex(
(item: { productId: string; variantId?: string }) => (item: { productId: string; variantId?: string }) =>
item.productId === product.id && item.variantId === selectedVariant item.productId === product.id && item.variantId === (selectedVariant || undefined)
) )
if (existingIndex >= 0) { if (existingIndex >= 0) {
@@ -249,7 +249,12 @@ export default function ProductDetailPage() {
size="lg" size="lg"
variant="secondary" variant="secondary"
onClick={() => { onClick={() => {
addToCart() const cart = JSON.parse(localStorage.getItem('cart') || '[]')
const alreadyInCart = cart.some(
(item: { productId: string; variantId?: string }) =>
item.productId === product.id && item.variantId === (selectedVariant || undefined)
)
if (!alreadyInCart) addToCart()
router.push('/cart') router.push('/cart')
}} }}
> >
+11 -3
View File
@@ -1,6 +1,6 @@
'use client' 'use client'
import { useState } from 'react' import { useState, useEffect } from 'react'
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { Input } from '@/components/ui/Input' import { Input } from '@/components/ui/Input'
@@ -14,9 +14,17 @@ export default function RegisterPage() {
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [siteName, setSiteName] = useState('ShopX')
const router = useRouter() const router = useRouter()
const { refreshUser } = useUser() const { refreshUser } = useUser()
useEffect(() => {
fetch('/api/settings')
.then((r) => r.json())
.then((data) => { if (data.settings?.site_name) setSiteName(data.settings.site_name as string) })
.catch(() => {})
}, [])
async function handleSubmit(e: React.FormEvent) { async function handleSubmit(e: React.FormEvent) {
e.preventDefault() e.preventDefault()
setError('') setError('')
@@ -50,9 +58,9 @@ export default function RegisterPage() {
<div className="w-full max-w-md"> <div className="w-full max-w-md">
<div className="bg-white rounded-lg border border-gray-200 shadow-sm p-8"> <div className="bg-white rounded-lg border border-gray-200 shadow-sm p-8">
<div className="text-center mb-8"> <div className="text-center mb-8">
<Link href="/" className="text-2xl font-bold text-gray-900">ShopX</Link> <Link href="/" className="text-2xl font-bold text-gray-900">{siteName}</Link>
<h1 className="text-xl font-semibold mt-4">Create Account</h1> <h1 className="text-xl font-semibold mt-4">Create Account</h1>
<p className="text-gray-600 text-sm mt-1">Join ShopX today</p> <p className="text-gray-600 text-sm mt-1">Join {siteName} today</p>
</div> </div>
{error && <Alert variant="error" className="mb-4">{error}</Alert>} {error && <Alert variant="error" className="mb-4">{error}</Alert>}
+12 -1
View File
@@ -7,6 +7,7 @@ import { useUser } from '@/context/UserContext'
export function Navbar() { export function Navbar() {
const [cartCount, setCartCount] = useState(0) const [cartCount, setCartCount] = useState(0)
const [siteName, setSiteName] = useState('ShopX')
const { user, refreshUser } = useUser() const { user, refreshUser } = useUser()
const router = useRouter() const router = useRouter()
@@ -16,6 +17,16 @@ export function Navbar() {
setCartCount(count) setCartCount(count)
}, []) }, [])
useEffect(() => {
fetch('/api/settings')
.then((r) => r.json())
.then((data) => {
const name = data.settings?.site_name
if (name) setSiteName(name as string)
})
.catch(() => {})
}, [])
async function handleLogout() { async function handleLogout() {
await fetch('/api/auth/logout', { method: 'POST' }) await fetch('/api/auth/logout', { method: 'POST' })
await refreshUser() await refreshUser()
@@ -28,7 +39,7 @@ export function Navbar() {
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16"> <div className="flex items-center justify-between h-16">
<Link href="/" className="text-xl font-bold text-gray-900"> <Link href="/" className="text-xl font-bold text-gray-900">
ShopX {siteName}
</Link> </Link>
<nav className="flex items-center gap-6 text-sm"> <nav className="flex items-center gap-6 text-sm">
+10
View File
@@ -49,3 +49,13 @@ services:
- ./data/uploads:/srv/uploads - ./data/uploads:/srv/uploads
depends_on: depends_on:
- app - app
stripe-cli:
image: stripe/stripe-cli:latest
command: listen --forward-to http://app:3000/api/webhooks/stripe --api-key ${STRIPE_SECRET_KEY}
depends_on:
- app
restart: unless-stopped
profiles:
- dev
+397
View File
@@ -0,0 +1,397 @@
# Suite di Test
Tutti i test automatizzati del progetto stanno qui, separati da `app/` per una scelta precisa: il codice di produzione rimane pulito, la configurazione Vitest è indipendente dal build di Next.js, e i test girano senza avviare Docker o il database.
## Installazione e comandi
I comandi vanno lanciati dalla cartella `app/`:
```bash
cd ~/ecommerce-platform/app
npm install # installa le dipendenze (incluse quelle di test)
npm run test # esegui tutti i test una volta (modalità CI)
npm run test:watch # riesegui automaticamente al salvataggio (sviluppo)
npm run test:coverage # genera il report HTML in app/coverage/index.html
```
## Stato attuale: 151 test, 10 file
| File | Area | Test |
|------|------|-----:|
| `unit/lib/validate.test.ts` | 10 schemi Zod (login, register, prodotti, ecc.) | 49 |
| `unit/lib/auth.test.ts` | hashToken, hashPassword, sessioni, getCurrentUser | 26 |
| `unit/lib/storage.test.ts` | magic bytes JPEG/PNG/WebP/ICO, saveImage, deleteImageFile | 11 |
| `unit/lib/email.test.ts` | sendEmail, sendOrderConfirmationEmail, sendPasswordResetEmail | 9 |
| `unit/lib/rate-limit.test.ts` | checkRateLimit (finestra 15 min), recordAttempt | 7 |
| `integration/api/auth/login.test.ts` | POST /api/auth/login — rate limit, validazione, credenziali | 9 |
| `integration/api/auth/register.test.ts` | POST /api/auth/register — duplicati, password, sessione | 9 |
| `integration/api/webhooks/stripe.test.ts` | checkout.session.completed, payment_intent, firma mancante | 11 |
| `components/ui/Button.test.tsx` | loading, disabled, varianti, onClick | 10 |
| `components/storefront/ProductCard.test.tsx` | prezzo, slug, immagine, placeholder "No image" | 10 |
## Struttura
```
test/
├── vitest.config.ts # ambiente happy-dom, alias @/, soglie copertura 70%
├── setup.ts # env vars mock, mock globale next/headers e next/navigation
├── tsconfig.json # alias @/ per il type-checker dell'IDE
├── unit/lib/ # funzioni pure di app/src/lib/ (nessun DB reale)
├── integration/api/ # API route Next.js 14 App Router (Prisma mockato)
│ ├── auth/
│ └── webhooks/
├── components/ # componenti React con @testing-library/react
│ ├── ui/
│ └── storefront/
├── __mocks__/
│ └── prisma.ts # mock centralizzato del Prisma client (tutti i vi.fn())
└── fixtures/
├── users.ts # mockUser, mockAdmin, mockSession
└── orders.ts # mockOrder, mockPayment, eventi Stripe
```
## Come funziona il mock di Prisma
Il file `test/__mocks__/prisma.ts` esporta un oggetto con `vi.fn()` per ogni metodo Prisma usato nel progetto. Nei test di integrazione basta importarlo all'inizio del file — il `vi.mock('@/lib/prisma')` è già incluso dentro.
```typescript
import '../../../__mocks__/prisma' // monta il mock E chiama vi.mock internamente
import { prisma } from '@/lib/prisma'
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
})
```
> **Nota sui percorsi**: i test di integrazione si trovano 3 livelli sotto `test/`
> (`integration/api/auth/`), quindi il percorso relativo verso `__mocks__/` è `../../../__mocks__/prisma`.
> I test unitari in `unit/lib/` usano invece `../../__mocks__/prisma`.
## Come testare una API route
Le route App Router sono funzioni TypeScript che accettano `NextRequest``NextResponse`. Si importano e si chiamano direttamente, senza un server HTTP.
```typescript
import { NextRequest } from 'next/server'
import { POST } from '@/app/api/auth/login/route'
it('restituisce 401 per password errata', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
vi.mocked(verifyPassword).mockResolvedValue(false)
const req = new NextRequest(
new Request('http://localhost/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-forwarded-for': '1.2.3.4' },
body: JSON.stringify({ email: 'test@example.com', password: 'WrongPass1!' }),
})
)
const res = await POST(req)
expect(res.status).toBe(401)
expect((await res.json()).error).toBe('Invalid email or password')
})
```
Per route con parametri dinamici (es. `/api/admin/products/[id]`):
```typescript
import { GET } from '@/app/api/admin/products/[id]/route'
const res = await GET(req, { params: { id: 'prod-123' } })
```
## Aggiungere nuovi test
**Test unitario** (per una nuova funzione in `lib/`): copia la struttura di `unit/lib/email.test.ts`. Mocka le dipendenze esterne in cima con `vi.mock(...)`, poi testa solo la logica della funzione.
**Test di integrazione** (per una nuova API route):
1. Crea il file nella cartella corrispondente sotto `integration/api/`
2. Importa `'../../../__mocks__/prisma'` (o `'../../__mocks__/prisma'` a seconda della profondità)
3. Mocka lib esterne (`@/lib/auth`, `@/lib/stripe`, ecc.) con `vi.mock`
4. Prepara i mock nel `beforeEach` con `vi.clearAllMocks()` + valori di ritorno
**Test di componente**: copia `components/ui/Button.test.tsx`. Usa `render()` e `screen` di `@testing-library/react`. Testa comportamento visibile, non implementazione interna.
## Copertura
La soglia minima configurata in `vitest.config.ts` è **70% di linee e funzioni**. Il comando `npm run test:coverage` fallisce se non viene rispettata. La copertura attuale è circa **11% di linee e 33% di funzioni** — la soglia va abbassata temporaneamente o la suite va estesa.
### Output atteso durante l'esecuzione
Durante `npm test` o `npm run test:coverage` possono comparire righe che sembrano errori ma sono normali:
```
stderr | ...stripe.test.ts > returns 400 when signature verification fails
Webhook signature verification failed: stripe_signature_mismatch
```
La route `/api/webhooks/stripe` logga intenzionalmente il messaggio quando la firma è invalida. Il test verifica proprio questo scenario — il `stderr` è corretto.
```
stdout | ...stripe.test.ts > returns 200 for unhandled event types
Unhandled event type: customer.created
```
Anche questo è il log della route per eventi Stripe non gestiti. Comportamento atteso.
```
The CJS build of Vite's Node API is deprecated.
```
Warning di Vitest 1.x, innocuo. Sparirà aggiornando a Vitest 2+.
### Cosa manca (per priorità)
#### Alta priorità — logica di business critica
| File | Cosa testare |
|------|-------------|
| `lib/stripe.ts` | `createCheckoutSession`: parametri passati a Stripe, metadati orderId |
| `api/auth/logout/route.ts` | cancellazione cookie, chiamata a `deleteSession` |
| `api/auth/me/route.ts` | utente autenticato → 200, non autenticato → 401 |
| `api/auth/change-password/route.ts` | password errata → 401, nuova password debole → 400, successo → 200 |
| `api/checkout/route.ts` | utente non autenticato → 401, prodotto inesistente → 400, creazione ordine + sessione Stripe |
#### Media priorità — route admin (CRUD)
| File | Cosa testare |
|------|-------------|
| `api/admin/products/route.ts` | GET con paginazione/filtri, POST crea prodotto, accesso CUSTOMER → 403 |
| `api/admin/products/[id]/route.ts` | GET, PATCH, DELETE — prodotto inesistente → 404 |
| `api/admin/orders/route.ts` | lista ordini con filtri di stato |
| `api/admin/orders/[id]/route.ts` | aggiornamento stato ordine |
| `api/admin/categories/route.ts` | CRUD categorie, slug duplicato → 409 |
| `api/admin/settings/route.ts` | lettura e scrittura impostazioni sito |
| `api/admin/users/route.ts` | creazione admin, email duplicata → 409 |
#### Bassa priorità — componenti UI
| File | Cosa testare |
|------|-------------|
| `components/ui/Input.tsx` | rendering label, messaggio di errore, stato disabled |
| `components/ui/Alert.tsx` | varianti (success, error, warning, info) |
| `components/ui/Badge.tsx` | varianti colore, testo |
| `components/ui/Card.tsx` | rendering children |
### Come implementare i test mancanti
---
#### `unit/lib/stripe.test.ts`
Crea il file in `test/unit/lib/`. Mock dell'intero modulo `stripe` con `vi.hoisted` (necessario perché `stripe.ts` istanzia `new Stripe(...)` a module load time):
```typescript
const { mockCreate, mockConstructEvent } = vi.hoisted(() => ({
mockCreate: vi.fn().mockResolvedValue({ id: 'cs_test', url: 'https://stripe.com/pay/cs_test' }),
mockConstructEvent: vi.fn(),
}))
vi.mock('stripe', () => ({
default: vi.fn().mockImplementation(() => ({
checkout: { sessions: { create: mockCreate } },
webhooks: { constructEvent: mockConstructEvent },
})),
}))
import { createCheckoutSession, constructWebhookEvent } from '@/lib/stripe'
it('passa orderId nei metadata', async () => {
await createCheckoutSession({
orderId: 'order-1',
lineItems: [{ price_data: { currency: 'eur', unit_amount: 1000, product_data: { name: 'T-shirt' } }, quantity: 1 }],
customerEmail: 'user@example.com',
successUrl: 'http://localhost/success',
cancelUrl: 'http://localhost/cancel',
})
expect(mockCreate).toHaveBeenCalledWith(expect.objectContaining({
metadata: { orderId: 'order-1' },
}))
})
```
---
#### `integration/api/auth/logout.test.ts`
Crea in `test/integration/api/auth/`. La route `logout` legge il cookie, cancella la sessione e pulisce il cookie:
```typescript
import '../../../__mocks__/prisma'
import { NextRequest } from 'next/server'
import { POST } from '@/app/api/auth/logout/route'
import { cookies } from 'next/headers'
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return { ...actual, deleteSession: vi.fn(), clearSessionCookie: vi.fn() }
})
import { deleteSession, clearSessionCookie } from '@/lib/auth'
it('cancella la sessione e il cookie se il token esiste', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'mytoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
const res = await POST()
expect(res.status).toBe(200)
expect(deleteSession).toHaveBeenCalledWith('mytoken')
expect(clearSessionCookie).toHaveBeenCalled()
})
it('risponde 200 anche senza token (utente già sloggato)', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue(undefined), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
const res = await POST()
expect(res.status).toBe(200)
expect(deleteSession).not.toHaveBeenCalled()
})
```
---
#### `integration/api/auth/me.test.ts`
La route `me` chiama `getCurrentUser()` — mocka solo `@/lib/auth`:
```typescript
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return { ...actual, getCurrentUser: vi.fn() }
})
import { getCurrentUser } from '@/lib/auth'
it('restituisce i dati utente se autenticato', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(mockUser as any)
const res = await GET()
expect(res.status).toBe(200)
expect((await res.json()).user.email).toBe(mockUser.email)
expect((await res.json()).user).not.toHaveProperty('passwordHash')
})
it('restituisce 401 se non autenticato', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(null)
const res = await GET()
expect(res.status).toBe(401)
})
```
---
#### `integration/api/auth/change-password.test.ts`
La route richiede `getCurrentUser`, `verifyPassword`, `hashPassword` e `prisma.user.update`:
```typescript
import '../../../__mocks__/prisma'
import { prisma } from '@/lib/prisma'
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return { ...actual, getCurrentUser: vi.fn(), verifyPassword: vi.fn(), hashPassword: vi.fn().mockResolvedValue('newhash') }
})
import { getCurrentUser, verifyPassword } from '@/lib/auth'
// beforeEach: clearAllMocks, loginAttempt.count → 0, user.update → mockUser
it('restituisce 401 se non autenticato', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(null)
const res = await POST(makeRequest({ currentPassword: 'Old1!', newPassword: 'NewPass123!' }))
expect(res.status).toBe(401)
})
it('restituisce 400 se la password attuale è errata', async () => {
vi.mocked(getCurrentUser).mockResolvedValue({ ...mockUser, passwordHash: 'hash' } as any)
vi.mocked(verifyPassword).mockResolvedValue(false)
const res = await POST(makeRequest({ currentPassword: 'Wrong1!', newPassword: 'NewPass123!' }))
expect(res.status).toBe(400)
expect((await res.json()).error).toMatch(/incorrect/)
})
it('aggiorna la password e azzera mustChangePassword', async () => {
vi.mocked(getCurrentUser).mockResolvedValue({ ...mockUser, passwordHash: 'hash' } as any)
vi.mocked(verifyPassword).mockResolvedValue(true)
vi.mocked(prisma.user.update).mockResolvedValue(mockUser as any)
const res = await POST(makeRequest({ currentPassword: 'OldPass1!', newPassword: 'NewPass123!' }))
expect(res.status).toBe(200)
expect(prisma.user.update).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ mustChangePassword: false }),
}))
})
```
---
#### `integration/api/admin/products.test.ts`
Le route admin verificano il ruolo prima di tutto. Pattern chiave da testare: accesso negato, paginazione, creazione con audit log:
```typescript
import '../../../__mocks__/prisma'
import { prisma } from '@/lib/prisma'
import { mockAdmin, mockUser } from '../../../fixtures/users'
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return { ...actual, getCurrentUser: vi.fn() }
})
import { getCurrentUser } from '@/lib/auth'
// Test GET
it('restituisce 403 per utente CUSTOMER', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(mockUser as any) // role: CUSTOMER
const res = await GET(makeRequest())
expect(res.status).toBe(403)
})
it('restituisce la lista prodotti paginata per ADMIN', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(mockAdmin as any)
vi.mocked(prisma.product.findMany).mockResolvedValue([])
vi.mocked(prisma.product.count).mockResolvedValue(0)
const res = await GET(makeRequest())
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toHaveProperty('pagination')
})
// Test POST
it('crea il prodotto e scrive l\'audit log', async () => {
vi.mocked(getCurrentUser).mockResolvedValue(mockAdmin as any)
vi.mocked(prisma.product.create).mockResolvedValue(mockProduct as any)
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as any)
const res = await POST(makeRequest(validProduct))
expect(res.status).toBe(201)
expect(prisma.auditLog.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ action: 'CREATE', entity: 'Product' }) })
)
})
```
---
#### `components/ui/Input.test.tsx`, `Alert.test.tsx`, `Badge.test.tsx`
Stessa struttura di `Button.test.tsx`. Leggi prima il file sorgente del componente, poi testa solo ciò che è visibile:
```typescript
import { render, screen } from '@testing-library/react'
import { Input } from '@/components/ui/Input'
it('mostra il messaggio di errore', () => {
render(<Input label="Email" error="Campo obbligatorio" />)
expect(screen.getByText('Campo obbligatorio')).toBeTruthy()
})
it('ha attributo disabled quando disabled=true', () => {
render(<Input label="Email" disabled />)
expect(screen.getByRole('textbox')).toBeDisabled()
})
```
---
#### Da non testare
- Le **23 pagine `page.tsx`** — Server Components Next.js con fetch dati, richiedono il runtime Next.js completo per essere testati in modo significativo
- **`UserContext.tsx`** — context React client-side, coperto implicitamente dai test di integrazione
- **`middleware.ts`** — header di sicurezza statici, nessuna logica da verificare
+81
View File
@@ -0,0 +1,81 @@
import { vi } from 'vitest'
export const prisma = {
user: {
findUnique: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
count: vi.fn(),
},
session: {
create: vi.fn(),
findUnique: vi.fn(),
delete: vi.fn(),
deleteMany: vi.fn(),
},
loginAttempt: {
count: vi.fn(),
create: vi.fn(),
deleteMany: vi.fn(),
},
order: {
create: vi.fn(),
update: vi.fn(),
findUnique: vi.fn(),
findMany: vi.fn(),
count: vi.fn(),
},
orderItem: {
create: vi.fn(),
findMany: vi.fn(),
},
payment: {
create: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
},
product: {
findUnique: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
count: vi.fn(),
},
productType: {
findUnique: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
category: {
findUnique: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
review: {
findMany: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
count: vi.fn(),
},
auditLog: {
create: vi.fn(),
findMany: vi.fn(),
},
siteSettings: {
findMany: vi.fn(),
upsert: vi.fn(),
},
$transaction: vi.fn((fn: (tx: unknown) => unknown) => fn(prisma)),
}
vi.mock('@/lib/prisma', () => ({ prisma }))
@@ -0,0 +1,76 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { ProductCard } from '@/components/storefront/ProductCard'
vi.mock('next/link', () => ({
default: ({ href, children, className }: any) => (
<a href={href} className={className}>{children}</a>
),
}))
const baseProduct = {
id: 'prod-1',
title: 'Maglietta Blu',
slug: 'maglietta-blu',
basePrice: 2999,
currency: 'EUR',
images: [{ url: '/uploads/prod-1/photo.jpg', altText: 'Maglietta blu' }],
}
describe('ProductCard', () => {
it('renders the product title', () => {
render(<ProductCard product={baseProduct} />)
expect(screen.getByText('Maglietta Blu')).toBeTruthy()
})
it('formats price correctly (cents → euros with 2 decimals)', () => {
render(<ProductCard product={baseProduct} />)
expect(screen.getByText(/29\.99/)).toBeTruthy()
})
it('shows the currency', () => {
render(<ProductCard product={baseProduct} />)
expect(screen.getByText(/EUR/)).toBeTruthy()
})
it('links to the correct product URL', () => {
const { container } = render(<ProductCard product={baseProduct} />)
const link = container.querySelector('a')
expect(link?.getAttribute('href')).toBe('/products/maglietta-blu')
})
it('renders the product image when images are present', () => {
render(<ProductCard product={baseProduct} />)
const img = screen.getByRole('img')
expect(img.getAttribute('src')).toBe('/uploads/prod-1/photo.jpg')
})
it('uses altText when provided', () => {
render(<ProductCard product={baseProduct} />)
expect(screen.getByRole('img').getAttribute('alt')).toBe('Maglietta blu')
})
it('falls back to product title as alt text when altText is null', () => {
const product = {
...baseProduct,
images: [{ url: '/img.jpg', altText: null }],
}
render(<ProductCard product={product} />)
expect(screen.getByRole('img').getAttribute('alt')).toBe('Maglietta Blu')
})
it('shows "No image" placeholder when images array is empty', () => {
render(<ProductCard product={{ ...baseProduct, images: [] }} />)
expect(screen.getByText('No image')).toBeTruthy()
})
it('does not render img tag when no images', () => {
render(<ProductCard product={{ ...baseProduct, images: [] }} />)
expect(screen.queryByRole('img')).toBeNull()
})
it('formats price = 0 correctly', () => {
render(<ProductCard product={{ ...baseProduct, basePrice: 0 }} />)
expect(screen.getByText(/0\.00/)).toBeTruthy()
})
})
@@ -0,0 +1,90 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import ProductDetailPage from '@/app/products/[slug]/page'
const mockPush = vi.fn()
vi.mock('next/navigation', () => ({
useParams: () => ({ slug: 'test-product' }),
useRouter: () => ({ push: mockPush }),
}))
vi.mock('@/components/storefront/Navbar', () => ({
Navbar: () => null,
}))
const mockProduct = {
product: {
id: 'prod-1',
title: 'Test Product',
slug: 'test-product',
description: 'A test product',
basePrice: 1000,
currency: 'EUR',
stock: 10,
images: [],
variants: [],
categories: [],
reviews: [],
},
}
describe('ProductDetailPage - cart behavior', () => {
beforeEach(() => {
localStorage.clear()
mockPush.mockClear()
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ json: () => Promise.resolve(mockProduct) })
)
})
it('Add to Cart aggiunge 1 articolo al carrello', async () => {
render(<ProductDetailPage />)
await waitFor(() => screen.getByText('Test Product'))
fireEvent.click(screen.getByText('Add to Cart'))
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
expect(cart).toHaveLength(1)
expect(cart[0].quantity).toBe(1)
expect(cart[0].productId).toBe('prod-1')
})
it('Add to Cart cliccato due volte incrementa la quantità a 2', async () => {
render(<ProductDetailPage />)
await waitFor(() => screen.getByText('Test Product'))
fireEvent.click(screen.getByText('Add to Cart'))
fireEvent.click(screen.getByText('Add to Cart'))
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
expect(cart).toHaveLength(1)
expect(cart[0].quantity).toBe(2)
})
it('Buy Now aggiunge 1 articolo e naviga al carrello', async () => {
render(<ProductDetailPage />)
await waitFor(() => screen.getByText('Test Product'))
fireEvent.click(screen.getByText('Buy Now'))
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
expect(cart).toHaveLength(1)
expect(cart[0].quantity).toBe(1)
expect(mockPush).toHaveBeenCalledWith('/cart')
})
it('Add to Cart seguito da Buy Now non duplica: rimane 1 articolo con quantità 1', async () => {
render(<ProductDetailPage />)
await waitFor(() => screen.getByText('Test Product'))
fireEvent.click(screen.getByText('Add to Cart'))
fireEvent.click(screen.getByText('Buy Now'))
const cart = JSON.parse(localStorage.getItem('cart') || '[]')
expect(cart).toHaveLength(1)
expect(cart[0].quantity).toBe(1)
expect(mockPush).toHaveBeenCalledWith('/cart')
})
})
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from '@/components/ui/Button'
describe('Button', () => {
it('renders children text', () => {
render(<Button>Clicca qui</Button>)
expect(screen.getByText('Clicca qui')).toBeTruthy()
})
it('is disabled when loading=true', () => {
render(<Button loading>Salva</Button>)
expect(screen.getByRole('button')).toBeDisabled()
})
it('shows spinner SVG when loading=true', () => {
const { container } = render(<Button loading>Salva</Button>)
expect(container.querySelector('svg')).toBeTruthy()
})
it('does not show spinner when not loading', () => {
const { container } = render(<Button>Salva</Button>)
expect(container.querySelector('svg')).toBeNull()
})
it('is disabled when disabled prop is set', () => {
render(<Button disabled>Salva</Button>)
expect(screen.getByRole('button')).toBeDisabled()
})
it('calls onClick when clicked', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Clic</Button>)
await userEvent.click(screen.getByRole('button'))
expect(onClick).toHaveBeenCalledOnce()
})
it('does not call onClick when disabled', async () => {
const onClick = vi.fn()
render(<Button disabled onClick={onClick}>Clic</Button>)
await userEvent.click(screen.getByRole('button'))
expect(onClick).not.toHaveBeenCalled()
})
it('applies primary variant class by default', () => {
render(<Button>Primary</Button>)
expect(screen.getByRole('button').className).toContain('bg-blue-600')
})
it('applies danger variant class', () => {
render(<Button variant="danger">Elimina</Button>)
expect(screen.getByRole('button').className).toContain('bg-red-600')
})
it('applies secondary variant class', () => {
render(<Button variant="secondary">Annulla</Button>)
expect(screen.getByRole('button').className).toContain('bg-gray-200')
})
})
+53
View File
@@ -0,0 +1,53 @@
import { mockUser } from './users'
export const mockOrder = {
id: 'order-1',
userId: mockUser.id,
status: 'PENDING' as const,
grandTotal: 2999,
currency: 'EUR',
createdAt: new Date('2024-01-01'),
updatedAt: new Date('2024-01-01'),
user: mockUser,
}
export const mockPayment = {
id: 'payment-1',
orderId: mockOrder.id,
provider: 'stripe',
providerPaymentId: 'pi_test_123',
status: 'pending',
amount: 2999,
currency: 'EUR',
rawPayload: {},
createdAt: new Date('2024-01-01'),
updatedAt: new Date('2024-01-01'),
}
export const mockStripeCheckoutEvent = {
type: 'checkout.session.completed',
data: {
object: {
metadata: { orderId: mockOrder.id },
payment_intent: 'pi_test_123',
},
},
}
export const mockStripePaymentSucceededEvent = {
type: 'payment_intent.succeeded',
data: {
object: {
id: 'pi_test_123',
},
},
}
export const mockStripePaymentFailedEvent = {
type: 'payment_intent.payment_failed',
data: {
object: {
id: 'pi_test_123',
},
},
}
+27
View File
@@ -0,0 +1,27 @@
export const mockUser = {
id: 'user-1',
email: 'test@example.com',
name: 'Test User',
passwordHash: '$2a$12$hashedpassword',
role: 'CUSTOMER' as const,
mustChangePassword: false,
createdAt: new Date('2024-01-01'),
updatedAt: new Date('2024-01-01'),
}
export const mockAdmin = {
...mockUser,
id: 'admin-1',
email: 'admin@example.com',
name: 'Admin User',
role: 'ADMIN' as const,
}
export const mockSession = {
id: 'session-1',
userId: mockUser.id,
tokenHash: 'abc123hash',
expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
createdAt: new Date('2024-01-01'),
user: mockUser,
}
+119
View File
@@ -0,0 +1,119 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import '../../../__mocks__/prisma'
import { NextRequest } from 'next/server'
import { POST } from '@/app/api/auth/login/route'
import { prisma } from '@/lib/prisma'
import { mockUser } from '../../../fixtures/users'
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return {
...actual,
verifyPassword: vi.fn(),
createSession: vi.fn().mockResolvedValue('mock-session-token'),
setSessionCookie: vi.fn(),
}
})
import { verifyPassword, createSession, setSessionCookie } from '@/lib/auth'
function makeRequest(body: unknown, ip = '1.2.3.4') {
return new NextRequest(
new Request('http://localhost/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-forwarded-for': ip },
body: JSON.stringify(body),
})
)
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(0)
vi.mocked(prisma.loginAttempt.create).mockResolvedValue({ id: '1', key: '1.2.3.4', createdAt: new Date() })
vi.mocked(prisma.loginAttempt.deleteMany).mockResolvedValue({ count: 0 })
})
describe('POST /api/auth/login', () => {
it('returns 429 when rate limit exceeded', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(10)
const res = await POST(makeRequest({ email: 'user@example.com', password: 'pass' }))
expect(res.status).toBe(429)
const data = await res.json()
expect(data.error).toMatch(/Too many/)
})
it('returns 400 for invalid email format', async () => {
const res = await POST(makeRequest({ email: 'not-an-email', password: 'pass' }))
expect(res.status).toBe(400)
})
it('returns 400 for empty password', async () => {
const res = await POST(makeRequest({ email: 'user@example.com', password: '' }))
expect(res.status).toBe(400)
})
it('returns 400 for malformed JSON body', async () => {
const req = new NextRequest(
new Request('http://localhost/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-forwarded-for': '1.2.3.4' },
body: 'not-json',
})
)
const res = await POST(req)
expect(res.status).toBe(400)
})
it('returns 401 when user not found', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null)
const res = await POST(makeRequest({ email: 'notfound@example.com', password: 'SomePass1!' }))
expect(res.status).toBe(401)
const data = await res.json()
expect(data.error).toBe('Invalid email or password')
})
it('records a failed attempt when user not found', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(null)
await POST(makeRequest({ email: 'notfound@example.com', password: 'SomePass1!' }))
expect(prisma.loginAttempt.create).toHaveBeenCalledWith({ data: { key: '1.2.3.4' } })
})
it('returns 401 when password is wrong', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
vi.mocked(verifyPassword).mockResolvedValue(false)
const res = await POST(makeRequest({ email: mockUser.email, password: 'WrongPass1!' }))
expect(res.status).toBe(401)
expect((await res.json()).error).toBe('Invalid email or password')
})
it('returns 200 with user data on successful login', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
vi.mocked(verifyPassword).mockResolvedValue(true)
vi.mocked(prisma.session.create).mockResolvedValue({} as any)
const res = await POST(makeRequest({ email: mockUser.email, password: 'ValidPass1!' }))
expect(res.status).toBe(200)
const data = await res.json()
expect(data.user.email).toBe(mockUser.email)
expect(data.user.role).toBe(mockUser.role)
expect(data.user).not.toHaveProperty('passwordHash')
})
it('creates a session and sets cookie on successful login', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
vi.mocked(verifyPassword).mockResolvedValue(true)
vi.mocked(prisma.session.create).mockResolvedValue({} as any)
await POST(makeRequest({ email: mockUser.email, password: 'ValidPass1!' }))
expect(createSession).toHaveBeenCalledWith(mockUser.id)
expect(setSessionCookie).toHaveBeenCalledWith('mock-session-token')
})
})
+107
View File
@@ -0,0 +1,107 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import '../../../__mocks__/prisma'
import { NextRequest } from 'next/server'
import { POST } from '@/app/api/auth/register/route'
import { prisma } from '@/lib/prisma'
import { mockUser } from '../../../fixtures/users'
vi.mock('@/lib/auth', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth')>()
return {
...actual,
hashPassword: vi.fn().mockResolvedValue('$2a$12$hashedpassword'),
createSession: vi.fn().mockResolvedValue('mock-token'),
setSessionCookie: vi.fn(),
}
})
import { hashPassword, createSession, setSessionCookie } from '@/lib/auth'
function makeRequest(body: unknown) {
return new NextRequest(
new Request('http://localhost/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
)
}
const validBody = {
email: 'newuser@example.com',
password: 'ValidPass123!',
name: 'Nuovo Utente',
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(prisma.user.findUnique).mockResolvedValue(null)
vi.mocked(prisma.user.create).mockResolvedValue({ ...mockUser, email: validBody.email, name: validBody.name } as any)
vi.mocked(prisma.session.create).mockResolvedValue({} as any)
})
describe('POST /api/auth/register', () => {
it('returns 201 with user data on successful registration', async () => {
const res = await POST(makeRequest(validBody))
expect(res.status).toBe(201)
const data = await res.json()
expect(data.user.email).toBe(validBody.email)
expect(data.user).not.toHaveProperty('passwordHash')
})
it('hashes the password before storing', async () => {
await POST(makeRequest(validBody))
expect(hashPassword).toHaveBeenCalledWith(validBody.password)
const createCall = vi.mocked(prisma.user.create).mock.calls[0][0]
expect(createCall.data.passwordHash).toBe('$2a$12$hashedpassword')
})
it('creates a session and sets cookie after registration', async () => {
await POST(makeRequest(validBody))
expect(createSession).toHaveBeenCalled()
expect(setSessionCookie).toHaveBeenCalledWith('mock-token')
})
it('sets role to CUSTOMER', async () => {
await POST(makeRequest(validBody))
const createCall = vi.mocked(prisma.user.create).mock.calls[0][0]
expect(createCall.data.role).toBe('CUSTOMER')
})
it('returns 409 when email is already in use', async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue(mockUser as any)
const res = await POST(makeRequest(validBody))
expect(res.status).toBe(409)
const data = await res.json()
expect(data.error).toMatch(/already/)
})
it('returns 400 for invalid email', async () => {
const res = await POST(makeRequest({ ...validBody, email: 'not-an-email' }))
expect(res.status).toBe(400)
})
it('returns 400 for weak password (too short)', async () => {
const res = await POST(makeRequest({ ...validBody, password: 'Short1!' }))
expect(res.status).toBe(400)
})
it('returns 400 for empty name', async () => {
const res = await POST(makeRequest({ ...validBody, name: '' }))
expect(res.status).toBe(400)
})
it('returns 400 for malformed JSON', async () => {
const req = new NextRequest(
new Request('http://localhost/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: 'bad-json',
})
)
const res = await POST(req)
expect(res.status).toBe(400)
})
})
@@ -0,0 +1,166 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import '../../../__mocks__/prisma'
import { NextRequest } from 'next/server'
import { POST } from '@/app/api/webhooks/stripe/route'
import { prisma } from '@/lib/prisma'
import {
mockOrder,
mockPayment,
mockStripeCheckoutEvent,
mockStripePaymentSucceededEvent,
mockStripePaymentFailedEvent,
} from '../../../fixtures/orders'
vi.mock('@/lib/stripe', () => ({
constructWebhookEvent: vi.fn(),
}))
vi.mock('@/lib/email', () => ({
sendOrderConfirmationEmail: vi.fn().mockResolvedValue(undefined),
}))
import { constructWebhookEvent } from '@/lib/stripe'
import { sendOrderConfirmationEmail } from '@/lib/email'
function makeRequest(body: string, signature = 'valid-sig') {
return new NextRequest(
new Request('http://localhost/api/webhooks/stripe', {
method: 'POST',
headers: { 'stripe-signature': signature, 'Content-Type': 'text/plain' },
body,
})
)
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(prisma.order.update).mockResolvedValue(mockOrder as any)
vi.mocked(prisma.payment.updateMany).mockResolvedValue({ count: 1 })
vi.mocked(prisma.payment.update).mockResolvedValue(mockPayment as any)
vi.mocked(prisma.payment.findFirst).mockResolvedValue(mockPayment as any)
vi.mocked(prisma.order.findUnique).mockResolvedValue({ ...mockOrder, user: mockOrder.user } as any)
})
describe('POST /api/webhooks/stripe', () => {
it('returns 400 when stripe-signature header is missing', async () => {
const req = new NextRequest(
new Request('http://localhost/api/webhooks/stripe', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: '{}',
})
)
const res = await POST(req)
expect(res.status).toBe(400)
expect((await res.json()).error).toMatch(/signature/)
})
it('returns 400 when signature verification fails', async () => {
vi.mocked(constructWebhookEvent).mockImplementation(() => {
throw new Error('stripe_signature_mismatch')
})
const res = await POST(makeRequest('{}', 'bad-sig'))
expect(res.status).toBe(400)
expect((await res.json()).error).toBe('Invalid signature')
})
it('processes checkout.session.completed: updates order to PAID', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripeCheckoutEvent as any)
const res = await POST(makeRequest(JSON.stringify(mockStripeCheckoutEvent)))
expect(res.status).toBe(200)
expect(prisma.order.update).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: mockOrder.id }, data: { status: 'PAID' } })
)
})
it('processes checkout.session.completed: updates payment record', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripeCheckoutEvent as any)
await POST(makeRequest(JSON.stringify(mockStripeCheckoutEvent)))
expect(prisma.payment.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { orderId: mockOrder.id },
data: expect.objectContaining({ status: 'paid' }),
})
)
})
it('processes checkout.session.completed: sends confirmation email', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripeCheckoutEvent as any)
await POST(makeRequest(JSON.stringify(mockStripeCheckoutEvent)))
expect(sendOrderConfirmationEmail).toHaveBeenCalledWith(
mockOrder.user.email,
expect.objectContaining({ orderId: mockOrder.id })
)
})
it('skips email send if order user has no email', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripeCheckoutEvent as any)
vi.mocked(prisma.order.findUnique).mockResolvedValue({ ...mockOrder, user: null } as any)
await POST(makeRequest(JSON.stringify(mockStripeCheckoutEvent)))
expect(sendOrderConfirmationEmail).not.toHaveBeenCalled()
})
it('processes checkout.session.completed without orderId: no DB update', async () => {
const eventWithoutOrderId = {
type: 'checkout.session.completed',
data: { object: { metadata: {}, payment_intent: 'pi_test' } },
}
vi.mocked(constructWebhookEvent).mockReturnValue(eventWithoutOrderId as any)
const res = await POST(makeRequest('{}'))
expect(res.status).toBe(200)
expect(prisma.order.update).not.toHaveBeenCalled()
})
it('processes payment_intent.succeeded: updates payment and order', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripePaymentSucceededEvent as any)
const res = await POST(makeRequest(JSON.stringify(mockStripePaymentSucceededEvent)))
expect(res.status).toBe(200)
expect(prisma.payment.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ status: 'paid' }) })
)
expect(prisma.order.update).toHaveBeenCalledWith(
expect.objectContaining({ data: { status: 'PAID' } })
)
})
it('processes payment_intent.succeeded: no-op when payment not found', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripePaymentSucceededEvent as any)
vi.mocked(prisma.payment.findFirst).mockResolvedValue(null)
const res = await POST(makeRequest('{}'))
expect(res.status).toBe(200)
expect(prisma.payment.update).not.toHaveBeenCalled()
})
it('processes payment_intent.payment_failed: sets status to failed and CANCELLED', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue(mockStripePaymentFailedEvent as any)
const res = await POST(makeRequest(JSON.stringify(mockStripePaymentFailedEvent)))
expect(res.status).toBe(200)
expect(prisma.payment.update).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ status: 'failed' }) })
)
expect(prisma.order.update).toHaveBeenCalledWith(
expect.objectContaining({ data: { status: 'CANCELLED' } })
)
})
it('returns 200 for unhandled event types', async () => {
vi.mocked(constructWebhookEvent).mockReturnValue({ type: 'customer.created', data: { object: {} } } as any)
const res = await POST(makeRequest('{}'))
expect(res.status).toBe(200)
expect((await res.json()).received).toBe(true)
})
})
+31
View File
@@ -0,0 +1,31 @@
import '@testing-library/jest-dom'
import { vi } from 'vitest'
// Env vars necessarie per i test
process.env.STRIPE_SECRET_KEY = 'sk_test_mock'
process.env.STRIPE_WEBHOOK_SECRET = 'whsec_test_mock'
process.env.SMTP_HOST = 'localhost'
process.env.SMTP_PORT = '1025'
process.env.APP_URL = 'http://localhost'
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test'
process.env.NODE_ENV = 'test'
process.env.AUTH_SECRET = 'test-secret-32-chars-minimum-ok!'
// Mock di next/headers (cookies() lancia fuori dal runtime Next.js)
vi.mock('next/headers', () => {
const mockCookieStore = {
get: vi.fn(),
set: vi.fn(),
delete: vi.fn(),
}
return {
cookies: vi.fn(() => mockCookieStore),
}
})
// Mock di next/navigation
vi.mock('next/navigation', () => ({
useRouter: vi.fn(() => ({ push: vi.fn(), replace: vi.fn() })),
usePathname: vi.fn(() => '/'),
redirect: vi.fn(),
}))
+15
View File
@@ -0,0 +1,15 @@
{
"extends": "../app/tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["../app/src/*"]
},
"types": ["vitest/globals", "@testing-library/jest-dom"]
},
"include": [
"./**/*.ts",
"./**/*.tsx"
],
"exclude": ["node_modules"]
}
+222
View File
@@ -0,0 +1,222 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import '../../../test/__mocks__/prisma'
import {
hashToken,
hashPassword,
verifyPassword,
validatePasswordStrength,
createSession,
getSessionToken,
getSession,
getCurrentUser,
deleteSession,
deleteAllUserSessions,
} from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { mockUser, mockSession } from '../../fixtures/users'
import { cookies } from 'next/headers'
// ─── hashToken ───────────────────────────────────────────────────────────────
describe('hashToken', () => {
it('returns a 64-char hex string', () => {
const hash = hashToken('sometoken')
expect(hash).toMatch(/^[a-f0-9]{64}$/)
})
it('is deterministic for the same input', () => {
expect(hashToken('abc')).toBe(hashToken('abc'))
})
it('produces different hashes for different inputs', () => {
expect(hashToken('abc')).not.toBe(hashToken('xyz'))
})
})
// ─── hashPassword / verifyPassword ───────────────────────────────────────────
describe('hashPassword / verifyPassword', () => {
it('hashes a password and verifies it correctly', async () => {
const hash = await hashPassword('MyPassword1!')
expect(await verifyPassword('MyPassword1!', hash)).toBe(true)
})
it('returns false for wrong password', async () => {
const hash = await hashPassword('MyPassword1!')
expect(await verifyPassword('WrongPassword1!', hash)).toBe(false)
})
it('produces different hashes for the same password (bcrypt salt)', async () => {
const h1 = await hashPassword('SamePass1!')
const h2 = await hashPassword('SamePass1!')
expect(h1).not.toBe(h2)
})
})
// ─── validatePasswordStrength ─────────────────────────────────────────────────
describe('validatePasswordStrength', () => {
it('returns null for a strong password', () => {
expect(validatePasswordStrength('StrongPass1!')).toBeNull()
})
it('rejects password shorter than 12 chars', () => {
expect(validatePasswordStrength('Short1!')).toMatch(/12 characters/)
})
it('rejects password without uppercase', () => {
expect(validatePasswordStrength('nouppercase1!')).toMatch(/uppercase/)
})
it('rejects password without lowercase', () => {
expect(validatePasswordStrength('NOLOWERCASE1!')).toMatch(/lowercase/)
})
it('rejects password without number', () => {
expect(validatePasswordStrength('NoNumberHere!')).toMatch(/number/)
})
it('rejects password without symbol', () => {
expect(validatePasswordStrength('NoSymbolHere12')).toMatch(/symbol/)
})
it('checks length first (shortest error message path)', () => {
expect(validatePasswordStrength('short')).toMatch(/12 characters/)
})
})
// ─── createSession ────────────────────────────────────────────────────────────
describe('createSession', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(prisma.session.create).mockResolvedValue(mockSession)
})
it('creates a session in DB and returns a token string', async () => {
const token = await createSession(mockUser.id)
expect(typeof token).toBe('string')
expect(token.length).toBeGreaterThan(0)
})
it('calls prisma.session.create with userId and tokenHash', async () => {
const token = await createSession(mockUser.id)
expect(prisma.session.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ userId: mockUser.id }),
})
)
const callArg = vi.mocked(prisma.session.create).mock.calls[0][0]
const tokenHash = hashToken(token)
expect(callArg.data.tokenHash).toBe(tokenHash)
})
it('sets expiry ~30 days from now', async () => {
await createSession(mockUser.id)
const callArg = vi.mocked(prisma.session.create).mock.calls[0][0]
const expiresAt = callArg.data.expiresAt as Date
const diffDays = (expiresAt.getTime() - Date.now()) / (1000 * 60 * 60 * 24)
expect(diffDays).toBeCloseTo(30, 0)
})
})
// ─── getSessionToken ──────────────────────────────────────────────────────────
describe('getSessionToken', () => {
it('returns token from cookie', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'mytoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
expect(await getSessionToken()).toBe('mytoken')
})
it('returns null when cookie is missing', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue(undefined), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
expect(await getSessionToken()).toBeNull()
})
})
// ─── getSession ───────────────────────────────────────────────────────────────
describe('getSession', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns null when no token cookie', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue(undefined), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
expect(await getSession()).toBeNull()
})
it('returns session when token is valid and not expired', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'validtoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
vi.mocked(prisma.session.findUnique).mockResolvedValue(mockSession as any)
const session = await getSession()
expect(session).not.toBeNull()
expect(session?.user.id).toBe(mockUser.id)
})
it('returns null and deletes session when expired', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'expiredtoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
const expiredSession = { ...mockSession, expiresAt: new Date(Date.now() - 1000) }
vi.mocked(prisma.session.findUnique).mockResolvedValue(expiredSession as any)
vi.mocked(prisma.session.delete).mockResolvedValue(expiredSession as any)
const result = await getSession()
expect(result).toBeNull()
expect(prisma.session.delete).toHaveBeenCalledWith({ where: { id: expiredSession.id } })
})
it('returns null when session not found in DB', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'unknowntoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
vi.mocked(prisma.session.findUnique).mockResolvedValue(null)
expect(await getSession()).toBeNull()
})
})
// ─── getCurrentUser ───────────────────────────────────────────────────────────
describe('getCurrentUser', () => {
it('returns user from valid session', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue({ value: 'validtoken' }), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
vi.mocked(prisma.session.findUnique).mockResolvedValue(mockSession as any)
const user = await getCurrentUser()
expect(user?.id).toBe(mockUser.id)
})
it('returns null when no session', async () => {
const mockCookieStore = { get: vi.fn().mockReturnValue(undefined), set: vi.fn(), delete: vi.fn() }
vi.mocked(cookies).mockReturnValue(mockCookieStore as any)
expect(await getCurrentUser()).toBeNull()
})
})
// ─── deleteSession / deleteAllUserSessions ────────────────────────────────────
describe('deleteSession', () => {
it('calls prisma.session.deleteMany with the correct tokenHash', async () => {
vi.mocked(prisma.session.deleteMany).mockResolvedValue({ count: 1 })
await deleteSession('mytoken')
expect(prisma.session.deleteMany).toHaveBeenCalledWith({
where: { tokenHash: hashToken('mytoken') },
})
})
})
describe('deleteAllUserSessions', () => {
it('calls prisma.session.deleteMany with the userId', async () => {
vi.mocked(prisma.session.deleteMany).mockResolvedValue({ count: 3 })
await deleteAllUserSessions('user-123')
expect(prisma.session.deleteMany).toHaveBeenCalledWith({ where: { userId: 'user-123' } })
})
})
+109
View File
@@ -0,0 +1,109 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { mockSendMail, mockCreateTransport } = vi.hoisted(() => {
const mockSendMail = vi.fn().mockResolvedValue({ messageId: 'mock-id' })
const mockCreateTransport = vi.fn().mockReturnValue({ sendMail: mockSendMail })
return { mockSendMail, mockCreateTransport }
})
vi.mock('nodemailer', () => ({
default: { createTransport: mockCreateTransport },
}))
import { sendEmail, sendOrderConfirmationEmail, sendPasswordResetEmail } from '@/lib/email'
beforeEach(() => {
vi.clearAllMocks()
mockSendMail.mockResolvedValue({ messageId: 'mock-id' })
})
// ─── sendEmail ────────────────────────────────────────────────────────────────
describe('sendEmail', () => {
it('calls sendMail with correct to, subject, html', async () => {
await sendEmail({ to: 'user@example.com', subject: 'Test', html: '<p>Hello</p>' })
expect(mockSendMail).toHaveBeenCalledWith(
expect.objectContaining({
to: 'user@example.com',
subject: 'Test',
html: '<p>Hello</p>',
})
)
})
it('includes optional text field when provided', async () => {
await sendEmail({ to: 'u@e.com', subject: 'S', html: '<p>h</p>', text: 'plain text' })
expect(mockSendMail).toHaveBeenCalledWith(expect.objectContaining({ text: 'plain text' }))
})
it('propagates sendMail errors', async () => {
mockSendMail.mockRejectedValueOnce(new Error('SMTP down'))
await expect(sendEmail({ to: 'u@e.com', subject: 'S', html: '<p>h</p>' })).rejects.toThrow('SMTP down')
})
})
// ─── sendOrderConfirmationEmail ───────────────────────────────────────────────
describe('sendOrderConfirmationEmail', () => {
it('sends email with correct subject containing orderId', async () => {
await sendOrderConfirmationEmail('customer@example.com', {
orderId: 'order-42',
grandTotal: 2999,
currency: 'EUR',
})
expect(mockSendMail).toHaveBeenCalledWith(
expect.objectContaining({
to: 'customer@example.com',
subject: expect.stringContaining('order-42'),
})
)
})
it('formats price correctly (cents to euros)', async () => {
await sendOrderConfirmationEmail('customer@example.com', {
orderId: 'order-1',
grandTotal: 2999,
currency: 'EUR',
})
const callArg = mockSendMail.mock.calls[0][0]
expect(callArg.html).toContain('29.99')
expect(callArg.html).toContain('EUR')
})
it('includes orderId in the email body', async () => {
await sendOrderConfirmationEmail('customer@example.com', {
orderId: 'order-xyz',
grandTotal: 1000,
currency: 'USD',
})
const callArg = mockSendMail.mock.calls[0][0]
expect(callArg.html).toContain('order-xyz')
})
it('includes account orders link', async () => {
await sendOrderConfirmationEmail('customer@example.com', {
orderId: 'order-1',
grandTotal: 100,
currency: 'EUR',
})
const callArg = mockSendMail.mock.calls[0][0]
expect(callArg.html).toContain('/account/orders')
})
})
// ─── sendPasswordResetEmail ───────────────────────────────────────────────────
describe('sendPasswordResetEmail', () => {
it('sends email with reset token in URL', async () => {
await sendPasswordResetEmail('user@example.com', 'reset-token-abc')
const callArg = mockSendMail.mock.calls[0][0]
expect(callArg.html).toContain('reset-token-abc')
expect(callArg.to).toBe('user@example.com')
})
it('subject mentions password reset', async () => {
await sendPasswordResetEmail('user@example.com', 'token')
const callArg = mockSendMail.mock.calls[0][0]
expect(callArg.subject).toMatch(/[Pp]assword [Rr]eset/)
})
})
+71
View File
@@ -0,0 +1,71 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import '../../../test/__mocks__/prisma'
import { checkRateLimit, recordAttempt } from '@/lib/rate-limit'
import { prisma } from '@/lib/prisma'
beforeEach(() => {
vi.clearAllMocks()
})
describe('checkRateLimit', () => {
it('returns not limited when attempts < 10', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(5)
const result = await checkRateLimit('1.2.3.4')
expect(result.limited).toBe(false)
expect(result.remaining).toBe(5)
})
it('returns limited when attempts >= 10', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(10)
const result = await checkRateLimit('1.2.3.4')
expect(result.limited).toBe(true)
expect(result.remaining).toBe(0)
})
it('returns limited when attempts > 10', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(15)
const result = await checkRateLimit('1.2.3.4')
expect(result.limited).toBe(true)
})
it('returns remaining = 1 when attempts = 9', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(9)
const result = await checkRateLimit('1.2.3.4')
expect(result.limited).toBe(false)
expect(result.remaining).toBe(1)
})
it('queries with a windowStart within the last 15 minutes', async () => {
vi.mocked(prisma.loginAttempt.count).mockResolvedValue(0)
const before = new Date(Date.now() - 15 * 60 * 1000 - 100)
await checkRateLimit('1.2.3.4')
const callArg = vi.mocked(prisma.loginAttempt.count).mock.calls[0][0]
const windowStart = callArg?.where?.createdAt?.gte as Date
expect(windowStart.getTime()).toBeGreaterThan(before.getTime())
})
})
describe('recordAttempt', () => {
it('creates a login attempt record', async () => {
vi.mocked(prisma.loginAttempt.create).mockResolvedValue({ id: '1', key: '1.2.3.4', createdAt: new Date() })
vi.mocked(prisma.loginAttempt.deleteMany).mockResolvedValue({ count: 0 })
await recordAttempt('1.2.3.4')
expect(prisma.loginAttempt.create).toHaveBeenCalledWith({ data: { key: '1.2.3.4' } })
})
it('cleans up old records after creating', async () => {
vi.mocked(prisma.loginAttempt.create).mockResolvedValue({ id: '1', key: '1.2.3.4', createdAt: new Date() })
vi.mocked(prisma.loginAttempt.deleteMany).mockResolvedValue({ count: 0 })
await recordAttempt('1.2.3.4')
expect(prisma.loginAttempt.deleteMany).toHaveBeenCalledWith(
expect.objectContaining({ where: expect.objectContaining({ createdAt: expect.anything() }) })
)
})
})
+126
View File
@@ -0,0 +1,126 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { mockMkdir, mockWriteFile, mockUnlink } = vi.hoisted(() => ({
mockMkdir: vi.fn().mockResolvedValue(undefined),
mockWriteFile: vi.fn().mockResolvedValue(undefined),
mockUnlink: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('fs/promises', () => ({
__esModule: true,
default: { mkdir: mockMkdir, writeFile: mockWriteFile, unlink: mockUnlink },
mkdir: mockMkdir,
writeFile: mockWriteFile,
unlink: mockUnlink,
}))
import { saveImage, validateImageMagicBytes, deleteImageFile } from '@/lib/storage'
function makeJpegBuffer(): Buffer {
const b = Buffer.alloc(12)
b[0] = 0xff; b[1] = 0xd8; b[2] = 0xff
return b
}
function makePngBuffer(): Buffer {
const b = Buffer.alloc(12)
b[0] = 0x89; b[1] = 0x50; b[2] = 0x4e; b[3] = 0x47
return b
}
function makeWebpBuffer(): Buffer {
const b = Buffer.alloc(12)
b[0] = 0x52; b[1] = 0x49; b[2] = 0x46; b[3] = 0x46
b[8] = 0x57; b[9] = 0x45; b[10] = 0x42; b[11] = 0x50
return b
}
function makeIcoBuffer(): Buffer {
const b = Buffer.alloc(12)
b[0] = 0x00; b[1] = 0x00; b[2] = 0x01; b[3] = 0x00
return b
}
function makeFileFromBuffer(buf: Buffer, type: string): File {
return new File([new Uint8Array(buf)], 'test.img', { type })
}
beforeEach(() => {
vi.clearAllMocks()
mockMkdir.mockResolvedValue(undefined)
mockWriteFile.mockResolvedValue(undefined)
mockUnlink.mockResolvedValue(undefined)
})
// ─── validateImageMagicBytes ──────────────────────────────────────────────────
describe('validateImageMagicBytes', () => {
it('accepts a valid JPEG', async () => {
const file = makeFileFromBuffer(makeJpegBuffer(), 'image/jpeg')
expect(await validateImageMagicBytes(file, 'image/jpeg')).toBe(true)
})
it('accepts a valid PNG', async () => {
const file = makeFileFromBuffer(makePngBuffer(), 'image/png')
expect(await validateImageMagicBytes(file, 'image/png')).toBe(true)
})
it('accepts a valid WebP', async () => {
const file = makeFileFromBuffer(makeWebpBuffer(), 'image/webp')
expect(await validateImageMagicBytes(file, 'image/webp')).toBe(true)
})
it('accepts a valid ICO', async () => {
const file = makeFileFromBuffer(makeIcoBuffer(), 'image/x-icon')
expect(await validateImageMagicBytes(file, 'image/x-icon')).toBe(true)
})
it('rejects JPEG buffer declared as PNG', async () => {
const file = makeFileFromBuffer(makeJpegBuffer(), 'image/png')
expect(await validateImageMagicBytes(file, 'image/png')).toBe(false)
})
it('rejects unknown MIME type', async () => {
const file = makeFileFromBuffer(makeJpegBuffer(), 'image/bmp')
expect(await validateImageMagicBytes(file, 'image/bmp')).toBe(false)
})
it('rejects a random buffer as JPEG', async () => {
const file = makeFileFromBuffer(Buffer.from([0x00, 0x01, 0x02]), 'image/jpeg')
expect(await validateImageMagicBytes(file, 'image/jpeg')).toBe(false)
})
})
// ─── saveImage ────────────────────────────────────────────────────────────────
describe('saveImage', () => {
it('creates the product directory and writes file', async () => {
const buf = Buffer.from('fakeimage')
const url = await saveImage('prod-123', buf, 'photo.jpg')
expect(mockMkdir).toHaveBeenCalledWith(expect.stringContaining('prod-123'), { recursive: true })
expect(mockWriteFile).toHaveBeenCalled()
expect(url).toMatch(/^\/uploads\/prod-123\//)
expect(url).toMatch(/photo\.jpg$/)
})
it('sanitizes filename (removes special chars)', async () => {
const buf = Buffer.from('fakeimage')
const url = await saveImage('prod-123', buf, 'my photo (1).JPG')
expect(url).toMatch(/my_photo__1_\.jpg$/)
})
it('returns a URL starting with /uploads/', async () => {
const url = await saveImage('prod-abc', Buffer.from('x'), 'img.png')
expect(url).toMatch(/^\/uploads\/prod-abc\//)
})
})
// ─── deleteImageFile ──────────────────────────────────────────────────────────
describe('deleteImageFile', () => {
it('calls unlink with the correct path', async () => {
await deleteImageFile('/uploads/prod-1/image.jpg')
expect(mockUnlink).toHaveBeenCalledWith(expect.stringContaining('/uploads/prod-1/image.jpg'))
})
})
+329
View File
@@ -0,0 +1,329 @@
import { describe, it, expect } from 'vitest'
import {
loginSchema,
registerSchema,
changePasswordSchema,
productTypeSchema,
productSchema,
categorySchema,
reviewSchema,
cartItemSchema,
checkoutSchema,
settingSchema,
} from '@/lib/validate'
// ─── loginSchema ────────────────────────────────────────────────────────────
describe('loginSchema', () => {
it('accepts valid email and password', () => {
const result = loginSchema.safeParse({ email: 'user@example.com', password: 'anypass' })
expect(result.success).toBe(true)
})
it('rejects invalid email', () => {
const result = loginSchema.safeParse({ email: 'not-an-email', password: 'pass' })
expect(result.success).toBe(false)
expect(result.error?.errors[0].message).toBe('Invalid email address')
})
it('rejects empty password', () => {
const result = loginSchema.safeParse({ email: 'user@example.com', password: '' })
expect(result.success).toBe(false)
})
it('rejects missing fields', () => {
expect(loginSchema.safeParse({}).success).toBe(false)
})
})
// ─── registerSchema ──────────────────────────────────────────────────────────
describe('registerSchema', () => {
const valid = {
email: 'user@example.com',
password: 'ValidPass123!',
name: 'Mario Rossi',
}
it('accepts valid registration data', () => {
expect(registerSchema.safeParse(valid).success).toBe(true)
})
it('rejects password shorter than 12 chars', () => {
const r = registerSchema.safeParse({ ...valid, password: 'Short1!' })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toMatch(/12 characters/)
})
it('rejects password without uppercase', () => {
const r = registerSchema.safeParse({ ...valid, password: 'nouppercase1!' })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toMatch(/uppercase/)
})
it('rejects password without lowercase', () => {
const r = registerSchema.safeParse({ ...valid, password: 'NOLOWERCASE1!' })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toMatch(/lowercase/)
})
it('rejects password without number', () => {
const r = registerSchema.safeParse({ ...valid, password: 'NoNumberHere!' })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toMatch(/number/)
})
it('rejects password without symbol', () => {
const r = registerSchema.safeParse({ ...valid, password: 'NoSymbolHere1' })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toMatch(/symbol/)
})
it('rejects empty name', () => {
const r = registerSchema.safeParse({ ...valid, name: '' })
expect(r.success).toBe(false)
})
it('rejects name longer than 100 chars', () => {
const r = registerSchema.safeParse({ ...valid, name: 'a'.repeat(101) })
expect(r.success).toBe(false)
})
})
// ─── changePasswordSchema ────────────────────────────────────────────────────
describe('changePasswordSchema', () => {
it('accepts valid passwords', () => {
const r = changePasswordSchema.safeParse({
currentPassword: 'OldPass1!',
newPassword: 'NewStrongPass1!',
})
expect(r.success).toBe(true)
})
it('rejects empty currentPassword', () => {
const r = changePasswordSchema.safeParse({
currentPassword: '',
newPassword: 'NewStrongPass1!',
})
expect(r.success).toBe(false)
})
it('rejects weak newPassword', () => {
const r = changePasswordSchema.safeParse({
currentPassword: 'OldPass1!',
newPassword: 'weak',
})
expect(r.success).toBe(false)
})
})
// ─── productTypeSchema ───────────────────────────────────────────────────────
describe('productTypeSchema', () => {
const valid = { name: 'Abbigliamento', slug: 'abbigliamento', schema: { color: 'string' } }
it('accepts valid product type', () => {
expect(productTypeSchema.safeParse(valid).success).toBe(true)
})
it('rejects slug with uppercase', () => {
const r = productTypeSchema.safeParse({ ...valid, slug: 'Abbigliamento' })
expect(r.success).toBe(false)
})
it('rejects slug with spaces', () => {
const r = productTypeSchema.safeParse({ ...valid, slug: 'con spazio' })
expect(r.success).toBe(false)
})
it('accepts slug with hyphens and numbers', () => {
const r = productTypeSchema.safeParse({ ...valid, slug: 'tipo-123' })
expect(r.success).toBe(true)
})
it('rejects empty name', () => {
expect(productTypeSchema.safeParse({ ...valid, name: '' }).success).toBe(false)
})
})
// ─── productSchema ───────────────────────────────────────────────────────────
describe('productSchema', () => {
const valid = {
typeId: 'type-1',
title: 'Maglietta',
slug: 'maglietta',
description: 'Una bella maglietta',
basePrice: 1999,
currency: 'EUR',
status: 'DRAFT' as const,
attributes: {},
}
it('accepts valid product', () => {
expect(productSchema.safeParse(valid).success).toBe(true)
})
it('rejects negative price', () => {
const r = productSchema.safeParse({ ...valid, basePrice: -1 })
expect(r.success).toBe(false)
})
it('accepts price = 0', () => {
const r = productSchema.safeParse({ ...valid, basePrice: 0 })
expect(r.success).toBe(true)
})
it('rejects currency not 3 chars', () => {
const r = productSchema.safeParse({ ...valid, currency: 'EU' })
expect(r.success).toBe(false)
})
it('rejects invalid status', () => {
const r = productSchema.safeParse({ ...valid, status: 'INVALID' })
expect(r.success).toBe(false)
})
it('accepts all valid statuses', () => {
for (const status of ['DRAFT', 'PUBLISHED', 'ARCHIVED'] as const) {
expect(productSchema.safeParse({ ...valid, status }).success).toBe(true)
}
})
it('accepts optional categoryIds', () => {
const r = productSchema.safeParse({ ...valid, categoryIds: ['cat-1', 'cat-2'] })
expect(r.success).toBe(true)
})
it('rejects non-integer price', () => {
const r = productSchema.safeParse({ ...valid, basePrice: 19.99 })
expect(r.success).toBe(false)
})
})
// ─── categorySchema ──────────────────────────────────────────────────────────
describe('categorySchema', () => {
const valid = { name: 'Uomo', slug: 'uomo' }
it('accepts valid category', () => {
expect(categorySchema.safeParse(valid).success).toBe(true)
})
it('accepts category with parentId', () => {
expect(categorySchema.safeParse({ ...valid, parentId: 'parent-1' }).success).toBe(true)
})
it('accepts parentId = null', () => {
expect(categorySchema.safeParse({ ...valid, parentId: null }).success).toBe(true)
})
it('rejects slug with special chars', () => {
const r = categorySchema.safeParse({ ...valid, slug: 'cat@home' })
expect(r.success).toBe(false)
})
})
// ─── reviewSchema ────────────────────────────────────────────────────────────
describe('reviewSchema', () => {
const valid = { productId: 'prod-1', rating: 4 }
it('accepts valid review', () => {
expect(reviewSchema.safeParse(valid).success).toBe(true)
})
it('rejects rating 0', () => {
expect(reviewSchema.safeParse({ ...valid, rating: 0 }).success).toBe(false)
})
it('rejects rating 6', () => {
expect(reviewSchema.safeParse({ ...valid, rating: 6 }).success).toBe(false)
})
it('accepts all valid ratings 1-5', () => {
for (const rating of [1, 2, 3, 4, 5]) {
expect(reviewSchema.safeParse({ ...valid, rating }).success).toBe(true)
}
})
it('rejects comment longer than 2000 chars', () => {
const r = reviewSchema.safeParse({ ...valid, comment: 'a'.repeat(2001) })
expect(r.success).toBe(false)
})
it('accepts title up to 200 chars', () => {
expect(reviewSchema.safeParse({ ...valid, title: 'a'.repeat(200) }).success).toBe(true)
})
})
// ─── cartItemSchema ──────────────────────────────────────────────────────────
describe('cartItemSchema', () => {
const valid = { productId: 'prod-1', quantity: 2 }
it('accepts valid cart item', () => {
expect(cartItemSchema.safeParse(valid).success).toBe(true)
})
it('rejects quantity 0', () => {
expect(cartItemSchema.safeParse({ ...valid, quantity: 0 }).success).toBe(false)
})
it('rejects quantity over 100', () => {
expect(cartItemSchema.safeParse({ ...valid, quantity: 101 }).success).toBe(false)
})
it('accepts quantity = 100', () => {
expect(cartItemSchema.safeParse({ ...valid, quantity: 100 }).success).toBe(true)
})
it('accepts optional variantId', () => {
expect(cartItemSchema.safeParse({ ...valid, variantId: 'var-1' }).success).toBe(true)
})
})
// ─── checkoutSchema ──────────────────────────────────────────────────────────
describe('checkoutSchema', () => {
const valid = { items: [{ productId: 'prod-1', quantity: 1 }] }
it('accepts valid checkout', () => {
expect(checkoutSchema.safeParse(valid).success).toBe(true)
})
it('rejects empty items array', () => {
const r = checkoutSchema.safeParse({ items: [] })
expect(r.success).toBe(false)
expect(r.error?.errors[0].message).toBe('Cart is empty')
})
it('accepts multiple items', () => {
const r = checkoutSchema.safeParse({
items: [
{ productId: 'prod-1', quantity: 2 },
{ productId: 'prod-2', quantity: 1 },
],
})
expect(r.success).toBe(true)
})
})
// ─── settingSchema ───────────────────────────────────────────────────────────
describe('settingSchema', () => {
it('accepts valid setting', () => {
expect(settingSchema.safeParse({ key: 'site_name', value: 'My Shop' }).success).toBe(true)
})
it('rejects empty key', () => {
expect(settingSchema.safeParse({ key: '', value: 'anything' }).success).toBe(false)
})
it('accepts any value type', () => {
for (const value of ['string', 42, true, null, { nested: true }]) {
expect(settingSchema.safeParse({ key: 'k', value }).success).toBe(true)
}
})
})
+36
View File
@@ -0,0 +1,36 @@
import { defineConfig } from 'vitest/config'
import path from 'path'
export default defineConfig({
test: {
environment: 'happy-dom',
globals: true,
setupFiles: [path.resolve(__dirname, 'setup.ts')],
include: [
'../test/unit/**/*.{test,spec}.{ts,tsx}',
'../test/integration/**/*.{test,spec}.{ts,tsx}',
'../test/components/**/*.{test,spec}.{ts,tsx}',
],
exclude: ['**/node_modules/**'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
include: ['src/**/*.ts', 'src/**/*.tsx'],
exclude: [
'src/app/layout.tsx',
'src/lib/prisma.ts',
'src/**/*.d.ts',
],
thresholds: { lines: 70, functions: 70 },
},
},
resolve: {
alias: {
'@': path.resolve(__dirname, '../app/src'),
},
},
esbuild: {
jsx: 'automatic',
jsxImportSource: 'react',
},
})