Skip to content

Latest commit

 

History

History
885 lines (521 loc) · 16.7 KB

File metadata and controls

885 lines (521 loc) · 16.7 KB

API Reference

Tavola Romagna REST API — Base URL: /api

All endpoints return JSON. Authenticated endpoints require a valid session_token cookie. Errors follow the shape { error: string }.


Table of Contents


Health & System

GET /api/health

Health check endpoint. Returns service status and integration connectivity.

Auth: None
Response: 200

{
  "status": "healthy",
  "services": {
    "database": { "status": "up", "latencyMs": 5 },
    "stripe": { "status": "up" },
    "email": { "status": "mock" }
  }
}

GET /api/i18n

Returns localized message dictionary for the detected/requested locale.

Auth: None
Query: ?locale=en (optional, defaults to Accept-Language detection)

GET /api/metrics

Platform-wide metrics dashboard data.

Auth: Required


Authentication

POST /api/auth/register

Register a new user account.

Auth: None
Body:

{
  "email": "user@example.com",
  "password": "securepass",
  "name": "Mario Rossi"
}

Response: 201 — Sets session_token cookie

POST /api/auth/login

Authenticate and create a session.

Auth: None
Body:

{
  "email": "user@example.com",
  "password": "securepass"
}

Response: 200 — Sets session_token cookie

POST /api/auth/logout

Destroy the current session.

Auth: Required
Response: 200 — Clears session_token cookie

GET /api/auth/me

Get the current authenticated user.

Auth: Required
Response: 200 — User object with producer relation if applicable

GET /api/auth/profile · PATCH /api/auth/profile

Read or update the user profile.

Auth: Required

POST /api/auth/password-reset

Initiate a password reset flow.

Auth: None
Body: { "email": "user@example.com" }

GET /api/auth/addresses · POST /api/auth/addresses · DELETE /api/auth/addresses

Manage saved delivery addresses.

Auth: Required

GET /api/auth/sessions · DELETE /api/auth/sessions

List active sessions or revoke a session.

Auth: Required

GET /api/auth/mfa · POST /api/auth/mfa

MFA setup and verification.

Auth: Required

POST /api/auth/oauth

OAuth login (Google / Apple).

Auth: None
Body: { "provider": "google", "token": "..." }


Products & Catalog

GET /api/products

List all active products with filtering.

Auth: None
Query: ?category=formaggi&organic=true&featured=true&search=parmigiano

POST /api/products

Create a new product (producer only).

Auth: Required (producer)

GET /api/search

Full-text search across products, producers, recipes.

Auth: None
Query: ?q=search+term&category=vino

GET /api/seasonal

Seasonal product availability calendar.

Auth: None


Producers

GET /api/producers

List all approved producers.

Auth: None

GET /api/producer/onboarding · POST /api/producer/onboarding

Producer registration and Stripe Connect onboarding flow.

Auth: Required
POST Body:

{
  "businessName": "Azienda Agricola Rossi",
  "partitaIva": "IT12345678901",
  "specialty": "formaggi",
  "categories": ["formaggi", "salumi"]
}

Cart

GET /api/cart

Get the current user's cart items.

Auth: Required

POST /api/cart

Add an item to the cart.

Auth: Required
Body: { "productId": "...", "quantity": 2 }

DELETE /api/cart

Remove item(s) or clear the cart.

Auth: Required
Body: { "productId": "..." } or { "clear": true }


Checkout & Orders

POST /api/checkout

Process a checkout. Creates an order, applies coupons/loyalty, triggers Stripe payment.

Auth: Required
Body:

{
  "deliveryAddress": "Via Roma 1",
  "deliveryCity": "Forlì",
  "deliveryPostalCode": "47121",
  "deliverySlot": "2025-01-15 09:00-12:00",
  "couponCode": "WELCOME10",
  "notes": "Citofono Rossi"
}

POST /api/split-checkout

Split checkout — creates separate sub-orders per producer for multi-producer carts.

Auth: Required

GET /api/orders · PATCH /api/orders

List user orders or update order status.

Auth: Required

POST /api/refunds

Request a refund for an order/payment.

Auth: Required
Body: { "paymentIntentId": "pi_...", "amount": 1500, "reason": "requested_by_customer" }


Subscriptions

GET /api/subscriptions · POST /api/subscriptions · PATCH /api/subscriptions

Manage subscription boxes (create, pause, cancel, update preferences).

Auth: Required

GET /api/subscriptions/profile · POST /api/subscriptions/profile

Dietary profile for personalized box composition.

Auth: Required

GET /api/subscriptions/[id]/composition · POST /api/subscriptions/[id]/composition · PATCH /api/subscriptions/[id]/composition

View/manage the composition of an upcoming delivery box.

Auth: Required

POST /api/subscriptions/[id]/satisfaction

Submit satisfaction feedback for a delivered box.

Auth: Required

GET /api/subscriptions/experiments · POST /api/subscriptions/experiments

A/B testing for subscription box variants.

