# Required Backend APIs (to retire all mock data)

These endpoints do **not** exist in `Fiesta_All_Endpoints_With_Tables_And_Params.xlsx` and the
values cannot be derived client-side. Each spec gives the **request** (params/body) and the
**exact response JSON** the frontend needs. All responses follow the existing Fiesta envelope:

```json
{ "code": 200, "status": true, "message": "OK", "details": <payload> }
```

`details` is the `<payload>` documented per endpoint. Money is in INR (paise-free rupees,
2-dp numbers). Dates are `YYYY-MM-DD`; timestamps ISO-8601.

Grouped as the request asked: **Overall (executive) analysis**, **Store-wise analysis**,
**Reports**, then supporting operational feeds.

---

## A. OVERALL / EXECUTIVE ANALYSIS

### [R1] Revenue summary — `GET /orders/getrevenuesummary`
Real money totals (today the app fakes revenue as `delivered × 355`).

**Request**
| param | type | required | notes |
|---|---|---|---|
| tenantid | int | ✓ | |
| locationid | int |  | omit = all outlets (overall); set = store-wise |
| fromdate | date | ✓ | |
| todate | date | ✓ | |

**Response `details`** (single object)
```json
{
  "tenantid": 1087,
  "grossrevenue": 1248302.00,
  "netrevenue": 1180500.00,
  "profit": 354216.00,
  "marginpct": 28.4,
  "ordercount": 4921,
  "deliveredcount": 4102,
  "cancelledcount": 142,
  "avgordervalue": 1580.00,
  "prev_grossrevenue": 1090000.00,
  "prev_ordercount": 4370
}
```
`prev_*` = same metric for the immediately preceding equal-length window, so the UI can show
the `+14.2%` deltas without a second call. (If omitted, the frontend will issue a second
range query to derive deltas — see [R2].)

---

### [R2] Orders/revenue time-series — `GET /orders/gettimeseries`
Powers the Reports main chart (Orders / Revenue / Cancelled / SKUs) and the StoreDetail 7-day ledger.

**Request**
| param | type | required | notes |
|---|---|---|---|
| tenantid | int | ✓ | |
| locationid | int |  | omit = overall |
| granularity | enum | ✓ | `day` \| `month` \| `year` |
| fromdate | date | ✓ | |
| todate | date | ✓ | |

**Response `details`** (array, one bucket per period)
```json
[
  { "label": "2026-06-01", "orders": 312, "revenue": 442800.00,
    "cancelled": 9, "delivered": 298, "activeskus": 72 }
]
```
`label` is the bucket key (`YYYY-MM-DD` for day, `YYYY-MM` for month, `YYYY` for year).
This removes all hardcoded `CHART_DATA_YTD` / `getDynamicChartData` arrays **and** the
region-scaling multipliers (filter by `locationid` instead).

---

### [R12] Operational alerts — `GET /alerts/getalerts`
Replaces `operationalAlerts` in `data.ts` (stock-critical, latency, rebalance, etc.).

**Request**: `tenantid` (✓), `locationid` (optional), `status` (`open|all`), `pageno`, `pagesize`.

**Response `details`** (array)
```json
[
  { "alertid": 5012, "tenantid": 1087, "locationid": 1097,
    "type": "critical",            // critical | warning | info
    "title": "Stock Critical: RS Puram",
    "details": "Dairy inventory below 5%.",
    "createdat": "2026-06-06T08:24:00",
    "acknowledged": false }
]
```

---

## B. STORE-WISE ANALYSIS

### [R3] Product sales analytics — `GET /products/getproductanalytics`
The stock-statement mapper currently approximates `unitsSold = debit` and
`revenue = debit × retailprice`. This returns true sales + the product meta the matrix shows.

**Request**
| param | type | required | notes |
|---|---|---|---|
| tenantid | int | ✓ | |
| locationid | int |  | omit = across all outlets |
| subcategoryid | int |  | |
| fromdate / todate | date |  | sales window (default month-to-date) |
| keyword | string |  | |
| pageno / pagesize | int |  | |

**Response `details`** (array)
```json
[
  { "productid": 88231, "productname": "Ponni Raw Rice 10kg",
    "sku": "PONNI-RICE-10K", "categoryid": 2, "subcategoryname": "Rice",
    "image": "https://…",
    "unitssold": 12402, "revenue": 868140.00, "trend": "up",   // up|flat|down
    "closingstock": 1402, "maxcapacity": 2000, "binlocation": "BIN-C12",
    "lastauditdate": "2026-06-05", "verified": true,
    "outlets": [ { "locationid": 1097, "locationname": "RS Puram", "stock": 840 } ] }
]
```
`outlets[]` gives the real per-hub split (replaces the hardcoded 60/40). `binlocation`,
`lastauditdate`, `image` replace the fabricated bin/barcode/audit fields — **drop them if the
catalog doesn't track them** rather than faking.

---

### [R10] Intraday dispatch buckets — `GET /deliveries/getdispatchbuckets`
Replaces StoreDetail `intervalSlots` (Morning Rush / Midday / Evening Peak, computed from `%`).

**Request**: `tenantid` (✓), `locationid` (✓), `date` (✓, default today).

**Response `details`** (array, fixed buckets)
```json
[
  { "bucket": "06:00-10:00", "label": "Morning Rush",
    "orders": 64, "revenue": 88400.00, "status": "PEAK" }   // PEAK|HIGH|NORMAL|LOW
]
```

---

### [R11] Customer analytics — `GET /customers/getcustomeranalytics`
Replaces hardcoded CSAT 5.0 / retention 88.4% / AOV ₹1,580 in StoreDetail.

**Request**: `tenantid` (✓), `locationid` (optional), `customerid` (optional — single-customer rollup).

