85 lines
8.5 KiB
Markdown
85 lines
8.5 KiB
Markdown
# Marketplace — Flutter integration
|
||
|
||
Base URL: `{{baseUrl}}`, with `baseUrl = http://localhost:4000/api/v1` in the shared environment. Use `Authorization: Bearer {{accessToken}}` for cart, checkout and orders. Product/shop reads are public.
|
||
|
||
Import `Oudelaa-Marketplace-Flutter.postman_collection.json`. Each request contains saved response examples captured from HTTP integration tests against the real controllers, services and an isolated MongoDB replica set. Authentication was replaced with a test guard; all customers, products and addresses are synthetic. The images use example.com placeholders. These are **not production responses**. Raw captures are in `marketplace-response-examples.json`.
|
||
|
||
Responses below are unwrapped (the default). When `RESPONSE_ENVELOPE_ENABLED=true`, unwrap `data` from `{ "data": ..., "meta": { "statusCode": 200, "timestamp": "..." } }` before deserializing. POST returns 201; GET/PATCH/DELETE return 200.
|
||
|
||
## Endpoints
|
||
|
||
| Method | Path | Request / result |
|
||
|---|---|---|
|
||
| GET | `/marketplace/listings?shopId={shopId}` | Paginated products belonging to a shop; existing search/category/price filters remain available. |
|
||
| GET | `/marketplace/shops/{shopId}/listings` | Same paginated result; validates that the shop exists and is active. |
|
||
| GET | `/marketplace/listings/{listingId}` | Product details including stock, shop and policies. |
|
||
| GET | `/marketplace/shops/{shopId}` | Shop details. `shopId` is the owner's admin user ID, not a repair-shop ID. |
|
||
| GET | `/marketplace/cart` | `{items, itemCount, quantity}`; `quantity` is the sum of quantities. |
|
||
| POST | `/marketplace/cart/items` | `{listingId, quantity}`; sets the absolute quantity for this product, including when it already exists. Returns the cart. |
|
||
| PATCH | `/marketplace/cart/items/{itemId}` | `{quantity}`; returns the cart. Use the cart line's `id`, not `listingId`. |
|
||
| DELETE | `/marketplace/cart/items/{itemId}` | Returns the remaining cart. |
|
||
| DELETE | `/marketplace/cart` | Returns the current cart, normally `{items: [], itemCount: 0, quantity: 0}`. |
|
||
| POST | `/marketplace/checkout/preview` | `{items: [{listingId, quantity}], fulfillmentMethod: "delivery" or "pickup"}`. |
|
||
| POST | `/marketplace/orders` | Checkout items plus the customer and fulfillment fields shown below. Returns the order. |
|
||
| GET | `/marketplace/orders` | Current customer's paginated orders; `page`, `limit`, `status`, `q` (order number). |
|
||
| GET | `/marketplace/orders/{orderId}` | Current customer's order, otherwise 404. |
|
||
| POST | `/marketplace/orders/{orderId}/cancel` | Optional `{reason}`. Allowed while `pending` or `confirmed`. Returns the cancelled order. |
|
||
|
||
Pagination uses the existing `{items, count, page, limit, total, totalPages, nextCursor, pagination}` format. These endpoints use offset pagination; `nextCursor` is null.
|
||
|
||
## Checkout and order contract
|
||
|
||
```json
|
||
{
|
||
"items": [{ "listingId": "REPLACE_WITH_LISTING_ID", "quantity": 2 }],
|
||
"customerName": "Customer Name",
|
||
"customerPhone": "+966500000000",
|
||
"fulfillmentMethod": "delivery",
|
||
"city": "Riyadh",
|
||
"address": "Street and building",
|
||
"latitude": 24.7136,
|
||
"longitude": 46.6753,
|
||
"paymentMethod": "cash_on_delivery",
|
||
"notes": "Call before arrival"
|
||
}
|
||
```
|
||
|
||
- A checkout/order contains 1–50 distinct products, each with an integer quantity of 1–100, from **one shop and one currency**. Split purchases across shops/currencies into separate orders in Flutter. The cart can hold items from multiple shops/currencies; it intentionally has no misleading combined monetary total.
|
||
- Send items explicitly to preview and create. The server reads the current price and stock; it never accepts a client total or delivery fee. Duplicate product lines are rejected.
|
||
- Delivery requires city, address, latitude and longitude. For pickup these fields can be omitted; if coordinates are supplied, both are required.
|
||
- Preview returns `items`, `shopId`, `subtotal`, `deliveryFee`, `discount`, `total`, `currency`, `fulfillmentMethod`, `isValid`, and `stockIssues`. Each line includes requested `quantity`, `stockQuantity`, and `isInStock` (enough stock for that requested quantity).
|
||
- Insufficient stock produces a preview with `isValid: false` and `stockIssues: [{listingId, requestedQuantity, stockQuantity}]`. Unavailable/deleted products or a disabled shop return 400. Creating an order with insufficient stock returns 409. Preview does not reserve stock.
|
||
- Delivery costs the shop's configured flat `shopDeliveryFee` **once per order**, in the order currency; pickup costs zero. Delivery is unavailable until the shop enables it. Discounts are currently zero; there is no coupon system or additional tax calculation.
|
||
- Successful order creation reserves stock and stores price/product snapshots. MongoDB transactions prevent partial reservations and overselling. Cancellation restores all quantities atomically. A repeated or disallowed cancellation returns 409 without restoring stock again.
|
||
- Creating an order does not clear the cart. After success, Flutter can remove the purchased lines or clear the cart explicitly. POST orders is not idempotent: disable repeated submission and do not blindly retry after an ambiguous timeout; refresh the customer's orders first.
|
||
- Order states: `pending`, `confirmed`, `processing`, `ready`, `completed`, `cancelled`. Seller status management continues under `/orders/admin` and handles all lines of a marketplace order.
|
||
- `paymentMethod` currently accepts only `cash_on_delivery` (cash at delivery or pickup); `paymentStatus` is `unpaid`. Online payments and webhook endpoints are deferred at the owner's request; do not call `/marketplace/payments/*` yet. No payment provider is configured.
|
||
|
||
## Product and shop models
|
||
|
||
Product details include `id`, `itemType` (the listing category), `name` (alias of `title`), `description`, `price`, `currency`, `imageUrls`, `condition` (`new`, `like_new`, `used`, `refurbished`), `listingCategory`, `instrumentType`, `stockQuantity`, `isInStock`, `shopId`, `shop`, `deliveryAvailable`, `deliveryFee`, `trialPolicy`, and `returnPolicy`. Existing `_id`, `title`, `quantity`, and other fields remain for compatibility. `imageUrls` contains all stored images.
|
||
|
||
`shop` contains `id`, `shopId`, `name`, `description`, `logoUrl`, `coverUrl`, `imageUrls`, `phone`, `address`, `latitude`, `longitude`, `isVerified`, `deliveryAvailable`, `deliveryFee`, `trialPolicy`, `returnPolicy`, and `policies`. Standalone shop responses also keep the existing `adminId` and `shop*` fields. Latitude/longitude can be null; missing text/policies are empty strings. No return or trial promise is invented for an unconfigured store.
|
||
|
||
The existing shop-profile PATCH routes now accept `shopPhone`, `shopLogoUrl`, `shopCoverUrl`, `shopDeliveryAvailable`, `shopDeliveryFee`, `shopTrialPolicy`, `shopReturnPolicy`, `shopPolicies` alongside their existing fields. Logo/cover fall back to the first/second shop images. Verification comes from the existing admin-controlled `isVerified` state.
|
||
|
||
Cart rows for unavailable/deleted products remain removable and return `isAvailable: false`, `isInStock: false`, `stockQuantity: 0`, and nullable display/price fields. Cart additions do not reserve stock. Refresh/preview before checkout.
|
||
|
||
## Errors and deployment
|
||
|
||
Validation returns 400 (invalid IDs, quantities, duplicate items, unknown fields, missing delivery details, unsupported payment method). Missing cart/order resources return 404; protected routes require authentication (401). Stock conflicts and disallowed cancellation return 409. Use `message` for display and handle both string and string-array validation messages.
|
||
|
||
Order creation and cancellation require **MongoDB replica set or sharded deployment**, including local development. Standalone MongoDB does not support these transactions. Existing shop records do not need a migration: new fields have defaults, and merchants must configure phone, delivery and policies before enabling those features.
|
||
|
||
Run the isolated integration tests on Windows:
|
||
|
||
```powershell
|
||
$env:MARKETPLACE_INTEGRATION='1'
|
||
$env:MONGOD_BINARY='C:\Program Files\MongoDB\Server\8.2\bin\mongod.exe'
|
||
$env:MARKETPLACE_CAPTURE_EXAMPLES='1'
|
||
npx.cmd jest --runInBand --config test/jest-e2e.json --runTestsByPath test/marketplace-commerce.e2e-spec.ts
|
||
node scripts/build-marketplace-postman.js
|
||
```
|
||
|
||
The test starts and stops its own local mongod instance on an available port and leaves its diagnostic files in a unique OS temporary directory. It never reads application database credentials or connects to the application's database. Do not use the synthetic IDs in captures against production; set the collection variables from your own API responses.
|