Auth: Required (admin)


Pricing Engine

POST /api/pricing/evaluate

Evaluate dynamic pricing for a product given context (quantity, delivery slot, expiry).

Auth: None
Body:

{
  "productId": "...",
  "quantity": 5,
  "deliverySlotId": "...",
  "daysToExpiry": 2
}

Response:

{
  "unitOriginalPrice": 8.50,
  "unitDynamicPrice": 6.80,
  "originalPrice": 42.50,
  "dynamicPrice": 34.00,
  "savings": 8.50,
  "appliedRules": [
    { "name": "Expiry markdown", "type": "expiry_markdown", "reason": "..." }
  ]
}

GET /api/pricing/rules · POST /api/pricing/rules

List or create pricing rules.

Auth: Required (admin)

PUT /api/pricing/rules/[id] · DELETE /api/pricing/rules/[id]

Update or delete a pricing rule.

Auth: Required (admin)

POST /api/pricing/expiry-scan

Trigger a scan for near-expiry products and apply automatic markdowns.

Auth: Required (admin/cron)


Delivery

GET /api/delivery/timeslots

Available delivery time slots by zone.

Auth: None
Query: ?zone=forli-centro

POST /api/delivery/validate

Validate a delivery address and return the matching zone/fee.

Auth: None
Body: { "city": "Forlì", "postalCode": "47121" }


Surplus / Food Rescue

GET /api/surplus · POST /api/surplus

List active surplus listings or create a new surplus offer (producer).

Auth: Required


Gift Boxes

GET /api/gift-boxes · POST /api/gift-boxes

Browse or create gift box templates.

Auth: Required

GET /api/gift-orders · POST /api/gift-orders

Purchase a gift or list gift orders.

Auth: Required

GET /api/gift-orders/unbox

Unbox a gift using a token.

Auth: None
Query: ?token=unboxing-token-uuid


Events

GET /api/events · POST /api/events

List or create farm events/experiences.

Auth: POST requires auth

GET /api/events/[id] · PUT /api/events/[id]

Get or update an event.

Auth: PUT requires auth

POST /api/events/[id]/book

Book an event.

Auth: Required
Body: { "quantity": 2 }


Recipes

GET /api/recipes · POST /api/recipes

List or create recipes.

Auth: None (POST may require auth)

POST /api/recipes/generate

AI-powered recipe generation from available ingredients.

Auth: None

POST /api/recipes/basket-builder

Build a shopping basket from a recipe's ingredients.

Auth: None
Body: { "recipeId": "...", "servings": 4 }

GET /api/recipes/weekly-menu · POST /api/recipes/weekly-menu

Get or generate a weekly meal plan.

Auth: None


Recommendations

GET /api/recommendations

Get personalized product recommendations.

Auth: Optional (better results when authenticated)
Query: ?productId=...&recipeId=...

Returns sections: also_bought, similar, personal, trending, contextual, recipe_ingredients.


Community & Forum

GET /api/forum/posts · POST /api/forum/posts

List or create forum posts.

Auth: POST requires auth

GET /api/forum/posts/[id]

Get a forum post with comments.

Auth: None

POST /api/forum/posts/[id]/comments

Add a comment.

Auth: Required

POST /api/forum/posts/[id]/like

Like a post.

Auth: Required


Adoptions

GET /api/adoptions/programs · POST /api/adoptions/programs

List or create adoption programs (olive trees, vineyards, etc.).

Auth: POST requires auth

POST /api/adoptions/adopt

Adopt a tree/vine.

Auth: Required


Cooperatives

GET /api/cooperatives · POST /api/cooperatives

List or create cooperatives.

Auth: POST requires auth

GET /api/cooperatives/[id] · PUT /api/cooperatives/[id] · DELETE /api/cooperatives/[id]

CRUD for a single cooperative.

Auth: Required

GET /api/cooperatives/[id]/members · POST /api/cooperatives/[id]/members · DELETE /api/cooperatives/[id]/members

Manage cooperative membership.

Auth: Required


Tourism

GET /api/tourism/itineraries · POST /api/tourism/itineraries

Agri-tourism itinerary management.

Auth: POST requires auth

GET /api/tourism/partners · POST /api/tourism/partners

Hospitality partner management.

Auth: POST requires auth

POST /api/tourism/ship-home

Ship products home (for tourists visiting the region).

Auth: Required


Traceability

GET /api/traceability/[productId]

Full supply chain timeline for a product.

Auth: None

POST /api/traceability/events

Record a supply chain event.

Auth: Required

GET /api/traceability/certifications · POST /api/traceability/certifications

Manage producer certifications (DOP, IGP, Bio).

Auth: Required

GET /api/traceability/verify/[txHash]

Verify a blockchain-anchored traceability hash.

Auth: None


Reviews

GET /api/reviews · POST /api/reviews

List or submit product reviews.

Auth: Required


Notifications

GET /api/notifications · PATCH /api/notifications

List or mark notifications as read.

Auth: Required