**Response `details`** (object; per-customer when `customerid` set)
```json
{
  "retentionpct": 88.4,
  "avgordervalue": 1580.00,
  "csat": 4.9,
  "totalcustomers": 1240,
  "percustomer": { "customerid": 55012, "orderscount": 18,
                   "totalspent": 28450.00, "csat": 5.0, "lastorderdate": "2026-06-04" }
}
```
> Customer order **history** itself is already available: `GET /orders/getorders?customerid=` (sheet row 56) — wire that, no new API needed.

---

### [R9] Rider telemetry — `GET /partners/getridertelemetry`
Replaces hardcoded rider `rating 4.7`, `battery`, `lastPing`, and the fake GPS route / "9 MINS" / "1.2 km left".

**Request**: `applocationid` (✓), `tenantid` (optional), `userid` (optional — single rider).

**Response `details`** (array)
```json
[
  { "userid": 7781, "name": "Karthikeyan R", "status": "Delivering",  // Delivering|Idle|Offline
    "rating": 4.7, "completedtoday": 12, "battery": 84,
    "lastping": "2026-06-06T14:21:00", "zone": "RS Puram",
    "lat": 11.0041, "lng": 76.9612,
    "activedelivery": { "deliveryid": 99213, "etamins": 9, "distancekm": 1.2,
                        "destlat": 11.0102, "destlng": 76.9550 } }
]
```

---

## C. REPORTS

Reports are powered primarily by **[R1]** (revenue + deltas), **[R2]** (time-series chart &
ledger), and **[R3]** (product matrix). Additional reports-only needs:

### [R4] Import / sync audit log — `GET /imports/getimportlogs` + validation
Replaces `initialImportLogs` and the hardcoded "14 duplicate SKUs" validator messages.

**Request (list)**: `tenantid` (✓), `pageno`, `pagesize`.
**Response `details`**
```json
[
  { "importid": 921, "batchref": "#IMP_0921_A", "type": "Inventory Sync",
    "source": "ERP Export", "rows": 421, "result": "SUCCESS",   // SUCCESS|FAILED|PARTIAL
    "message": "421 rows", "createdat": "2026-05-31T09:12:00" }
]
```
**Upload (optional)**: `POST /imports/upload` (multipart csv) → returns the same row plus a
`validation` block:
```json
{ "validation": { "passed": true, "duplicateskus": ["ST-SONA-25K"],
                  "badcolumns": [45, 82], "headerversion": "v2.8" } }
```

### [R13] Scheduled reports — `GET/POST /reports/getschedules` *(optional feature)*
Replaces the 3 hardcoded calendar events. Drop the feature if not on the roadmap.
```json
[ { "scheduleid": 11, "name": "Monthly Assortment Audit", "cron": "0 0 1 * *",
    "nextrun": "2026-07-01T00:00:00", "format": "PDF", "recipients": ["ops@…"] } ]
```

---

## D. SETTINGS / CONFIG

### [R6] Merchant settings + branding — `GET /tenants/getsettings`, `PUT /tenants/updatesettings`
Replaces `DEFAULTS` (localStorage) and the Brand Design Studio local state. Some fields already
live on the tenant (`minorder`, `paymenttype`) — fold those in.

**GET response `details`**
```json
{
  "tenantid": 1087,
  "contactemail": "ops@ragul.com", "contactphone": "+91…",
  "minordervalue": 199, "deliverycharge": 29, "prepmins": 20,
  "deliverywindowmins": 45, "cancelwindowsecs": 120, "autoassignrider": true,
  "defaulttaxpercent": 5, "codenabled": true, "onlinepaymentenabled": true,
  "defaultregion": "Coimbatore", "defaultnewuserrole": 4,
  "ordernotifications": true, "lowstockalerts": true, "dailysummaryemail": false,
  "syncinterval": 15, "sandboxmode": false,
  "branding": { "themename": "Kaveri Org", "primarycolor": "#16a34a",
                "secondarycolor": "#f59e0b", "baglabel": "Freshly Harvested",
                "ecoverified": true, "stickerpattern": "radial" }
}
```
**PUT body**: same object (partial allowed) → returns updated object.

---

## E. SUPPORTING OPERATIONAL ENDPOINTS (optional / phase-2)

### [R7] Forecast / efficiency insight — `GET /insights/getforecast`
Operations "Forecast Efficiency 92% / ₹1.9L savings". **Recommend removing** these tiles until a
forecasting model exists, rather than building a thin API. If kept:
```json
{ "forecastefficiencypct": 92, "estsavingsperweek": 190000.00, "horizondays": 7 }
```

### [R8] Stock transfer — `POST /products/stocktransfer`
Operations transfer-stock modal.
**Body**: `{ tenantid, productid, fromlocationid, tolocationid, quantity }` →
**Response**: updated stock rows for both locations.

### [R5] Catalog presets — `GET /products/getcatalogpresets` *(optional)*
Inventory "Nilgiris Dairy / Coimbatore Heritage" quick-add packs. Could instead reuse master
catalog listings (sheet row 90) filtered by subcategory — **prefer that, skip the new API**.

---

## Mutation routes already in the sheet (confirm shape, then wire)
These are marked `REVIEW_REQUIRED` in the sheet — backend must publish request/response:
| Action | Route (sheet) | Used by |
|---|---|---|
| Create web order | POST orders+orderdetails | Orders "create order" |
| Update order status | PUT orders | Orders status buttons |
| Assign rider / dispatch | POST deliveries+deliverydetails | Orders assign-rider |
| Update pickup / delivered | PUT deliveries | Orders status progression |
| Add multi-product stock | POST (products) | Inventory/Operations add stock |
| Create/Update/Delete product | POST/PUT/DELETE | Catalogue management |
| Onboard tenant / store / location | POST/PUT | App add-store modal |