GET /api/notifications/preferences · PATCH /api/notifications/preferences

Manage notification channel preferences (email, push, WhatsApp, in-app).

Auth: Required

GET /api/notifications/stream

Server-Sent Events (SSE) stream for real-time notifications.

Auth: Required


Loyalty

GET /api/loyalty · POST /api/loyalty

View loyalty account/points or earn/redeem points.

Auth: Required


Coupons

GET /api/coupons · POST /api/coupons

List or create coupon codes.

Auth: Required (admin)

POST /api/coupons/validate

Validate a coupon code against an order.

Auth: Required
Body: { "code": "WELCOME10", "subtotal": 45.00 }


Search

GET /api/search

Full-text product/producer search.

Auth: None
Query: ?q=piadina&category=pane


Uploads & Storage

GET /api/uploads · POST /api/uploads

Upload images via Vercel Blob or Cloudinary.

Auth: Required
POST: multipart/form-data with file field


GDPR & Privacy

GET /api/gdpr/consent · POST /api/gdpr/consent

Read or record user consent (analytics, marketing, etc.).

Auth: Required

GET /api/gdpr/data-export · POST /api/gdpr/data-export

Request or download a full data export.

Auth: Required

POST /api/gdpr/account-deletion · DELETE /api/gdpr/account-deletion

Request or confirm account deletion.

Auth: Required


Newsletter

POST /api/newsletter

Subscribe to the newsletter.

Auth: None
Body: { "email": "...", "name": "...", "language": "it" }

DELETE /api/newsletter

Unsubscribe.

Auth: None
Body: { "email": "..." }


Admin

All admin endpoints require authentication with an admin role.

Endpoint Methods Purpose
/api/admin/stats GET Aggregated platform statistics
/api/admin/producers GET, PATCH Producer approval/management
/api/admin/applications GET, POST Producer application review
/api/admin/reviews GET, DELETE Review moderation
/api/admin/operations GET, PATCH Operations dashboard
/api/admin/payouts GET, POST Producer payout management
/api/admin/drivers GET, POST Delivery driver management
/api/admin/jobs GET, POST Background job management
/api/admin/metrics GET, POST Platform metrics
/api/admin/support GET, POST Support ticket management
/api/admin/audit GET Security audit log

Producer Analytics

All endpoints require producer authentication.

Endpoint Methods Purpose
/api/producer/analytics GET Dashboard overview
/api/producer/analytics/alerts GET, PATCH Price/stock alerts
/api/producer/analytics/benchmarks GET, POST Category benchmarks
/api/producer/analytics/cohorts GET Customer cohort analysis
/api/producer/analytics/forecast GET Revenue forecasting
/api/producer/analytics/lifecycle GET Product lifecycle stages
/api/producer/analytics/report GET Downloadable reports

Webhooks

POST /api/webhooks/stripe

Stripe webhook receiver. Handles checkout.session.completed, payment_intent.succeeded, invoice.paid, etc.

Auth: Stripe signature verification

GET /api/whatsapp/webhook · POST /api/whatsapp/webhook

WhatsApp Business API webhook verification and message ingestion.

Auth: WhatsApp verification token


Messaging

POST /api/push/subscribe

Register a push notification subscription.

Auth: Required

POST /api/push/send

Send a push notification.

Auth: Required

POST /api/whatsapp/send

Send a WhatsApp message.

Auth: Required


Cron Jobs

Scheduled via Vercel Cron (vercel.json):

Endpoint Schedule Purpose
GET /api/cron/analytics Daily 2:00 AM Compute daily sales, benchmarks, cohorts
GET /api/cron/pricing-scan Every 6 hours Scan for expiry markdowns and price adjustments
GET /api/cron/surplus-scan Daily 8:00 AM Identify new surplus opportunities
GET /api/cron/notification-digest Monday 9:00 AM Send weekly notification digest emails
GET /api/cron/menu-generation On demand Generate weekly menu suggestions

Miscellaneous

GET /api/moonshots

Innovation portfolio / experimental features listing.

Auth: None

GET /api/federation/products

Federated product listing for partner platforms.

Auth: None

POST /api/seed

Seed the database with sample data (development only).

Auth: None

GET /api/inventory · PATCH /api/inventory

Manage product inventory levels.

Auth: Required

POST /api/inventory/watch

Subscribe to stock-back-in notifications.

Auth: Required


Rate Limits

Scope Limit Window
Auth endpoints 5 requests 15 minutes
General API 100 requests 1 minute
Webhooks 50 requests 1 minute
Admin 30 requests 1 minute
Uploads 10 requests 1 minute

Rate limit headers: X-RateLimit-Remaining, X-RateLimit-Reset, Retry-After (on 429).


Error Responses

All errors follow a consistent shape:

{ "error": "Human-readable error message in Italian" }
Status Meaning
400 Validation error
401 Not authenticated
403 Forbidden (wrong role)
404 Resource not found
405 Method not allowed
415 Unsupported content type
429 Rate limited
500 Internal server error