{
  "openapi": "3.0.3",
  "info": {
    "title": "Fieldproof Partner API",
    "version": "1.0.0",
    "description": "Field collections as an API for regulated lenders. Push overdue cases, read case status, poll the change feed, confirm gateway payments, manage webhook deliveries and read your billing statements and GST invoices.\n\n**Hosts** — Sandbox `https://alpha-gig.fluxusforge.in` (accepts `pk_<org>_test_…` keys only) · Production `https://gig.fluxusforge.in` (`pk_<org>_live_…` keys only). The legacy hosts `alpha-gig.quikkred.in` / `gig.quikkred.in` remain valid with the same keys. All paths below are relative to the host and start with `/api/v1/partner`.\n\n**Authentication** — every request carries `Authorization: Bearer <apiKeyId>` plus `X-Fieldproof-Timestamp` (unix ms) and `X-Fieldproof-Signature` (lowercase-hex HMAC-SHA256 of `METHOD\\nPATH\\nTIMESTAMP\\nRAW_BODY`). The `apiKeyId` security scheme below spells out the exact rules; `POST /api/v1/partner/debug/echo-signature` on the sandbox shows you the server-side canonical string.\n\n**Order of checks** — (1) header presence: a missing `Authorization: Bearer`, `X-Fieldproof-Timestamp` or `X-Fieldproof-Signature` header is `401 UNAUTHORIZED`; (2) a body sent with a `Content-Type` other than `application/json` is `415 UNSUPPORTED_MEDIA_TYPE`; (3) the body is parsed — too large is `413 PAYLOAD_TOO_LARGE`, malformed JSON is `422 VALIDATION_FAILED` (message only, no `details`); (4) the key and the HMAC signature are verified (`401 UNAUTHORIZED` / `SIGNATURE_INVALID` / `TIMESTAMP_SKEW`, `403 LENDER_INACTIVE`, `429 AUTH_LOCKED`); (5) the 60 requests/min per-key limit (`429 RATE_LIMITED`); (6) schema validation (`422 VALIDATION_FAILED` with `details[]`). So a 413, a 415 or a malformed-JSON 422 can come back before your signature is checked; a schema `VALIDATION_FAILED` never does.\n\n**Conventions** — request bodies are `application/json` (only those raw bytes are signed); unknown fields in a request body are silently dropped, not rejected. All money values are whole INR rupees (never paise; the server rounds to integers). Successful responses are flat objects with `success: true` — there is no `{ success, data }` envelope (`GET /api/v1/partner/health` has no `success` field at all, and the invoice PDF is `application/pdf`). Every 4xx/5xx uses the `Error` envelope `{ success:false, error:{ code, message, … } }`. Every response from a defined route carries an `X-Request-Id` header — quote it when writing to partners@fluxusforge.in. (A path that does not exist gets the framework's plain `404` body — no `Error` envelope and no `X-Request-Id`.)\n\n**Rate limits** — 60 requests/min per API key (`429 RATE_LIMITED` with `Retry-After`); `POST /api/v1/partner/cases` is additionally limited to 10 batches/hour per key, and dry runs and idempotent replays count toward that 10.\n\n**Events** — case events reach you on your registered HTTPS webhook (see the *Webhooks* section) and, identically, through `GET /api/v1/partner/cases/updates`. Fieldproof does not send alerts to your technical contact; monitor `GET /api/v1/partner/health` and `GET /api/v1/partner/webhooks/deliveries`.\n\nMoney never routes through Fieldproof — collections land directly on your own payment rails (static UPI QR / bank details, or your own payment-link gateway) and field partners never accept cash on external-org cases (a payment Fieldproof's collection team records for you, cash included, arrives as `payment.collected`, with mode `other` when its mode is not in the list).\n\n**Canonical spec** — this document, published at https://developers.fluxusforge.in/openapi/partner-v1.json, is the canonical contract: generate clients from it. `GET /api/v1/partner/openapi.json` on the API returns only a machine listing of the live routes (generic response schemas, no error codes, no auth header parameters).\n\nGuides: https://developers.fluxusforge.in · Support: partners@fluxusforge.in",
    "contact": {
      "name": "Fieldproof Integration Support",
      "url": "https://developers.fluxusforge.in",
      "email": "partners@fluxusforge.in"
    },
    "license": {
      "name": "Proprietary — Fluxus Forge"
    }
  },
  "servers": [
    {
      "url": "https://alpha-gig.fluxusforge.in",
      "description": "Sandbox — accepts TEST keys (pk_<org>_test_…) only. Try-it console targets this host."
    },
    {
      "url": "https://gig.fluxusforge.in",
      "description": "Production — accepts LIVE keys (pk_<org>_live_…) only. Not browser-callable (no CORS)."
    },
    {
      "url": "https://alpha-gig.quikkred.in",
      "description": "Sandbox — legacy Quikkred host, still valid with the same test keys."
    },
    {
      "url": "https://gig.quikkred.in",
      "description": "Production — legacy Quikkred host, still valid with the same live keys."
    }
  ],
  "security": [
    {
      "apiKeyId": []
    }
  ],
  "tags": [
    {
      "name": "Health",
      "description": "Credential smoke test and reachability check."
    },
    {
      "name": "Cases",
      "description": "Push your overdue book, read case status, poll the change feed and recall cases."
    },
    {
      "name": "Payments",
      "description": "org_gateway organisations confirm captures made on their own payment gateway. Static-QR organisations build nothing here — Fieldproof ops verify the partner's proof and `payment.collected` fires."
    },
    {
      "name": "Webhooks",
      "description": "Self-serve webhook tooling (test ping, delivery log, replay) plus the outbound delivery contract for events Fieldproof POSTs to your callback URL."
    },
    {
      "name": "Billing",
      "description": "Read-only billing: your finalized monthly statements and their GST tax invoices (JSON or PDF). Only what you are charged — Fieldproof's internal cost and margin figures are never included."
    },
    {
      "name": "Sandbox tools",
      "description": "Available only on the sandbox host with test keys."
    },
    {
      "name": "Reference",
      "description": "A machine listing of the live routes, served by the API itself. The canonical spec for client generation is this published document."
    }
  ],
  "paths": {
    "/api/v1/partner/health": {
      "get": {
        "operationId": "getHealth",
        "tags": [
          "Health"
        ],
        "summary": "Credential smoke test",
        "description": "Confirms your key, signature and clock are accepted, and returns the organisation code your key is bound to, the key environment (`test` on the sandbox host, `live` on production) and the server time. Make this the first call of every integration and re-run it whenever you see `TIMESTAMP_SKEW` (compare `serverTime` with your clock).\n\nThe response is a flat object — no `success` field, no `{ success, data }` envelope. Fieldproof does not send alerts to your technical contact; monitor reachability with this endpoint and delivery health with `GET /api/v1/partner/webhooks/deliveries`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "Credentials accepted.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthResponse"
                },
                "example": {
                  "ok": true,
                  "lenderCode": "YOURORG",
                  "env": "test",
                  "serverTime": "2026-08-18T10:00:00.000Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/openapi.json": {
      "get": {
        "operationId": "getOpenApiSpec",
        "tags": [
          "Reference"
        ],
        "summary": "Live route listing (not the canonical spec)",
        "description": "Returns an OpenAPI 3 document generated from the live server's route table, filtered to `/api/v1/partner/*`. It is a **machine listing of routes only**: response schemas are generic, error codes and examples are absent, and the `X-Fieldproof-Timestamp` / `X-Fieldproof-Signature` header parameters are not listed. Generate clients from the canonical spec published at https://developers.fluxusforge.in/openapi/partner-v1.json (this document); use the live listing only to see which routes a host exposes.\n\nIt is a signed request like every other endpoint (`Authorization: Bearer <apiKeyId>` + `X-Fieldproof-Timestamp` + `X-Fieldproof-Signature` over `GET\\n/api/v1/partner/openapi.json\\n<timestamp>\\n`); there are no unauthenticated endpoints. If the published spec and the live API's behaviour disagree, please tell partners@fluxusforge.in.",
        "parameters": [
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "An OpenAPI 3 route listing (JSON) — generic schemas, no error codes.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "additionalProperties": true,
                  "description": "An OpenAPI 3.x document (`openapi`, `info`, `servers`, `paths`, `components`, `security`) listing the live `/api/v1/partner/*` routes."
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/cases": {
      "post": {
        "operationId": "pushCases",
        "tags": [
          "Cases"
        ],
        "summary": "Push cases (create or update)",
        "description": "Push a batch of overdue loans to be worked in the field. Rows are validated and applied **individually** — a bad row is reported in `errors[]` (capped at 50; `summary.errored` is the true count) and never fails the batch. Rows that imported but need your attention are listed in `warnings[]` (same item shape, one entry per warning — a row can have several — capped at 50; `summary.warned` is the number of ROWS with at least one warning) — those rows WERE imported. Only envelope-level problems fail the whole request (`422 VALIDATION_FAILED`, `413 TOO_MANY_ROWS`).\n\n**Address contract** — every row must carry the borrower's address (`borrower.address.line1` or `full`, `city`, `state`, `pincode`) AND the real `latitude` / `longitude` of that address: WGS84 decimal degrees with at least 4 decimal places (send them as strings to keep trailing zeros), inside India, not `0,0`, and one pin may not be reused across different pincodes in a batch — each violation is a per-row error. A pin more than 50 km from Fieldproof's reference point for the pincode is imported with a warning. Your coordinates become the case pin at once (partner matching, check-in geofence, distance-based partner pay) and are never overwritten by Fieldproof's geocoding. Full rules: `RowAddress`.\n\n**What happens per row** — a new `sourceLoanNumber` opens a case (`summary.created`, emits `case.received`). A row for an existing ACTIVE case updates it in place (`updatedSnapshot`): omitted `loan.dpd` / `loan.lateCharges` reset to 0, other optional fields are preserved when omitted, nothing can be cleared to `null`. A row identical to the current snapshot is `unchanged`. If the loan's previous case is closed (`collected` / `closed_unrecovered`), the re-push opens a FRESH case with a new `caseId` and event `sequence` restarting at 1. If the same `sourceLoanNumber` appears twice in one batch, the first row is kept and the later duplicate is a per-row error.\n\n**Idempotency** — (1) the content-hash of a COMMITTED batch is remembered: an identical re-send is a no-op returning `idempotentReplay: true` with the original summary — UNLESS any `sourceLoanNumber` in it (rejected rows included) has no live case (its case was collected / closed / recalled, or its row was rejected so no case was ever created): then the batch is processed normally and closed loans get a FRESH case. Your coordinate grace period is part of the batch identity: a batch committed under strict address rules and re-sent unchanged after a grace period starts is processed again. (2) Optionally send an `Idempotency-Key` header (24 h, per org, only 200s cached, ignored on dry runs): a replay returns the ORIGINAL body verbatim with `X-Idempotent-Replay: true`, without comparing payloads.\n\n**Dry run** — `?dryRun=1` validates every row exactly as a real push would (per-row errors, unparseable dpd/dates, duplicates) but writes nothing and emits nothing.\n\n**Full snapshot** — `fullSnapshot: true` asserts this ONE batch is your complete open book; active cases whose loan is absent from it are flagged for ops review (`snapshot_dropped`) — a loan present on a row rejected for a data error still counts as present — and you get only the count in `summary.flaggedNeedsReview`. Never chunk a full snapshot; use it daily/weekly, not for incremental pushes.\n\n**Limits** — 1 – 20,000 rows per batch (keep ≤ 5,000 for fast responses); 10 batches/hour per API key on top of the global 60 requests/min — dry runs and idempotent replays both count toward the 10.",
        "parameters": [
          {
            "$ref": "#/components/parameters/DryRun"
          },
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PushRequest"
              },
              "examples": {
                "typical": {
                  "summary": "Two rows (full and minimal)",
                  "value": {
                    "fullSnapshot": false,
                    "rows": [
                      {
                        "sourceLoanNumber": "LN-2026-000123",
                        "borrower": {
                          "name": "Ravi Sharma",
                          "phone": "9876543210",
                          "email": "ravi.sharma@example.com",
                          "language": "hi",
                          "employerName": "Acme Textiles Pvt Ltd",
                          "address": {
                            "line1": "12 MG Road",
                            "line2": "Near Trinity Metro",
                            "landmark": "Opp. Garuda Mall",
                            "city": "Bengaluru",
                            "state": "Karnataka",
                            "pincode": "560001",
                            "latitude": "12.975326",
                            "longitude": "77.606262"
                          }
                        },
                        "loan": {
                          "outstandingAmount": 18500,
                          "dpd": 45,
                          "loanAmount": 50000,
                          "disbursedAmount": 48500,
                          "emiAmount": 4500,
                          "lateCharges": 500,
                          "interestRate": 24,
                          "tenure": 12,
                          "tenureUnit": "months",
                          "totalRepayable": 54000,
                          "totalCollected": 35500,
                          "productName": "Personal Loan",
                          "nextDueDate": "2026-08-05",
                          "disbursedDate": "2025-09-01"
                        }
                      },
                      {
                        "sourceLoanNumber": "LN-2026-000124",
                        "borrower": {
                          "name": "Priya Nair",
                          "phone": "9123456789",
                          "address": {
                            "line1": "Flat 4B, Sea View Apartments",
                            "city": "Kochi",
                            "state": "Kerala",
                            "pincode": "682001",
                            "latitude": "9.965389",
                            "longitude": "76.242083"
                          }
                        },
                        "loan": {
                          "outstandingAmount": 8200,
                          "dpd": "61-90"
                        }
                      }
                    ]
                  }
                },
                "fullSnapshot": {
                  "summary": "Daily full-book snapshot",
                  "value": {
                    "fullSnapshot": true,
                    "rows": [
                      {
                        "sourceLoanNumber": "LN-2026-000123",
                        "borrower": {
                          "name": "Ravi Sharma",
                          "phone": "9876543210",
                          "email": "ravi.sharma@example.com",
                          "language": "hi",
                          "employerName": "Acme Textiles Pvt Ltd",
                          "address": {
                            "line1": "12 MG Road",
                            "line2": "Near Trinity Metro",
                            "landmark": "Opp. Garuda Mall",
                            "city": "Bengaluru",
                            "state": "Karnataka",
                            "pincode": "560001",
                            "latitude": "12.975326",
                            "longitude": "77.606262"
                          }
                        },
                        "loan": {
                          "outstandingAmount": 18500,
                          "dpd": 45,
                          "loanAmount": 50000,
                          "disbursedAmount": 48500,
                          "emiAmount": 4500,
                          "lateCharges": 500,
                          "interestRate": 24,
                          "tenure": 12,
                          "tenureUnit": "months",
                          "totalRepayable": 54000,
                          "totalCollected": 35500,
                          "productName": "Personal Loan",
                          "nextDueDate": "2026-08-05",
                          "disbursedDate": "2025-09-01"
                        }
                      },
                      {
                        "sourceLoanNumber": "LN-2026-000124",
                        "borrower": {
                          "name": "Priya Nair",
                          "phone": "9123456789",
                          "address": {
                            "line1": "Flat 4B, Sea View Apartments",
                            "city": "Kochi",
                            "state": "Kerala",
                            "pincode": "682001",
                            "latitude": "9.965389",
                            "longitude": "76.242083"
                          }
                        },
                        "loan": {
                          "outstandingAmount": 8200,
                          "dpd": "61-90"
                        }
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Batch processed (or validated, on a dry run). Check `summary`, `errors[]` and `warnings[]` — a 200 does NOT mean every row was accepted. Rows in `warnings[]` were imported (on a dry run: would be).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              },
              "X-Idempotent-Replay": {
                "$ref": "#/components/headers/XIdempotentReplay"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PushResponse"
                },
                "examples": {
                  "committed": {
                    "summary": "Committed batch — one row rejected (address), one imported with a warning",
                    "value": {
                      "success": true,
                      "dryRun": false,
                      "batchId": "66c1f0a2b3c4d5e6f7a8b9c0",
                      "idempotentReplay": false,
                      "summary": {
                        "totalRowsInCsv": 4,
                        "validRows": 3,
                        "created": 2,
                        "updatedSnapshot": 1,
                        "unchanged": 0,
                        "flaggedNeedsReview": 0,
                        "errored": 1,
                        "warned": 1
                      },
                      "errors": [
                        {
                          "index": 2,
                          "sourceLoanNumber": "LN-2026-000125",
                          "reason": "Row 2 (LN-2026-000125): borrower.address.latitude/longitude need at least 4 decimal places (≈11 m) — got 12.97, 77.6. Send the coordinates of the door, not a rounded or city-level point"
                        }
                      ],
                      "warnings": [
                        {
                          "index": 3,
                          "sourceLoanNumber": "LN-2026-000126",
                          "reason": "Row 3 (LN-2026-000126): borrower.address.latitude/longitude are about 62 km from our reference point for pincode 560001 — imported, but please verify they are this borrower's address"
                        }
                      ]
                    }
                  },
                  "dryRun": {
                    "summary": "Dry run",
                    "value": {
                      "success": true,
                      "dryRun": true,
                      "batchId": "66c1f0a2b3c4d5e6f7a8b9c0",
                      "idempotentReplay": false,
                      "summary": {
                        "totalRowsInCsv": 4,
                        "validRows": 3,
                        "created": 2,
                        "updatedSnapshot": 1,
                        "unchanged": 0,
                        "flaggedNeedsReview": 0,
                        "errored": 1,
                        "warned": 1
                      },
                      "errors": [
                        {
                          "index": 2,
                          "sourceLoanNumber": "LN-2026-000125",
                          "reason": "Row 2 (LN-2026-000125): borrower.address.latitude/longitude need at least 4 decimal places (≈11 m) — got 12.97, 77.6. Send the coordinates of the door, not a rounded or city-level point"
                        }
                      ],
                      "warnings": [
                        {
                          "index": 3,
                          "sourceLoanNumber": "LN-2026-000126",
                          "reason": "Row 3 (LN-2026-000126): borrower.address.latitude/longitude are about 62 km from our reference point for pincode 560001 — imported, but please verify they are this borrower's address"
                        }
                      ]
                    }
                  },
                  "contentHashReplay": {
                    "summary": "Identical batch re-sent (content-hash no-op — every loan in it has a live case)",
                    "value": {
                      "success": true,
                      "dryRun": false,
                      "batchId": "66c1f0a2b3c4d5e6f7a8b9c0",
                      "idempotentReplay": true,
                      "summary": {
                        "totalRowsInCsv": 3,
                        "validRows": 3,
                        "created": 2,
                        "updatedSnapshot": 1,
                        "unchanged": 0,
                        "flaggedNeedsReview": 0,
                        "errored": 0,
                        "warned": 1
                      },
                      "errors": [],
                      "warnings": [
                        {
                          "index": 2,
                          "sourceLoanNumber": "LN-2026-000126",
                          "reason": "Row 2 (LN-2026-000126): borrower.address.latitude/longitude are about 62 km from our reference point for pincode 560001 — imported, but please verify they are this borrower's address"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`LENDER_INACTIVE` — your organisation is suspended. `UNKNOWN_LENDER` — your organisation is not yet provisioned for ingestion; contact partners@fluxusforge.in.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "LENDER_INACTIVE": {
                    "summary": "Organisation suspended",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "LENDER_INACTIVE",
                        "message": "organisation is inactive"
                      }
                    }
                  },
                  "UNKNOWN_LENDER": {
                    "summary": "Organisation not provisioned",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "UNKNOWN_LENDER",
                        "message": "No LenderBranding row for \"YOURORG\"."
                      }
                    }
                  }
                }
              }
            }
          },
          "413": {
            "description": "`TOO_MANY_ROWS` — more than 20,000 rows in one batch. `PAYLOAD_TOO_LARGE` — request body exceeds the size limit. Split the batch.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "TOO_MANY_ROWS": {
                    "summary": "More than 20,000 rows",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "TOO_MANY_ROWS",
                        "message": "Batch exceeds EXTERNAL_INGEST_MAX_ROWS (20000). Got 25000."
                      }
                    }
                  },
                  "PAYLOAD_TOO_LARGE": {
                    "summary": "Body too large",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "PAYLOAD_TOO_LARGE",
                        "message": "request body too large"
                      }
                    }
                  }
                }
              }
            }
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "422": {
            "$ref": "#/components/responses/ValidationFailed"
          },
          "429": {
            "description": "`RATE_LIMITED` — 60 requests/min per key, or the `POST /cases` limit of 10 batches/hour per key (dry runs and idempotent replays count). `AUTH_LOCKED` — key locked after 10 signature failures. Honour `Retry-After`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              },
              "Retry-After": {
                "$ref": "#/components/headers/RetryAfter"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "RATE_LIMITED": {
                    "summary": "Batch or request limit",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "RATE_LIMITED",
                        "message": "Too many requests",
                        "retryAfter": 1800
                      }
                    }
                  },
                  "AUTH_LOCKED": {
                    "summary": "Key locked after signature failures",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "AUTH_LOCKED",
                        "message": "too many failed signatures; key locked for 842s"
                      }
                    }
                  }
                }
              }
            }
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          },
          "503": {
            "description": "`FEATURE_DISABLED` — case ingestion is switched off on this environment; contact partners@fluxusforge.in.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "FEATURE_DISABLED": {
                    "summary": "Ingestion disabled",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "FEATURE_DISABLED",
                        "message": "External-lender ingestion is disabled"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/partner/cases/updates": {
      "get": {
        "operationId": "listCaseUpdates",
        "tags": [
          "Cases"
        ],
        "summary": "Poll the change feed",
        "description": "Cursor-paged feed of every case event for your organisation — the same `EventEnvelope` objects your webhook receives, so one parser serves both. Use it as your webhook fallback / reconciliation path, or as your only integration if you do not run a callback.\n\nEvents are returned oldest-first and include ALL event types regardless of your webhook subscription. Call without `cursor` (optionally with `since`) the first time, then pass `nextCursor` on every subsequent call. Persist `nextCursor` only AFTER you have processed the whole page. When `hasMore` is `true`, call again immediately.\n\n`sequence` is per **case** (not per loan) and starts at 1 for every new case — a loan whose case closed and was re-pushed gets a NEW `caseId` and restarts at 1, so key your watermark on (`sourceLoanNumber`, `caseId`) or reset it when you see `case.received`. Sequence counts ALL event types including ones you are not subscribed to, so default subscribers legitimately see gaps (e.g. 1 → 4). Apply any event whose sequence is greater than your watermark — gaps are normal, never wait for them to fill; on a gap you may reconcile via `GET /api/v1/partner/cases/{sourceLoanNumber}`. Never skip a `payment.collected` because of ordering: book it (idempotent on `eventId` / `reference`) and gate only your case-state fields.",
        "parameters": [
          {
            "$ref": "#/components/parameters/UpdatesLimit"
          },
          {
            "$ref": "#/components/parameters/Cursor"
          },
          {
            "$ref": "#/components/parameters/UpdatesSince"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "A page of events (possibly empty).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/UpdatesResponse"
                },
                "example": {
                  "success": true,
                  "events": [
                    {
                      "eventId": "evt_66c1f2a9d4e5f60718293a4b",
                      "type": "case.received",
                      "occurredAt": "2026-08-11T18:30:00.000Z",
                      "version": 1,
                      "lenderCode": "YOURORG",
                      "sourceLoanNumber": "LN-2026-000123",
                      "sequence": 1,
                      "payload": {
                        "sourceLoanNumber": "LN-2026-000123",
                        "caseId": "CC-2026-7K3M9QA",
                        "status": "pending"
                      }
                    },
                    {
                      "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
                      "type": "payment.collected",
                      "occurredAt": "2026-08-14T09:35:12.000Z",
                      "version": 1,
                      "lenderCode": "YOURORG",
                      "sourceLoanNumber": "LN-2026-000123",
                      "sequence": 4,
                      "payload": {
                        "sourceLoanNumber": "LN-2026-000123",
                        "caseId": "CC-2026-7K3M9QA",
                        "amount": 4500,
                        "mode": "upi",
                        "reference": "UPI/512345678901",
                        "totalCollected": 4500,
                        "outstandingAfter": 14000,
                        "collectedAt": "2026-08-14T09:35:12.000Z"
                      }
                    }
                  ],
                  "nextCursor": "66c4d3a4b5c6d7e8f9a0b1c2",
                  "hasMore": false
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "422": {
            "description": "`VALIDATION_FAILED` — `cursor` is not a cursor this API issued, or `since` is not a valid datetime.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "cursor": {
                    "summary": "Bad cursor",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "cursor is not valid"
                      }
                    }
                  },
                  "since": {
                    "summary": "Bad since",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "since is not a valid date"
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/cases/{sourceLoanNumber}": {
      "get": {
        "operationId": "getCase",
        "tags": [
          "Cases"
        ],
        "summary": "Read one case",
        "description": "Live status of the case for one of your loans: status, assignment, totals and the last 20 visits. When a loan has had several cases (closed then re-pushed), the ACTIVE case is returned; otherwise the most recent one.\n\nUse it to reconcile after a sequence gap or a missed webhook. Note that in static-QR mode `visits[].amountCollected` is the field partner's UNVERIFIED claim until Fieldproof ops verify the proof — the confirmed amount arrives on `payment.collected`.\n\nThe path segment must be percent-encoded and the canonical string must contain the encoded path (e.g. `/api/v1/partner/cases/LN%2F001`).",
        "parameters": [
          {
            "$ref": "#/components/parameters/SourceLoanNumberPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "The case.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CaseResponse"
                },
                "example": {
                  "success": true,
                  "case": {
                    "sourceLoanNumber": "LN-2026-000123",
                    "caseId": "CC-2026-7K3M9QA",
                    "status": "in_progress",
                    "isActive": true,
                    "assignedAt": "2026-08-12T04:10:22.000Z",
                    "totalCollected": 4500,
                    "outstandingAmount": 14000,
                    "visits": [
                      {
                        "visitAt": "2026-08-14T09:32:00.000Z",
                        "outcome": "partial",
                        "amountCollected": 4500,
                        "paymentMode": "upi",
                        "paymentReference": "UPI/512345678901",
                        "ptpDate": null
                      }
                    ],
                    "createdAt": "2026-08-11T18:30:00.000Z",
                    "updatedAt": "2026-08-14T09:35:12.000Z"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "$ref": "#/components/responses/CaseNotFound"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/cases/{sourceLoanNumber}/recall": {
      "post": {
        "operationId": "recallCase",
        "tags": [
          "Cases"
        ],
        "summary": "Recall (withdraw) a case",
        "description": "Withdraw a case you no longer want worked — the borrower paid you directly, the loan was restructured or sold, etc. The case closes as `closed_unrecovered`, a `case.closed` event with `reason: recalled` is emitted, and the assigned field partner is told to stop.\n\nIdempotent: recalling a case that is already terminal returns `200` with `alreadyClosed: true` and its existing `status`, and changes nothing. To work the loan again later, push it again — that opens a FRESH case (new `caseId`, sequence restarts at 1).\n\nSend a JSON body with `Content-Type: application/json` — `{}` is fine, or `{ \"reason\": \"…\" }` — and sign those exact bytes. A POST with no body at all is `422 VALIDATION_FAILED`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/SourceLoanNumberPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RecallRequest"
              },
              "examples": {
                "empty": {
                  "summary": "No reason (`{}` is fine)",
                  "value": {}
                },
                "withReason": {
                  "summary": "With a reason",
                  "value": {
                    "reason": "Borrower settled directly with us"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Case recalled — or already terminal (`alreadyClosed: true`).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/RecallResponse"
                },
                "examples": {
                  "recalled": {
                    "summary": "Recalled now",
                    "value": {
                      "success": true,
                      "alreadyClosed": false,
                      "caseId": "CC-2026-7K3M9QA",
                      "status": "closed_unrecovered"
                    }
                  },
                  "alreadyClosed": {
                    "summary": "Already terminal",
                    "value": {
                      "success": true,
                      "alreadyClosed": true,
                      "caseId": "CC-2026-7K3M9QA",
                      "status": "collected"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "$ref": "#/components/responses/CaseNotFound"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "422": {
            "description": "`VALIDATION_FAILED` — `reason` longer than 200 characters, no body at all (`details[0].field` = `body`, \"must be object\"), or malformed JSON (message only). Unknown body fields are silently dropped, not rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "VALIDATION_FAILED": {
                    "summary": "Schema violation",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "request body failed validation",
                        "details": [
                          {
                            "field": "reason",
                            "reason": "must NOT have more than 200 characters"
                          }
                        ]
                      }
                    }
                  },
                  "VALIDATION_FAILED_no_body": {
                    "summary": "POST without a body",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "request body failed validation",
                        "details": [
                          {
                            "field": "body",
                            "reason": "must be object"
                          }
                        ]
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/cases/{sourceLoanNumber}/payments/confirm": {
      "post": {
        "operationId": "confirmPayment",
        "tags": [
          "Payments"
        ],
        "summary": "Confirm a gateway payment (org_gateway mode)",
        "description": "Available ONLY to organisations on the **org_gateway** payment mode (`403 PAYMENT_MODE_MISMATCH` otherwise). Your gateway's captures never reach Fieldproof by themselves — call this from your gateway webhook handler (or a poller) with `reference` = the gateway payment id so the case ledger, the field partner's earning and your events stay correct.\n\n**Effect** — the amount is rounded to the nearest whole INR rupee and booked. If it clears the case (amount ≥ 99% of the remaining outstanding — 1% tolerance) the case completes (`status: collected`), the partner who performed the visit is credited, and `payment.collected` THEN `case.closed` (`status: collected`, `reason: full_settlement`) are emitted. A partial amount emits `payment.collected` only; the case detaches from the partner and re-enters the marketplace after a cool-down (default 48 h).\n\n**Idempotency & errors** — the same (`sourceLoanNumber`, `reference`) is booked once; a repeat is `409 DUPLICATE_CONFIRMATION` (with `error.caseId`) — TREAT IT AS SUCCESS (only `caseId` is returned, not the original booking). `409 CASE_ALREADY_COLLECTED` means the case was already fully collected — this reference is a SECOND payment for money not owed: refund the borrower. `409 AMOUNT_EXCEEDS_OUTSTANDING` (amount > 101% of the remaining outstanding): refund or adjust. `409 CASE_CLOSED`: the case was recalled / written off before this payment: refund. `mode: \"cash\"` (any letter case) is `422 VALIDATION_FAILED`; any other unrecognised or mis-cased `mode` is accepted and booked as `link`. Unknown body fields are silently dropped.\n\n**Retries** — a `5xx` after the ledger row is written is safe to retry with the same body: the retry RESUMES and completes the booking.\n\nOn the sandbox this endpoint is self-driveable and DOES emit `payment.collected` / `case.closed`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/SourceLoanNumberPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ConfirmRequest"
              },
              "examples": {
                "partial": {
                  "summary": "Partial payment",
                  "value": {
                    "amount": 4500,
                    "reference": "pay_Nq7Xk2Lm9RtY3z",
                    "paidAt": "2026-08-14T09:35:12.000Z",
                    "mode": "upi",
                    "linkId": "plink_8Hs2kD9"
                  }
                },
                "fullClear": {
                  "summary": "Full clearance",
                  "value": {
                    "amount": 14000,
                    "reference": "pay_Rt8Yz3Kp2Mn1qW",
                    "mode": "link"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Payment booked.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ConfirmResponse"
                },
                "examples": {
                  "partial": {
                    "summary": "Partial — case stays open",
                    "value": {
                      "success": true,
                      "caseId": "CC-2026-7K3M9QA",
                      "amount": 4500,
                      "outstandingAfter": 14000,
                      "status": "in_progress"
                    }
                  },
                  "fullClear": {
                    "summary": "Full clearance — case collected",
                    "value": {
                      "success": true,
                      "caseId": "CC-2026-7K3M9QA",
                      "amount": 14000,
                      "outstandingAfter": 0,
                      "status": "collected"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "description": "`PAYMENT_MODE_MISMATCH` — your organisation is not on the org_gateway payment mode (static-QR orgs never call this endpoint). `LENDER_INACTIVE` — organisation suspended.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "PAYMENT_MODE_MISMATCH": {
                    "summary": "Not an org_gateway organisation",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "PAYMENT_MODE_MISMATCH",
                        "message": "payments/confirm is only available for organisations on the org_gateway payment mode"
                      }
                    }
                  },
                  "LENDER_INACTIVE": {
                    "summary": "Organisation suspended",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "LENDER_INACTIVE",
                        "message": "organisation is inactive"
                      }
                    }
                  }
                }
              }
            }
          },
          "404": {
            "$ref": "#/components/responses/CaseNotFound"
          },
          "409": {
            "description": "Conflict with the case's ledger state. `DUPLICATE_CONFIRMATION` — this (loan, reference) was already booked; treat as success (`error.caseId` is included). `CASE_ALREADY_COLLECTED` — the case is already fully collected; refund this capture. `AMOUNT_EXCEEDS_OUTSTANDING` — amount is more than 101% of the remaining outstanding; refund/adjust. `CASE_CLOSED` — the case was recalled/closed before this payment; refund.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "DUPLICATE_CONFIRMATION": {
                    "summary": "Already booked — treat as success",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "DUPLICATE_CONFIRMATION",
                        "message": "this reference was already confirmed for this loan",
                        "caseId": "CC-2026-7K3M9QA"
                      }
                    }
                  },
                  "CASE_ALREADY_COLLECTED": {
                    "summary": "Case already fully collected — refund",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "CASE_ALREADY_COLLECTED",
                        "message": "case CC-2026-7K3M9QA is already fully collected (₹18500); refund reference pay_Rt8Yz3Kp2Mn1qW to the borrower"
                      }
                    }
                  },
                  "AMOUNT_EXCEEDS_OUTSTANDING": {
                    "summary": "Amount above remaining outstanding — refund/adjust",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "AMOUNT_EXCEEDS_OUTSTANDING",
                        "message": "amount ₹20000 exceeds remaining outstanding ₹14000 on case CC-2026-7K3M9QA"
                      }
                    }
                  },
                  "CASE_CLOSED": {
                    "summary": "Case recalled/closed before payment — refund",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "CASE_CLOSED",
                        "message": "case CC-2026-7K3M9QA was recalled/closed before this payment; refund reference pay_Rt8Yz3Kp2Mn1qW to the borrower"
                      }
                    }
                  }
                }
              }
            }
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "422": {
            "description": "`VALIDATION_FAILED`, from one of two layers. **Schema check** (with `details[]`): `amount` missing, not a number, ≤ 0 or > 1,000,000,000; `reference` missing, empty or longer than 128 characters; `mode` longer than 20 characters; `linkId` longer than 128 characters; or malformed JSON (message only). **Booking check** (message only — NO `details`): `mode` is `cash` in any letter case (never accepted), `paidAt` is not a parseable date, `amount` rounds to 0 whole rupees (e.g. `0.4`), or `reference` is only whitespace. Unknown body fields are silently dropped, not rejected.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "VALIDATION_FAILED": {
                    "summary": "Schema violation",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "request body failed validation",
                        "details": [
                          {
                            "field": "amount",
                            "reason": "must be > 0"
                          }
                        ]
                      }
                    }
                  },
                  "VALIDATION_FAILED_cash": {
                    "summary": "Cash rejected",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "mode 'cash' is not accepted — org_gateway confirms are online captures"
                      }
                    }
                  },
                  "VALIDATION_FAILED_paidAt": {
                    "summary": "Unparseable paidAt (no details)",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "paidAt is not a valid date"
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/webhooks/test": {
      "post": {
        "operationId": "testWebhook",
        "tags": [
          "Webhooks"
        ],
        "summary": "Send a signed ping to your callback",
        "description": "Fires a signed `ping` event synchronously at your registered callback URL and reports what happened — the fastest way to verify URL, TLS, signature verification and your 2xx response. The ping uses the normal delivery headers (`X-Fieldproof-Event: ping`, `X-Fieldproof-Delivery`, `X-Fieldproof-Timestamp`, `X-Fieldproof-Signature`) and is signed with your HMAC secret over `POST\\n<callback path>\\n<timestamp>\\n<raw body>`. Its envelope has `sourceLoanNumber: null` and `sequence: null` — receivers must tolerate that.\n\n`success: true` means the test RAN; check `delivered`, `statusCode`, `error` and `bodyExcerpt` for the result. Send `{}` as the JSON body and sign those two bytes.",
        "parameters": [
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EmptyBody"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "The ping was attempted. `delivered` tells you whether your callback answered 2xx within 10 s.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookTestResponse"
                },
                "examples": {
                  "delivered": {
                    "summary": "Callback answered 2xx",
                    "value": {
                      "success": true,
                      "delivered": true,
                      "statusCode": 200,
                      "latencyMs": 143,
                      "error": null,
                      "bodyExcerpt": "{\"ok\":true}"
                    }
                  },
                  "failed": {
                    "summary": "Callback returned 401 (bad signature check?)",
                    "value": {
                      "success": true,
                      "delivered": false,
                      "statusCode": 401,
                      "latencyMs": 98,
                      "error": null,
                      "bodyExcerpt": "{\"error\":\"invalid signature\"}"
                    }
                  },
                  "unreachable": {
                    "summary": "Connection failed",
                    "value": {
                      "success": true,
                      "delivered": false,
                      "statusCode": 0,
                      "latencyMs": 10004,
                      "error": "The operation was aborted due to timeout",
                      "bodyExcerpt": null
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "422": {
            "description": "`CALLBACK_NOT_CONFIGURED` — no active callback URL is registered for this environment (sandbox and production are configured separately). `VALIDATION_FAILED` — malformed JSON body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "CALLBACK_NOT_CONFIGURED": {
                    "summary": "No callback registered",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "CALLBACK_NOT_CONFIGURED",
                        "message": "no active callback URL (or no active API key for this environment) is configured for your organisation"
                      }
                    }
                  },
                  "VALIDATION_FAILED": {
                    "summary": "Malformed JSON",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "malformed request body (send valid JSON)"
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/webhooks/deliveries": {
      "get": {
        "operationId": "listWebhookDeliveries",
        "tags": [
          "Webhooks"
        ],
        "summary": "List your webhook delivery log",
        "description": "Your organisation's delivery log, newest first — one row per event that was queued for your callback, with attempt count, last status code / error and next attempt time. This is how you monitor delivery health: Fieldproof does not alert your technical contact about exhausted deliveries or a tripped circuit breaker; poll this endpoint (e.g. `?status=exhausted&since=<now − 30 days>&limit=200`, deduped on `eventId` + `replayedAt` — see `since` for why a short window misses rows) and replay what you missed.\n\nOnly events that were queued for a callback have a row here — events emitted while no callback was configured are available through `GET /api/v1/partner/cases/updates`, and can be replayed (which creates the delivery on demand).",
        "parameters": [
          {
            "$ref": "#/components/parameters/DeliveriesLimit"
          },
          {
            "$ref": "#/components/parameters/DeliveryStatus"
          },
          {
            "$ref": "#/components/parameters/DeliveriesSince"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "Delivery rows, newest first.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DeliveriesResponse"
                },
                "example": {
                  "success": true,
                  "deliveries": [
                    {
                      "eventId": "evt_66c9e5f6a7b8c9d0e1f2a3b4",
                      "sourceLoanNumber": "LN-2026-000123",
                      "sequence": 6,
                      "type": "case.closed",
                      "status": "exhausted",
                      "attempts": 7,
                      "nextAttemptAt": "2026-08-19T18:15:15.300Z",
                      "deliveredAt": null,
                      "lastStatusCode": 503,
                      "lastError": "HTTP 503",
                      "replayedAt": null,
                      "createdAt": "2026-08-18T11:02:45.300Z"
                    },
                    {
                      "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
                      "sourceLoanNumber": "LN-2026-000123",
                      "sequence": 4,
                      "type": "payment.collected",
                      "status": "delivered",
                      "attempts": 1,
                      "nextAttemptAt": "2026-08-14T09:35:12.900Z",
                      "deliveredAt": "2026-08-14T09:35:13.412Z",
                      "lastStatusCode": 200,
                      "lastError": null,
                      "replayedAt": null,
                      "createdAt": "2026-08-14T09:35:12.900Z"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "422": {
            "description": "`VALIDATION_FAILED` — `status` is not one of pending|in_flight|delivered|exhausted, or `since` is not a valid datetime.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "status": {
                    "summary": "Bad status",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "status must be pending|in_flight|delivered|exhausted"
                      }
                    }
                  },
                  "since": {
                    "summary": "Bad since",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "since is not a valid date"
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/webhooks/deliveries/{eventId}/replay": {
      "post": {
        "operationId": "replayWebhookDelivery",
        "tags": [
          "Webhooks"
        ],
        "summary": "Re-queue a webhook delivery",
        "description": "Queue an event for re-delivery to your callback with a FRESH retry ladder (attempts reset to 0). Works on `exhausted` rows and on already-`delivered` rows (e.g. you lost a processed event). Delivery-log rows are kept for 30 days after they finish, but a replay rebuilds the delivery from the event store, which keeps events for about 13 months — so any event from that window can be replayed. If the row is already `pending` / `in_flight`, nothing changes and the response says so.\n\nEvents that never had a delivery row (emitted while no callback was configured, or before you subscribed to the type) can be replayed too: the delivery is created on demand from the event store and queued — this requires an active callback (`422 CALLBACK_NOT_CONFIGURED` otherwise). `404 DELIVERY_NOT_FOUND` means no event with that id exists for your organisation. Send `{}` as the JSON body and sign those two bytes.",
        "parameters": [
          {
            "$ref": "#/components/parameters/EventIdPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EmptyBody"
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "Re-delivery queued (or already queued).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReplayResponse"
                },
                "examples": {
                  "queued": {
                    "summary": "Queued",
                    "value": {
                      "success": true,
                      "status": "pending",
                      "message": "re-delivery queued"
                    }
                  },
                  "alreadyQueued": {
                    "summary": "Already queued",
                    "value": {
                      "success": true,
                      "status": "in_flight",
                      "message": "delivery is already queued"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "description": "`DELIVERY_NOT_FOUND` — no event with that `eventId` exists for your organisation (wrong id, or another organisation's event).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "DELIVERY_NOT_FOUND": {
                    "summary": "Unknown delivery",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "DELIVERY_NOT_FOUND",
                        "message": "no delivery with that eventId for your organisation"
                      }
                    }
                  }
                }
              }
            }
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "422": {
            "description": "`VALIDATION_FAILED` — malformed JSON body.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "VALIDATION_FAILED": {
                    "summary": "Malformed JSON",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "malformed request body (send valid JSON)"
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/billing/statements": {
      "get": {
        "operationId": "listBillingStatements",
        "tags": [
          "Billing"
        ],
        "summary": "List finalized monthly statements",
        "description": "Your organisation's finalized monthly billing statements, newest month first — each with the month's activity, the billed charge lines, GST and a summary of its GST tax invoice. Only finalized (immutable) months are listed: the current month and any month Fieldproof has not closed yet are simply absent. Fieldproof's internal figures (field-partner payouts, margin) are never included.\n\nA statement whose invoice number was not allocated at finalization has `invoice: null`; the invoice endpoints answer `409 NO_INVOICE` for that month.\n\nSigned like every request — `GET`, empty body, and the canonical `PATH` excludes the query string (`/api/v1/partner/billing/statements`).",
        "parameters": [
          {
            "$ref": "#/components/parameters/BillingLimit"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "Finalized statements, newest first (possibly none).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BillingStatementsResponse"
                },
                "example": {
                  "success": true,
                  "count": 1,
                  "statements": [
                    {
                      "month": "2026-09",
                      "status": "final",
                      "currency": "INR",
                      "pricingModel": "hybrid",
                      "activity": {
                        "collectedAmount": 100000,
                        "payments": 1,
                        "resolvedCases": 1,
                        "completedVisits": 1,
                        "collectedByBucket": {
                          "0-30": 100000
                        }
                      },
                      "charges": {
                        "commission": 5000,
                        "caseFees": 100,
                        "visitFees": 0,
                        "retainer": 0,
                        "minimumTopUp": 0,
                        "adjustmentBroughtForward": 0,
                        "adjustmentCarriedForward": 0,
                        "subtotal": 5100,
                        "gstPct": 18,
                        "gstAmount": 918,
                        "total": 6018
                      },
                      "invoice": {
                        "number": "FP/26-27/0001",
                        "issuedAt": "2026-10-05T06:30:00.000Z",
                        "dueAt": "2026-10-20T06:30:00.000Z",
                        "status": "issued",
                        "sacCode": "997159",
                        "amountReceived": 0
                      },
                      "finalizedAt": "2026-10-05T06:30:00.000Z"
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "422": {
            "description": "`VALIDATION_FAILED` — `limit` is not an integer between 1 and 60 (out-of-range values are rejected, not clamped).",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "limit": {
                    "summary": "limit above 60",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "VALIDATION_FAILED",
                        "message": "request body failed validation",
                        "details": [
                          {
                            "field": "limit",
                            "reason": "must be <= 60"
                          }
                        ]
                      }
                    }
                  }
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/billing/statements/{month}": {
      "get": {
        "operationId": "getBillingStatement",
        "tags": [
          "Billing"
        ],
        "summary": "Get one month's finalized statement",
        "description": "One finalized month — the same object as an item of `GET /api/v1/partner/billing/statements`, under `statement`. `404 STATEMENT_NOT_FOUND` means the month is not finalized (not billed yet), not an error on your side.",
        "parameters": [
          {
            "$ref": "#/components/parameters/MonthPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "The statement.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BillingStatementResponse"
                },
                "example": {
                  "success": true,
                  "statement": {
                    "month": "2026-09",
                    "status": "final",
                    "currency": "INR",
                    "pricingModel": "hybrid",
                    "activity": {
                      "collectedAmount": 100000,
                      "payments": 1,
                      "resolvedCases": 1,
                      "completedVisits": 1,
                      "collectedByBucket": {
                        "0-30": 100000
                      }
                    },
                    "charges": {
                      "commission": 5000,
                      "caseFees": 100,
                      "visitFees": 0,
                      "retainer": 0,
                      "minimumTopUp": 0,
                      "adjustmentBroughtForward": 0,
                      "adjustmentCarriedForward": 0,
                      "subtotal": 5100,
                      "gstPct": 18,
                      "gstAmount": 918,
                      "total": 6018
                    },
                    "invoice": {
                      "number": "FP/26-27/0001",
                      "issuedAt": "2026-10-05T06:30:00.000Z",
                      "dueAt": "2026-10-20T06:30:00.000Z",
                      "status": "issued",
                      "sacCode": "997159",
                      "amountReceived": 0
                    },
                    "finalizedAt": "2026-10-05T06:30:00.000Z"
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "$ref": "#/components/responses/StatementNotFound"
          },
          "422": {
            "$ref": "#/components/responses/InvalidMonth"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/billing/statements/{month}/invoice": {
      "get": {
        "operationId": "getBillingInvoice",
        "tags": [
          "Billing"
        ],
        "summary": "Get the GST tax invoice (JSON)",
        "description": "The month's GST tax invoice as structured JSON: seller and buyer, line items, GST, indicative TDS and net payable. `status` moves `issued` → `part_paid` → `paid` as your payments are recorded; `overdue` is derived when an unpaid invoice is past `dueAt`.\n\n`buyer` (legal name, GSTIN, address, billing e-mail) comes from your onboarding profile — tell partners@fluxusforge.in if it changes. `tds.expected` is indicative TDS on the pre-GST `subtotal` (`netPayable` = `total` − `tds.expected`); deduct as applicable under law and share the certificate.",
        "parameters": [
          {
            "$ref": "#/components/parameters/MonthPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "The invoice.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/BillingInvoiceResponse"
                },
                "example": {
                  "success": true,
                  "invoice": {
                    "number": "FP/26-27/0001",
                    "issuedAt": "2026-10-05T06:30:00.000Z",
                    "dueAt": "2026-10-20T06:30:00.000Z",
                    "status": "issued",
                    "month": "2026-09",
                    "sacCode": "997159",
                    "seller": {
                      "legalName": "…",
                      "gstin": "…",
                      "pan": "…",
                      "address": "…",
                      "email": "…",
                      "state": "…"
                    },
                    "buyer": {
                      "legalName": "Your Org",
                      "gstin": "27ZZZZZ9999Z1Z5",
                      "address": "…",
                      "email": "…"
                    },
                    "lines": [
                      {
                        "desc": "Collection commission",
                        "amount": 5000
                      },
                      {
                        "desc": "Case resolution fees",
                        "amount": 100
                      }
                    ],
                    "subtotal": 5100,
                    "gstPct": 18,
                    "gstAmount": 918,
                    "total": 6018,
                    "tds": {
                      "section": "194H",
                      "ratePct": 2,
                      "expected": 102
                    },
                    "netPayable": 5916,
                    "received": {
                      "gross": 0,
                      "tds": 0,
                      "settledAt": null
                    },
                    "notes": "Fees for field-collection services. Money collected is remitted separately to the organisation."
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "$ref": "#/components/responses/StatementNotFound"
          },
          "409": {
            "$ref": "#/components/responses/NoInvoice"
          },
          "422": {
            "$ref": "#/components/responses/InvalidMonth"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    },
    "/api/v1/partner/billing/statements/{month}/invoice.pdf": {
      "get": {
        "operationId": "getBillingInvoicePdf",
        "tags": [
          "Billing"
        ],
        "summary": "Download the GST tax invoice (PDF)",
        "description": "The month's GST tax invoice as a downloadable PDF: `Content-Type: application/pdf` and `Content-Disposition: attachment` with the invoice number as the filename (`/` replaced by `-`, e.g. `FP-26-27-0001.pdf`). Same content as the JSON invoice; amounts are prefixed `INR` instead of the ₹ sign, which PDF standard fonts do not carry. Error responses are JSON (`Error` envelope) as everywhere else.\n\nSign the full path including the `.pdf` suffix: `GET\\n/api/v1/partner/billing/statements/2026-09/invoice.pdf\\n<timestamp>\\n`.",
        "parameters": [
          {
            "$ref": "#/components/parameters/MonthPath"
          },
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "responses": {
          "200": {
            "description": "The invoice PDF.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              },
              "Content-Disposition": {
                "description": "`attachment; filename=\"<invoice number with / replaced by ->.pdf\"`.",
                "schema": {
                  "type": "string",
                  "example": "attachment; filename=\"FP-26-27-0001.pdf\""
                }
              }
            },
            "content": {
              "application/pdf": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/LenderInactive"
          },
          "404": {
            "$ref": "#/components/responses/StatementNotFound"
          },
          "409": {
            "$ref": "#/components/responses/NoInvoice"
          },
          "422": {
            "$ref": "#/components/responses/InvalidMonth"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "description": "`INTERNAL_ERROR` — unexpected server error, including a failure to render the PDF. Safe to retry; quote `X-Request-Id` to partners@fluxusforge.in if it persists.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "PDF_RENDER": {
                    "summary": "PDF could not be rendered",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "INTERNAL_ERROR",
                        "message": "could not render invoice pdf"
                      }
                    }
                  },
                  "INTERNAL_ERROR": {
                    "summary": "Server error",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "INTERNAL_ERROR",
                        "message": "internal error"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/partner/debug/echo-signature": {
      "post": {
        "operationId": "echoSignature",
        "tags": [
          "Sandbox tools"
        ],
        "summary": "Debug your HMAC signature (sandbox only)",
        "description": "**Sandbox only** — works with a TEST key on the sandbox host; a live key or the production host gets `403 SANDBOX_ONLY`.\n\nDeliberately accepts a wrong or missing `X-Fieldproof-Signature` (that is what you are debugging) but still requires a valid test `Authorization: Bearer` key and the `X-Fieldproof-Timestamp` header. The key must be an existing, active (not revoked) TEST key of your organisation; its expiry date is not checked, and because the signature is never verified these calls neither count toward nor are blocked by the signature-failure lockout. Returns the canonical string exactly as the server computed it for THIS request, its parts (method, path without query, timestamp, raw-body byte length and SHA-256), the signature the server expected and the one you sent — so you can diff which component differs. Send any JSON body (e.g. `{\"probe\":true}`) to check body handling.",
        "parameters": [
          {
            "$ref": "#/components/parameters/XFieldproofTimestamp"
          },
          {
            "$ref": "#/components/parameters/XFieldproofSignature"
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "additionalProperties": true,
                "description": "Any JSON body — echoed into `canonicalParts.bodyBytes` / `bodySha256`.",
                "example": {
                  "probe": true
                }
              },
              "example": {
                "probe": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Canonical string, expected vs received signature, and skew check.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/EchoSignatureResponse"
                },
                "example": {
                  "success": true,
                  "canonicalString": "POST\n/api/v1/partner/debug/echo-signature\n1755500000000\n{\"probe\":true}",
                  "canonicalParts": {
                    "method": "POST",
                    "path": "/api/v1/partner/debug/echo-signature",
                    "timestamp": "1755500000000",
                    "bodyBytes": 14,
                    "bodySha256": "c775500ea34eded73c2a3c3bede193f0d839e6c14b36f21b6cc31472e0720a91"
                  },
                  "expectedSignature": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210",
                  "receivedSignature": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
                  "signatureMatches": false,
                  "timestampWithinSkew": true,
                  "note": "Sign hex(HMAC-SHA256(canonicalString, hmacSecret)) over the EXACT raw body bytes — do not re-serialize JSON after signing."
                }
              }
            }
          },
          "401": {
            "description": "`UNAUTHORIZED` — missing/unknown/revoked key, source IP not allowed, or missing `X-Fieldproof-Timestamp`.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "UNAUTHORIZED": {
                    "summary": "Missing or unknown key",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "UNAUTHORIZED",
                        "message": "unknown api key"
                      }
                    }
                  }
                }
              }
            }
          },
          "403": {
            "description": "`SANDBOX_ONLY` — called with a live key or on the production host. `LENDER_INACTIVE` — organisation suspended.",
            "headers": {
              "X-Request-Id": {
                "$ref": "#/components/headers/XRequestId"
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "SANDBOX_ONLY": {
                    "summary": "Not on sandbox / not a test key",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "SANDBOX_ONLY",
                        "message": "echo-signature is available only on the sandbox with sandbox (test) keys"
                      }
                    }
                  },
                  "LENDER_INACTIVE": {
                    "summary": "Organisation suspended",
                    "value": {
                      "success": false,
                      "error": {
                        "code": "LENDER_INACTIVE",
                        "message": "organisation is inactive"
                      }
                    }
                  }
                }
              }
            }
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "429": {
            "$ref": "#/components/responses/TooManyRequests"
          },
          "500": {
            "$ref": "#/components/responses/InternalError"
          }
        }
      }
    }
  },
  "x-webhooks": {
    "caseEvent": {
      "post": {
        "operationId": "receiveCaseEvent",
        "tags": [
          "Webhooks"
        ],
        "summary": "Case event delivered to your callback URL",
        "description": "Fieldproof POSTs each subscribed event to your registered HTTPS callback URL (public IP, no redirects followed, ≤ 64 KB of response read, 10 s timeout). Respond with any 2xx within 10 s; anything else (or a timeout) is retried on the ladder 0 s, 30 s, 2 m, 10 m, 1 h, 6 h, 24 h — 7 attempts (~31 h) — then the delivery is `exhausted` (replayable for about 13 months via `POST /api/v1/partner/webhooks/deliveries/{eventId}/replay`; the delivery-log row itself is kept 30 days). After 20 consecutive failures the endpoint is suspended and probed every 15 min; it auto-recovers and the backlog drains oldest-first with up to 25 concurrent POSTs, so deliveries are not strictly serialised per case. Delivery is at-least-once — dedupe on `eventId`. Sandbox and production callbacks are configured separately.\n\n**Signature** — `X-Fieldproof-Signature` = lowercase hex HMAC-SHA256 over `POST\\n<callback path>\\n<X-Fieldproof-Timestamp>\\n<raw body>` keyed with the HMAC secret of the FIRST active API key on your organisation for this environment — if you hold two active keys, verify with the first one's secret (`<callback path>` = URL pathname only). On key rotation the NEW secret signs webhooks immediately, so accept multiple secrets BEFORE requesting a rotation.\n\n`sequence` is per **case** (not per loan) and starts at 1 for every new case — a loan whose case closed and was re-pushed gets a NEW `caseId` and restarts at 1, so key your watermark on (`sourceLoanNumber`, `caseId`) or reset it when you see `case.received`. Sequence counts ALL event types including ones you are not subscribed to, so default subscribers legitimately see gaps (e.g. 1 → 4). Apply any event whose sequence is greater than your watermark — gaps are normal, never wait for them to fill; on a gap you may reconcile via `GET /api/v1/partner/cases/{sourceLoanNumber}`. Never skip a `payment.collected` because of ordering: book it (idempotent on `eventId` / `reference`) and gate only your case-state fields.",
        "security": [],
        "parameters": [
          {
            "name": "X-Fieldproof-Event",
            "in": "header",
            "required": true,
            "description": "The event `type` (e.g. `payment.collected`, or `ping` for the self-test). Duplicated as `X-Quikkred-Event`.",
            "schema": {
              "type": "string",
              "example": "payment.collected"
            }
          },
          {
            "name": "X-Fieldproof-Delivery",
            "in": "header",
            "required": true,
            "description": "Equals the body's `eventId`. Dedupe on it — delivery is at-least-once. Duplicated as `X-Quikkred-Delivery`.",
            "schema": {
              "type": "string",
              "example": "evt_66c4d3a4b5c6d7e8f9a0b1c2"
            }
          },
          {
            "name": "X-Fieldproof-Timestamp",
            "in": "header",
            "required": true,
            "description": "Unix ms at signing time. Reject deliveries older than a few minutes to limit replay. Duplicated as `X-Quikkred-Timestamp`.",
            "schema": {
              "type": "string",
              "example": "1755500000000"
            }
          },
          {
            "name": "X-Fieldproof-Signature",
            "in": "header",
            "required": true,
            "description": "Lowercase hex `HMAC-SHA256(\"POST\\n<callback path>\\n<timestamp>\\n<raw body>\", hmacSecret)` — `<callback path>` is the URL pathname of your callback only (no query string — do not put a query string in your callback URL). Verify over the RAW body bytes before parsing, and accept BOTH the current and the previous secret around a key rotation. Duplicated as `X-Quikkred-Signature`.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$",
              "example": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/EventEnvelope"
              },
              "examples": {
                "case.received": {
                  "summary": "case.received",
                  "value": {
                    "eventId": "evt_66c1f2a9d4e5f60718293a4b",
                    "type": "case.received",
                    "occurredAt": "2026-08-11T18:30:00.000Z",
                    "version": 1,
                    "lenderCode": "YOURORG",
                    "sourceLoanNumber": "LN-2026-000123",
                    "sequence": 1,
                    "payload": {
                      "sourceLoanNumber": "LN-2026-000123",
                      "caseId": "CC-2026-7K3M9QA",
                      "status": "pending"
                    }
                  }
                },
                "case.assigned": {
                  "summary": "case.assigned (opt-in)",
                  "value": {
                    "eventId": "evt_66c2a0b1c2d3e4f5a6b7c8d9",
                    "type": "case.assigned",
                    "occurredAt": "2026-08-12T04:10:22.000Z",
                    "version": 1,
                    "lenderCode": "YOURORG",
                    "sourceLoanNumber": "LN-2026-000123",
                    "sequence": 2,
                    "payload": {
                      "sourceLoanNumber": "LN-2026-000123",
                      "caseId": "CC-2026-7K3M9QA",
                      "assignedAt": "2026-08-12T04:10:22.000Z"
                    }
                  }
                },
                "visit.completed": {
                  "summary": "visit.completed (opt-in)",
                  "value": {
                    "eventId": "evt_66c4d1e2f3a4b5c6d7e8f9a0",
                    "type": "visit.completed",
                    "occurredAt": "2026-08-14T09:32:00.000Z",
                    "version": 1,
                    "lenderCode": "YOURORG",
                    "sourceLoanNumber": "LN-2026-000123",
                    "sequence": 3,
                    "payload": {
                      "sourceLoanNumber": "LN-2026-000123",
                      "caseId": "CC-2026-7K3M9QA",
                      "outcome": "delivered_acknowledged",
                      "visitAt": "2026-08-14T09:32:00.000Z",
                      "ptpDate": "2026-08-20",
                      "notes": "Borrower promised to pay after salary credit"
                    }
                  }
                },
                "payment.collected": {
                  "summary": "payment.collected",
                  "value": {
                    "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
                    "type": "payment.collected",
                    "occurredAt": "2026-08-14T09:35:12.000Z",
                    "version": 1,
                    "lenderCode": "YOURORG",
                    "sourceLoanNumber": "LN-2026-000123",
                    "sequence": 4,
                    "payload": {
                      "sourceLoanNumber": "LN-2026-000123",
                      "caseId": "CC-2026-7K3M9QA",
                      "amount": 4500,
                      "mode": "upi",
                      "reference": "UPI/512345678901",
                      "totalCollected": 4500,
                      "outstandingAfter": 14000,
                      "collectedAt": "2026-08-14T09:35:12.000Z"
                    }
                  }
                },
                "case.closed": {
                  "summary": "case.closed",
                  "value": {
                    "eventId": "evt_66c9e5f6a7b8c9d0e1f2a3b4",
                    "type": "case.closed",
                    "occurredAt": "2026-08-18T11:02:45.000Z",
                    "version": 1,
                    "lenderCode": "YOURORG",
                    "sourceLoanNumber": "LN-2026-000123",
                    "sequence": 6,
                    "payload": {
                      "sourceLoanNumber": "LN-2026-000123",
                      "caseId": "CC-2026-7K3M9QA",
                      "status": "collected",
                      "reason": "full_settlement",
                      "totalCollected": 18500
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Acknowledged. Any 2xx within 10 s marks the delivery `delivered`. Do your processing idempotently (dedupe on `eventId`); if you must do slow work, ack first and process asynchronously."
          },
          "default": {
            "description": "Any non-2xx status, or no response within 10 s, is a failed attempt and will be retried on the ladder."
          }
        }
      }
    },
    "ping": {
      "post": {
        "operationId": "receivePing",
        "tags": [
          "Webhooks"
        ],
        "summary": "Ping delivered by POST /webhooks/test",
        "description": "Sent synchronously when you call `POST /api/v1/partner/webhooks/test`. Same headers and signature scheme as a case event (`X-Fieldproof-Event: ping`, `X-Fieldproof-Delivery` = `evt_ping_<16 hex>`); the envelope has `sourceLoanNumber: null` and `sequence: null`. Respond 2xx.",
        "security": [],
        "parameters": [
          {
            "name": "X-Fieldproof-Event",
            "in": "header",
            "required": true,
            "description": "The event `type` (e.g. `payment.collected`, or `ping` for the self-test). Duplicated as `X-Quikkred-Event`.",
            "schema": {
              "type": "string",
              "example": "payment.collected"
            }
          },
          {
            "name": "X-Fieldproof-Delivery",
            "in": "header",
            "required": true,
            "description": "Equals the body's `eventId`. Dedupe on it — delivery is at-least-once. Duplicated as `X-Quikkred-Delivery`.",
            "schema": {
              "type": "string",
              "example": "evt_66c4d3a4b5c6d7e8f9a0b1c2"
            }
          },
          {
            "name": "X-Fieldproof-Timestamp",
            "in": "header",
            "required": true,
            "description": "Unix ms at signing time. Reject deliveries older than a few minutes to limit replay. Duplicated as `X-Quikkred-Timestamp`.",
            "schema": {
              "type": "string",
              "example": "1755500000000"
            }
          },
          {
            "name": "X-Fieldproof-Signature",
            "in": "header",
            "required": true,
            "description": "Lowercase hex `HMAC-SHA256(\"POST\\n<callback path>\\n<timestamp>\\n<raw body>\", hmacSecret)` — `<callback path>` is the URL pathname of your callback only (no query string — do not put a query string in your callback URL). Verify over the RAW body bytes before parsing, and accept BOTH the current and the previous secret around a key rotation. Duplicated as `X-Quikkred-Signature`.",
            "schema": {
              "type": "string",
              "pattern": "^[0-9a-f]{64}$",
              "example": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PingEvent"
              },
              "example": {
                "eventId": "evt_ping_9f8e7d6c5b4a3f21",
                "type": "ping",
                "occurredAt": "2026-08-18T10:00:00.000Z",
                "version": 1,
                "lenderCode": "YOURORG",
                "sourceLoanNumber": null,
                "sequence": null,
                "payload": {
                  "message": "webhook connectivity test — respond 2xx and dedupe on eventId"
                }
              }
            }
          }
        },
        "responses": {
          "2XX": {
            "description": "Acknowledged — reported as `delivered: true` in the `POST /webhooks/test` response."
          },
          "default": {
            "description": "Reported as `delivered: false` with your `statusCode` / `error` / `bodyExcerpt` in the `POST /webhooks/test` response."
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "apiKeyId": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "apiKeyId (pk_<org>_test_<hex> | pk_<org>_live_<hex>)",
        "description": "Send `Authorization: Bearer <apiKeyId>` — `pk_<org>_test_<hex>` on the sandbox host, `pk_<org>_live_<hex>` on production. Keys are environment-locked: a test key on production (or a live key on the sandbox) is `401 UNAUTHORIZED`.\n\nEvery request MUST also carry two headers (legacy `X-Quikkred-Timestamp` / `X-Quikkred-Signature` are accepted as aliases; the `X-Fieldproof-*` value wins if both are present):\n\n* `X-Fieldproof-Timestamp` — unix epoch time in **milliseconds** (e.g. `1755500000000`). Must be within ±5 minutes of server time or the request is `401 TIMESTAMP_SKEW`.\n* `X-Fieldproof-Signature` — lowercase hex `HMAC-SHA256(canonicalString, hmacSecret)`. Comparison is case-insensitive (the server lowercases).\n\nCanonical string:\n\n```\nMETHOD + \"\\n\" + PATH + \"\\n\" + TIMESTAMP + \"\\n\" + RAW_BODY\n```\n\n* `METHOD` — upper-case HTTP method.\n* `PATH` — the request path exactly as transmitted, **without** the query string, percent-encoded as sent (e.g. `/api/v1/partner/cases/LN%2F001` when the loan number contains `/`).\n* `TIMESTAMP` — the same value you put in `X-Fieldproof-Timestamp`.\n* `RAW_BODY` — the exact request-body bytes you send (empty string for `GET`). Sign the bytes you transmit; never re-serialise JSON after signing.\n\nThe `hmacSecret` is the opaque secret shown once when the key is issued (it also verifies inbound webhooks). **Order of checks** — header presence first (`401 UNAUTHORIZED` when the Bearer key, timestamp or signature header is missing); then a body sent with a non-JSON `Content-Type` is `415 UNSUPPORTED_MEDIA_TYPE`; then the body is parsed (too large → `413 PAYLOAD_TOO_LARGE`, malformed JSON → `422 VALIDATION_FAILED` without `details`); then the key and HMAC signature are verified (the 401s above, `403 LENDER_INACTIVE`, `429 AUTH_LOCKED`); then the 60/min rate limit; then schema validation (`422 VALIDATION_FAILED` with `details`). So a 413, 415 or malformed-JSON 422 can be returned before your signature is checked, but schema validation never runs before authentication. Only `application/json` bodies are accepted and signed. Ten signature failures within 300 s lock the key for 900 s (`429 AUTH_LOCKED`, `Retry-After` = seconds remaining). Revocation takes effect within 60 s.\n\nOn the sandbox, `POST /api/v1/partner/debug/echo-signature` returns the canonical string the server computed so you can diff it against yours."
      }
    },
    "parameters": {
      "XFieldproofTimestamp": {
        "name": "X-Fieldproof-Timestamp",
        "in": "header",
        "required": true,
        "description": "Unix epoch time in **milliseconds** when you signed the request. Must be within ±5 minutes of server time (`401 TIMESTAMP_SKEW` otherwise). The identical string goes into the canonical string. Legacy alias: `X-Quikkred-Timestamp`.",
        "schema": {
          "type": "string",
          "pattern": "^[0-9]+$",
          "example": "1755500000000"
        }
      },
      "XFieldproofSignature": {
        "name": "X-Fieldproof-Signature",
        "in": "header",
        "required": true,
        "description": "Lowercase hex `HMAC-SHA256(\"METHOD\\nPATH\\nTIMESTAMP\\nRAW_BODY\", hmacSecret)`. PATH excludes the query string and is percent-encoded as transmitted; RAW_BODY is the exact bytes sent (empty for GET). Compared case-insensitively. Legacy alias: `X-Quikkred-Signature`.",
        "schema": {
          "type": "string",
          "pattern": "^[0-9a-fA-F]{64}$",
          "example": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210"
        }
      },
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": false,
        "description": "Optional client-chosen key for safe retries of `POST /api/v1/partner/cases`. Scoped to your organisation, remembered for 24 h, ignored on dry runs, and only `200` responses are cached. A replay with the same key returns the ORIGINAL response body verbatim (no payload comparison is made) with the header `X-Idempotent-Replay: true` — and it still counts toward the 10 batches/hour limit.",
        "schema": {
          "type": "string",
          "example": "push-2026-08-18T10:00:00Z-1"
        }
      },
      "DryRun": {
        "name": "dryRun",
        "in": "query",
        "required": false,
        "description": "Set to `1` to validate the batch only: nothing is written, no events are emitted, `Idempotency-Key` is ignored. Every row is validated exactly as on a real push (per-row errors, unparseable dpd/dates, in-batch duplicates), so use it to test a feed. Dry runs DO count toward the 10 batches/hour limit.",
        "schema": {
          "type": "string",
          "example": "1"
        }
      },
      "UpdatesLimit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "description": "Page size. Default 100, maximum 500 (values above the maximum are clamped).",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 500,
          "default": 100,
          "example": 100
        }
      },
      "Cursor": {
        "name": "cursor",
        "in": "query",
        "required": false,
        "description": "Opaque cursor from the previous page's `nextCursor`. Omit on the first call (or use `since`). If both `cursor` and `since` are given, `cursor` wins. An unrecognised value is `422 VALIDATION_FAILED`.",
        "schema": {
          "type": "string",
          "example": "66c4d3a4b5c6d7e8f9a0b1c2"
        }
      },
      "UpdatesSince": {
        "name": "since",
        "in": "query",
        "required": false,
        "description": "ISO 8601 datetime — for the FIRST call only, to start from a point in time. Filters by the time Fieldproof RECEIVED the event (server receipt time), not `occurredAt`. Ignored when `cursor` is present. An unparseable value is `422 VALIDATION_FAILED`.",
        "schema": {
          "type": "string",
          "format": "date-time",
          "example": "2026-08-17T00:00:00.000Z"
        }
      },
      "DeliveriesLimit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "description": "Page size. Default 50, maximum 200 (values above the maximum are clamped).",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 200,
          "default": 50,
          "example": 50
        }
      },
      "DeliveryStatus": {
        "name": "status",
        "in": "query",
        "required": false,
        "description": "Filter by delivery status. Any other value is `422 VALIDATION_FAILED`.",
        "schema": {
          "type": "string",
          "enum": [
            "pending",
            "in_flight",
            "delivered",
            "exhausted"
          ],
          "example": "exhausted"
        }
      },
      "DeliveriesSince": {
        "name": "since",
        "in": "query",
        "required": false,
        "description": "ISO 8601 datetime — only deliveries CREATED at or after this instant. An unparseable value is `422 VALIDATION_FAILED`. A delivery usually turns `exhausted` about 31 h after it was created, but it can take much longer: while your circuit breaker is open, parked deliveries do not use up attempts, and a replay restarts the ladder without changing `createdAt`. So for an exhausted-delivery alert poll `?status=exhausted&since=<now − 30 days>&limit=200` (rows are kept 30 days after they finish; results are newest-created first with no next page, so with the default `limit` of 50 an older row that exhausts late can be missed) and dedupe on `eventId` + `replayedAt` — a `since` of your last check would never match.",
        "schema": {
          "type": "string",
          "format": "date-time",
          "example": "2026-08-17T00:00:00.000Z"
        }
      },
      "SourceLoanNumberPath": {
        "name": "sourceLoanNumber",
        "in": "path",
        "required": true,
        "description": "Your loan number as pushed in `rows[].sourceLoanNumber`. Percent-encode it (e.g. `LN%2F001` for `LN/001`) and sign the encoded path.",
        "schema": {
          "type": "string",
          "maxLength": 64,
          "example": "LN-2026-000123"
        }
      },
      "EventIdPath": {
        "name": "eventId",
        "in": "path",
        "required": true,
        "description": "The `eventId` of a delivery row from `GET /api/v1/partner/webhooks/deliveries`.",
        "schema": {
          "type": "string",
          "pattern": "^evt_[0-9a-f]{24}$",
          "example": "evt_66c9e5f6a7b8c9d0e1f2a3b4"
        }
      },
      "BillingLimit": {
        "name": "limit",
        "in": "query",
        "required": false,
        "description": "How many recent months to return, newest first. Default 24, range 1–60 — a value outside the range (or not an integer) is `422 VALIDATION_FAILED`, not clamped.",
        "schema": {
          "type": "integer",
          "minimum": 1,
          "maximum": 60,
          "default": 24,
          "example": 12
        }
      },
      "MonthPath": {
        "name": "month",
        "in": "path",
        "required": true,
        "description": "IST calendar month, `YYYY-MM` (e.g. `2026-09`). Anything else is `422 VALIDATION_FAILED` (`details[0].field` = `month`).",
        "schema": {
          "type": "string",
          "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])$",
          "example": "2026-09"
        }
      }
    },
    "headers": {
      "XRequestId": {
        "description": "Server-side request id — present on every response. Quote it when contacting partners@fluxusforge.in.",
        "schema": {
          "type": "string",
          "example": "req_9f2c1b7e4d3a"
        }
      },
      "RetryAfter": {
        "description": "Seconds to wait before retrying.",
        "schema": {
          "type": "integer",
          "example": 30
        }
      },
      "XIdempotentReplay": {
        "description": "`true` when this body was served from the `Idempotency-Key` cache (the ORIGINAL response, not a re-execution).",
        "schema": {
          "type": "string",
          "enum": [
            "true"
          ]
        }
      }
    },
    "responses": {
      "Unauthorized": {
        "description": "Authentication failed. `UNAUTHORIZED` — missing/unknown/revoked/expired key, key–environment mismatch (test key on production or vice versa), source IP not on your allowlist, or missing `X-Fieldproof-Timestamp` / `X-Fieldproof-Signature`. `SIGNATURE_INVALID` — the HMAC did not match (check method, percent-encoded path without query, timestamp string and RAW body bytes; use echo-signature on the sandbox). `TIMESTAMP_SKEW` — timestamp more than 5 minutes from server time. Authentication is checked after the header-presence gate, the `415` Content-Type check and body parsing (`413` / malformed-JSON `422`), and before schema validation.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "UNAUTHORIZED": {
                "summary": "Missing or unknown key",
                "value": {
                  "success": false,
                  "error": {
                    "code": "UNAUTHORIZED",
                    "message": "unknown api key"
                  }
                }
              },
              "UNAUTHORIZED_env_mismatch": {
                "summary": "Key/environment mismatch",
                "value": {
                  "success": false,
                  "error": {
                    "code": "UNAUTHORIZED",
                    "message": "this is a test key; environment mismatch"
                  }
                }
              },
              "UNAUTHORIZED_missing_headers": {
                "summary": "Signature headers missing",
                "value": {
                  "success": false,
                  "error": {
                    "code": "UNAUTHORIZED",
                    "message": "x-fieldproof-timestamp and x-fieldproof-signature required (x-quikkred-* also accepted)"
                  }
                }
              },
              "SIGNATURE_INVALID": {
                "summary": "HMAC mismatch",
                "value": {
                  "success": false,
                  "error": {
                    "code": "SIGNATURE_INVALID",
                    "message": "signature mismatch"
                  }
                }
              },
              "TIMESTAMP_SKEW": {
                "summary": "Clock skew > 5 min",
                "value": {
                  "success": false,
                  "error": {
                    "code": "TIMESTAMP_SKEW",
                    "message": "timestamp skew exceeds 5 minutes"
                  }
                }
              }
            }
          }
        }
      },
      "LenderInactive": {
        "description": "`LENDER_INACTIVE` — your organisation is suspended on Fieldproof; contact partners@fluxusforge.in.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "LENDER_INACTIVE": {
                "summary": "Organisation suspended",
                "value": {
                  "success": false,
                  "error": {
                    "code": "LENDER_INACTIVE",
                    "message": "organisation is inactive"
                  }
                }
              }
            }
          }
        }
      },
      "TooManyRequests": {
        "description": "`RATE_LIMITED` — more than 60 requests/min for this API key. `AUTH_LOCKED` — 10 signature failures within 300 s locked the key for 900 s. Both carry `Retry-After` (seconds); back off and retry after it.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          },
          "Retry-After": {
            "$ref": "#/components/headers/RetryAfter"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "RATE_LIMITED": {
                "summary": "Per-key request limit",
                "value": {
                  "success": false,
                  "error": {
                    "code": "RATE_LIMITED",
                    "message": "Too many requests",
                    "retryAfter": 12
                  }
                }
              },
              "AUTH_LOCKED": {
                "summary": "Key locked after signature failures",
                "value": {
                  "success": false,
                  "error": {
                    "code": "AUTH_LOCKED",
                    "message": "too many failed signatures; key locked for 842s"
                  }
                }
              }
            }
          }
        }
      },
      "ValidationFailed": {
        "description": "`VALIDATION_FAILED` — the request envelope failed schema validation (`details[]` names the first violation found) or the JSON could not be parsed (message `malformed request body (send valid JSON)`, no `details`). Per-row problems never produce a 422 — they come back in the 200 response's `errors[]`; a 422 here means `rows` is missing / empty / not an array of objects, `fullSnapshot` is not a boolean, or the JSON is malformed. Unknown top-level fields are dropped, not rejected.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "VALIDATION_FAILED": {
                "summary": "Schema violation",
                "value": {
                  "success": false,
                  "error": {
                    "code": "VALIDATION_FAILED",
                    "message": "request body failed validation",
                    "details": [
                      {
                        "field": "rows",
                        "reason": "must NOT have fewer than 1 items"
                      }
                    ]
                  }
                }
              },
              "VALIDATION_FAILED_missing_rows": {
                "summary": "rows missing",
                "value": {
                  "success": false,
                  "error": {
                    "code": "VALIDATION_FAILED",
                    "message": "request body failed validation",
                    "details": [
                      {
                        "field": "rows",
                        "reason": "must have required property 'rows'"
                      }
                    ]
                  }
                }
              },
              "VALIDATION_FAILED_malformed": {
                "summary": "Malformed JSON",
                "value": {
                  "success": false,
                  "error": {
                    "code": "VALIDATION_FAILED",
                    "message": "malformed request body (send valid JSON)"
                  }
                }
              }
            }
          }
        }
      },
      "PayloadTooLarge": {
        "description": "`PAYLOAD_TOO_LARGE` — the request body exceeds the size limit.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "PAYLOAD_TOO_LARGE": {
                "summary": "Body too large",
                "value": {
                  "success": false,
                  "error": {
                    "code": "PAYLOAD_TOO_LARGE",
                    "message": "request body too large"
                  }
                }
              }
            }
          }
        }
      },
      "UnsupportedMediaType": {
        "description": "`UNSUPPORTED_MEDIA_TYPE` — the request has a body whose `Content-Type` is not `application/json`. Checked right after the header-presence check and BEFORE the signature, so a wrong Content-Type never counts as a signature failure. Send `Content-Type: application/json` and sign the raw JSON bytes.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "UNSUPPORTED_MEDIA_TYPE": {
                "summary": "Wrong Content-Type",
                "value": {
                  "success": false,
                  "error": {
                    "code": "UNSUPPORTED_MEDIA_TYPE",
                    "message": "send application/json"
                  }
                }
              }
            }
          }
        }
      },
      "InternalError": {
        "description": "`INTERNAL_ERROR` — unexpected server error. Safe to retry with the same body (and the same `Idempotency-Key` / `reference` where applicable); quote `X-Request-Id` to partners@fluxusforge.in if it persists.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "INTERNAL_ERROR": {
                "summary": "Server error",
                "value": {
                  "success": false,
                  "error": {
                    "code": "INTERNAL_ERROR",
                    "message": "internal error"
                  }
                }
              }
            }
          }
        }
      },
      "CaseNotFound": {
        "description": "`CASE_NOT_FOUND` — no case for that `sourceLoanNumber` in your organisation. Also returned for another organisation's loan number (there is no existence oracle).",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "CASE_NOT_FOUND": {
                "summary": "Unknown loan",
                "value": {
                  "success": false,
                  "error": {
                    "code": "CASE_NOT_FOUND",
                    "message": "case not found"
                  }
                }
              }
            }
          }
        }
      },
      "StatementNotFound": {
        "description": "`STATEMENT_NOT_FOUND` — there is no finalized statement for that month: it has not been billed / closed yet (not an error — just \"not billed yet\"), or it is outside your billing history.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "STATEMENT_NOT_FOUND": {
                "summary": "Month not finalized",
                "value": {
                  "success": false,
                  "error": {
                    "code": "STATEMENT_NOT_FOUND",
                    "message": "no finalized statement for this month"
                  }
                }
              }
            }
          }
        }
      },
      "NoInvoice": {
        "description": "`NO_INVOICE` — the month is finalized but no invoice number was allocated when it was finalized. This is NOT transient: retrying will not help. Write to partners@fluxusforge.in quoting the month and `X-Request-Id`. In this state `GET /billing/statements` and `GET /billing/statements/{month}` return the statement with `invoice: null`.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "NO_INVOICE": {
                "summary": "Invoice number not allocated",
                "value": {
                  "success": false,
                  "error": {
                    "code": "NO_INVOICE",
                    "message": "statement has no invoice number"
                  }
                }
              }
            }
          }
        }
      },
      "InvalidMonth": {
        "description": "`VALIDATION_FAILED` — `month` is not `YYYY-MM` with a month of 01–12.",
        "headers": {
          "X-Request-Id": {
            "$ref": "#/components/headers/XRequestId"
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "examples": {
              "VALIDATION_FAILED": {
                "summary": "Bad month",
                "value": {
                  "success": false,
                  "error": {
                    "code": "VALIDATION_FAILED",
                    "message": "request body failed validation",
                    "details": [
                      {
                        "field": "month",
                        "reason": "must match pattern \"^\\d{4}-(0[1-9]|1[0-2])$\""
                      }
                    ]
                  }
                }
              }
            }
          }
        }
      }
    },
    "schemas": {
      "Error": {
        "type": "object",
        "description": "Envelope returned by every 4xx/5xx response of this API. `error.code` is stable and machine-readable; `error.message` is human text and may change. Some codes add extra fields to `error` (e.g. `details[]` on `VALIDATION_FAILED`, `caseId` on `DUPLICATE_CONFIRMATION`, `retryAfter` on `RATE_LIMITED`). Every response also carries an `X-Request-Id` header — quote it when contacting partners@fluxusforge.in.",
        "required": [
          "success",
          "error"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              false
            ],
            "example": false
          },
          "error": {
            "type": "object",
            "required": [
              "code",
              "message"
            ],
            "additionalProperties": true,
            "properties": {
              "code": {
                "type": "string",
                "description": "Machine-readable error code. HTTP status in brackets: UNAUTHORIZED (401), SIGNATURE_INVALID (401), TIMESTAMP_SKEW (401), LENDER_INACTIVE (403), SANDBOX_ONLY (403), UNKNOWN_LENDER (403), PAYMENT_MODE_MISMATCH (403), CASE_NOT_FOUND (404), DELIVERY_NOT_FOUND (404), STATEMENT_NOT_FOUND (404), DUPLICATE_CONFIRMATION (409), CASE_ALREADY_COLLECTED (409), AMOUNT_EXCEEDS_OUTSTANDING (409), CASE_CLOSED (409), NO_INVOICE (409, not transient — contact support), PAYLOAD_TOO_LARGE (413), TOO_MANY_ROWS (413), UNSUPPORTED_MEDIA_TYPE (415), VALIDATION_FAILED (422), CALLBACK_NOT_CONFIGURED (422), AUTH_LOCKED (429), RATE_LIMITED (429), INTERNAL_ERROR (500), FEATURE_DISABLED (503).",
                "enum": [
                  "UNAUTHORIZED",
                  "SIGNATURE_INVALID",
                  "TIMESTAMP_SKEW",
                  "LENDER_INACTIVE",
                  "SANDBOX_ONLY",
                  "AUTH_LOCKED",
                  "RATE_LIMITED",
                  "VALIDATION_FAILED",
                  "PAYLOAD_TOO_LARGE",
                  "UNSUPPORTED_MEDIA_TYPE",
                  "FEATURE_DISABLED",
                  "TOO_MANY_ROWS",
                  "UNKNOWN_LENDER",
                  "CASE_NOT_FOUND",
                  "PAYMENT_MODE_MISMATCH",
                  "DUPLICATE_CONFIRMATION",
                  "CASE_ALREADY_COLLECTED",
                  "AMOUNT_EXCEEDS_OUTSTANDING",
                  "CASE_CLOSED",
                  "CALLBACK_NOT_CONFIGURED",
                  "DELIVERY_NOT_FOUND",
                  "STATEMENT_NOT_FOUND",
                  "NO_INVOICE",
                  "INTERNAL_ERROR"
                ],
                "example": "VALIDATION_FAILED"
              },
              "message": {
                "type": "string",
                "description": "Human-readable explanation. Not stable — do not branch on it.",
                "example": "request body failed validation"
              },
              "details": {
                "type": "array",
                "description": "Present on `422 VALIDATION_FAILED` when a JSON-schema check of the body, path or query failed. It holds ONE entry — the first violation found (validation stops there); fix it and retry to see the next one. Absent for malformed JSON (message `malformed request body (send valid JSON)`) and for service-level checks such as `payments/confirm` rejecting `mode: cash`, an unparseable `paidAt` or an amount that rounds to 0.",
                "items": {
                  "$ref": "#/components/schemas/ErrorDetail"
                }
              },
              "caseId": {
                "type": "string",
                "description": "Present on `409 DUPLICATE_CONFIRMATION`: the case this loan currently resolves to (its active case, otherwise the most recent one) — not necessarily the case the earlier confirmation was booked against.",
                "example": "CC-2026-7K3M9QA"
              },
              "retryAfter": {
                "type": "integer",
                "description": "Present on `429 RATE_LIMITED`: seconds until the limiter admits another request (mirrors the `Retry-After` header).",
                "example": 12
              }
            }
          }
        },
        "example": {
          "success": false,
          "error": {
            "code": "VALIDATION_FAILED",
            "message": "request body failed validation",
            "details": [
              {
                "field": "rows",
                "reason": "must NOT have fewer than 1 items"
              }
            ]
          }
        }
      },
      "ErrorDetail": {
        "type": "object",
        "required": [
          "field",
          "reason"
        ],
        "properties": {
          "field": {
            "type": "string",
            "description": "Dotted path of the offending field (e.g. `rows`, `amount`), or `body` when the failure is not attributable to one field.",
            "example": "amount"
          },
          "reason": {
            "type": "string",
            "description": "Validator message for that field.",
            "example": "must be > 0"
          }
        }
      },
      "Row": {
        "type": "object",
        "description": "One loan / borrower to work in the field. Required: `sourceLoanNumber`, `borrower.name`, `borrower.phone`, the borrower's address — `borrower.address.line1` (or the single-line `borrower.address.full`), `city`, `state`, `pincode` — the real `borrower.address.latitude` / `longitude` of that address, and `loan.outstandingAmount`. Unknown fields are ignored. Rows are validated individually — a bad row is reported in `errors[]` and never fails the batch; a row that imported but needs attention is listed in `warnings[]`.\n\n**Coordinates** — WGS84 decimal degrees with at least 4 decimal places (6 recommended), inside India, not `0,0`, not swapped; send them as strings (`\"12.975326\"`) so trailing zeros survive JSON. They become the case pin (precision `org_supplied`) at once and drive partner matching, the check-in geofence and distance-based partner pay; Fieldproof's geocoding never overwrites them. Exception: if one of our partners has physically verified the address on a visit (on-site GPS), that verified pin is kept on later re-pushes unless the address itself changes. Every rule is listed on `RowAddress`.\n\n**Grace period** — Fieldproof ops can put your organisation on a coordinate grace period (optionally with an end date). While it runs, rows with BOTH coordinates absent — omitted, empty or a placeholder such as `NA` — (and/or a missing `line1` / `city` / `state`, or an unrecognised `state`) still import — placed from the pincode / street address as before, and re-placed from the new address when it changes — and are listed in `warnings[]`. Half or malformed coordinates are always errors. Grace ends automatically at its end date; the default for every organisation is enforced.\n\n**Re-push semantics** — sending a row for an existing ACTIVE case updates it in place (outstanding, dpd, address, …); different coordinates move the pin and count as an update. Omitted `loan.dpd` and `loan.lateCharges` reset to 0; every other optional field is preserved when omitted; nothing can be cleared to `null`. If the loan's previous case is closed (`collected` / `closed_unrecovered`), a re-push opens a FRESH case (new `caseId`, event `sequence` restarts at 1).\n\n**In-batch duplicates** — if the same `sourceLoanNumber` appears more than once in one batch, the first row is kept and each later duplicate is reported as a per-row error (visible on a dry run).\n\nAll money values are whole INR rupees (never paise); the server rounds to integers.",
        "required": [
          "sourceLoanNumber",
          "borrower",
          "loan"
        ],
        "additionalProperties": true,
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "maxLength": 64,
            "description": "Your loan / account number — the primary key of the case within your organisation (unique per org). Used as the path parameter of the per-case endpoints; percent-encode it there if it contains reserved characters such as `/`.",
            "example": "LN-2026-000123"
          },
          "borrower": {
            "$ref": "#/components/schemas/RowBorrower"
          },
          "loan": {
            "$ref": "#/components/schemas/RowLoan"
          }
        },
        "example": {
          "sourceLoanNumber": "LN-2026-000123",
          "borrower": {
            "name": "Ravi Sharma",
            "phone": "9876543210",
            "email": "ravi.sharma@example.com",
            "language": "hi",
            "employerName": "Acme Textiles Pvt Ltd",
            "address": {
              "line1": "12 MG Road",
              "line2": "Near Trinity Metro",
              "landmark": "Opp. Garuda Mall",
              "city": "Bengaluru",
              "state": "Karnataka",
              "pincode": "560001",
              "latitude": "12.975326",
              "longitude": "77.606262"
            }
          },
          "loan": {
            "outstandingAmount": 18500,
            "dpd": 45,
            "loanAmount": 50000,
            "disbursedAmount": 48500,
            "emiAmount": 4500,
            "lateCharges": 500,
            "interestRate": 24,
            "tenure": 12,
            "tenureUnit": "months",
            "totalRepayable": 54000,
            "totalCollected": 35500,
            "productName": "Personal Loan",
            "nextDueDate": "2026-08-05",
            "disbursedDate": "2025-09-01"
          }
        }
      },
      "RowBorrower": {
        "type": "object",
        "required": [
          "name",
          "phone",
          "address"
        ],
        "additionalProperties": true,
        "properties": {
          "name": {
            "type": "string",
            "description": "Borrower's full name (required).",
            "example": "Ravi Sharma"
          },
          "phone": {
            "type": "string",
            "description": "Borrower's mobile number (required). Leading `+91`, `91` or `0` prefixes are stripped; the result must be a 10-digit Indian mobile number.",
            "example": "9876543210"
          },
          "email": {
            "type": "string",
            "format": "email",
            "description": "Optional e-mail address.",
            "example": "ravi.sharma@example.com"
          },
          "language": {
            "type": "string",
            "description": "Optional preferred language of the borrower.",
            "example": "hi"
          },
          "employerName": {
            "type": "string",
            "description": "Optional employer name.",
            "example": "Acme Textiles Pvt Ltd"
          },
          "address": {
            "$ref": "#/components/schemas/RowAddress"
          }
        }
      },
      "RowAddress": {
        "type": "object",
        "description": "The borrower's postal address AND the real coordinates of that address. Required: `line1` (or `full`), `city`, `state`, `pincode`, `latitude`, `longitude`. A broken rule is a per-row error in `errors[]` (reason prefixed `Row N (LOAN): `) unless your organisation is on a coordinate grace period (see `Row`).\n\n**Coordinate rules**\n\n* WGS84 decimal degrees, as a numeric string or a JSON number — not degrees-minutes-seconds or hemisphere notation (a degree / minute / second mark — °, ', \", ′, ″ — or a leading / trailing N, S, E or W next to the number, such as `12.97 N`), and not a comma decimal (`12,9716`). A placeholder — empty, `NA`, `N/A`, `NULL`, `none`, `nil`, `NaN`, `unknown`, `-`, … — counts as ABSENT, not malformed (strict: \"required\" error; grace period: see `Row`). Any other non-numeric text (e.g. `TBD`) is reported as \"is not a number\".\n* At least 4 decimal places on BOTH values (≈ 11 m; 6 recommended). Decimals are counted on the text as sent — a JSON number loses trailing zeros (`12.9700` → `12.97`), so send coordinates as strings if your source has trailing zeros.\n* Inside India (latitude 6.0 – 37.5, longitude 67.5 – 97.8). A pair that lands inside India only when swapped is reported as swapped.\n* Not `0,0`.\n* Both or neither — sending only one of the two (the other absent or a placeholder) is always an error, even on a grace period.\n* The same pin (compared to 5 decimals) must not be used for rows in DIFFERENT pincodes within one batch: every such row is rejected (it looks like a default / office / branch location). The same pin on rows with the same pincode is fine (family members, one building).\n* A pin more than 50 km from Fieldproof's reference point for the pincode is NOT rejected: the row imports and comes back in `warnings[]` — please verify it is the borrower's address.",
        "required": [
          "city",
          "state",
          "pincode",
          "latitude",
          "longitude"
        ],
        "anyOf": [
          {
            "title": "line1",
            "required": [
              "line1"
            ]
          },
          {
            "title": "full (single-line address)",
            "required": [
              "full"
            ]
          }
        ],
        "additionalProperties": true,
        "properties": {
          "line1": {
            "type": "string",
            "minLength": 5,
            "description": "House / flat / building number and street. Required unless `full` is sent. At least 5 characters, must contain a letter, and must not be a placeholder (`NA`, `N/A`, `-`, `null`, `none`, `nil`, `unknown`, …).",
            "example": "12 MG Road"
          },
          "line2": {
            "type": "string",
            "description": "Optional second address line.",
            "example": "Near Trinity Metro"
          },
          "landmark": {
            "type": "string",
            "description": "Optional landmark to help the field partner find the door.",
            "example": "Opp. Garuda Mall"
          },
          "full": {
            "type": "string",
            "minLength": 5,
            "description": "Optional single-line address, accepted in place of `line1` (same rules: at least 5 characters, contains a letter, not a placeholder). Stored alongside `line1` when both are sent.",
            "example": "12 MG Road, Near Trinity Metro, Bengaluru 560001"
          },
          "city": {
            "type": "string",
            "minLength": 2,
            "description": "City / town (required). At least 2 characters, must contain a letter, not a placeholder.",
            "example": "Bengaluru"
          },
          "state": {
            "type": "string",
            "description": "Indian state or union territory (required): its full name or its 2-letter code (`KA`, `MH`, `DL`, `TN`, `TS` / `TG`, `UP`, `WB`, …). Case, spacing and punctuation are ignored (`Tamilnadu`, `J & K`, `U.P.`, `Andhra-Pradesh`), and legacy names and common misspellings are recognised (`Orissa`, `Pondicherry`, `NCT of Delhi`, `New Delhi`, `Chattisgarh`, `Telengana`, `Uttrakhand`, `Maharastra`, `Gujrat`, `Bengal`, …). Stored as sent. A placeholder (`NA`, `-`, …) counts as missing; an unrecognised value is a per-row error.",
            "example": "Karnataka"
          },
          "pincode": {
            "type": "string",
            "pattern": "^[0-9]{6}$",
            "description": "6-digit Indian PIN code (required). Drives field-partner routing and the 50 km plausibility check on your coordinates.",
            "example": "560001"
          },
          "latitude": {
            "description": "Latitude of the borrower's address, WGS84 decimal degrees (required) — a numeric string (recommended, keeps trailing zeros: `\"12.975326\"`) or a JSON number. At least 4 decimal places counted on the text as sent (6 recommended); inside India together with `longitude`; not `0,0`. Send the coordinates of the door, not a rounded, city-level, default or office point. A placeholder such as `NA` or `-` counts as absent. See the coordinate rules above.",
            "oneOf": [
              {
                "type": "string",
                "pattern": "^[+-]?[0-9]+\\.[0-9]{4,}$"
              },
              {
                "type": "number",
                "minimum": 6,
                "maximum": 37.5
              }
            ],
            "example": "12.975326"
          },
          "longitude": {
            "description": "Longitude of the borrower's address, WGS84 decimal degrees (required) — a numeric string (recommended: `\"77.606262\"`) or a JSON number. Same rules as `latitude`; the India range is 67.5 – 97.8.",
            "oneOf": [
              {
                "type": "string",
                "pattern": "^[+-]?[0-9]+\\.[0-9]{4,}$"
              },
              {
                "type": "number",
                "minimum": 67.5,
                "maximum": 97.8
              }
            ],
            "example": "77.606262"
          }
        },
        "example": {
          "line1": "12 MG Road",
          "line2": "Near Trinity Metro",
          "landmark": "Opp. Garuda Mall",
          "city": "Bengaluru",
          "state": "Karnataka",
          "pincode": "560001",
          "latitude": "12.975326",
          "longitude": "77.606262"
        }
      },
      "RowLoan": {
        "type": "object",
        "required": [
          "outstandingAmount"
        ],
        "additionalProperties": true,
        "properties": {
          "outstandingAmount": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true,
            "description": "Amount to collect, whole INR rupees, must be > 0 (required). Rounded to an integer server-side.",
            "example": 18500
          },
          "dpd": {
            "description": "Days past due. Either a number or a `\"lo-hi\"` range string (e.g. `\"61-90\"`) — a range resolves to its upper bound. Omitting `dpd` on a re-push resets it to 0. A present-but-unparseable value is a per-row error. Fieldproof derives a DPD bucket from this value; you do not send one.",
            "oneOf": [
              {
                "type": "number",
                "minimum": 0
              },
              {
                "type": "string",
                "pattern": "^[0-9]+-[0-9]+$"
              }
            ],
            "example": 45
          },
          "loanAmount": {
            "type": "number",
            "description": "Sanctioned loan amount, whole INR rupees.",
            "example": 50000
          },
          "disbursedAmount": {
            "type": "number",
            "description": "Amount actually disbursed, whole INR rupees.",
            "example": 48500
          },
          "emiAmount": {
            "type": "number",
            "description": "Instalment amount, whole INR rupees.",
            "example": 4500
          },
          "lateCharges": {
            "type": "number",
            "description": "Accrued late charges, whole INR rupees. Omitting `lateCharges` on a re-push resets it to 0.",
            "example": 500
          },
          "interestRate": {
            "type": "number",
            "description": "Interest rate as a number.",
            "example": 24
          },
          "tenure": {
            "type": "number",
            "description": "Loan tenure (see `tenureUnit`).",
            "example": 12
          },
          "tenureUnit": {
            "type": "string",
            "description": "Unit of `tenure` as a free-text string.",
            "example": "months"
          },
          "totalRepayable": {
            "type": "number",
            "description": "Total repayable over the life of the loan, whole INR rupees.",
            "example": 54000
          },
          "totalCollected": {
            "type": "number",
            "description": "Amount already collected by you before hand-over, whole INR rupees.",
            "example": 35500
          },
          "productName": {
            "type": "string",
            "description": "Product name shown to the field partner.",
            "example": "Personal Loan"
          },
          "nextDueDate": {
            "type": "string",
            "description": "Next due date. Accepted formats: `YYYY-MM-DD`, ISO 8601 datetime, `DD-MM-YYYY`, `DD/MM/YYYY`, `DD-Mon-YY` (e.g. `28-Apr-26`). Parsed in UTC. A present-but-unparseable value is a per-row error.",
            "example": "2026-08-05"
          },
          "disbursedDate": {
            "type": "string",
            "description": "Disbursal date. Same accepted formats as `nextDueDate`; parsed in UTC. A present-but-unparseable value is a per-row error.",
            "example": "2025-09-01"
          }
        }
      },
      "PushRequest": {
        "type": "object",
        "required": [
          "rows"
        ],
        "additionalProperties": false,
        "properties": {
          "fullSnapshot": {
            "type": "boolean",
            "default": false,
            "description": "Set `true` to assert that this batch is your COMPLETE open book. Active cases whose `sourceLoanNumber` does not appear in the batch are flagged for Fieldproof ops review (`snapshot_dropped`) — a loan that appears only on a row rejected for a data error (e.g. missing coordinates) still counts as present and is not flagged; you receive only the count in `summary.flaggedNeedsReview`. A full snapshot MUST be sent as ONE batch (chunking would flag every case missing from each chunk); use it daily or weekly, never for incremental pushes."
          },
          "rows": {
            "type": "array",
            "minItems": 1,
            "maxItems": 20000,
            "description": "1 – 20,000 rows (more → `413 TOO_MANY_ROWS`). Keep batches ≤ 5,000 rows for fast responses.",
            "items": {
              "$ref": "#/components/schemas/Row"
            }
          }
        },
        "example": {
          "fullSnapshot": false,
          "rows": [
            {
              "sourceLoanNumber": "LN-2026-000123",
              "borrower": {
                "name": "Ravi Sharma",
                "phone": "9876543210",
                "email": "ravi.sharma@example.com",
                "language": "hi",
                "employerName": "Acme Textiles Pvt Ltd",
                "address": {
                  "line1": "12 MG Road",
                  "line2": "Near Trinity Metro",
                  "landmark": "Opp. Garuda Mall",
                  "city": "Bengaluru",
                  "state": "Karnataka",
                  "pincode": "560001",
                  "latitude": "12.975326",
                  "longitude": "77.606262"
                }
              },
              "loan": {
                "outstandingAmount": 18500,
                "dpd": 45,
                "loanAmount": 50000,
                "disbursedAmount": 48500,
                "emiAmount": 4500,
                "lateCharges": 500,
                "interestRate": 24,
                "tenure": 12,
                "tenureUnit": "months",
                "totalRepayable": 54000,
                "totalCollected": 35500,
                "productName": "Personal Loan",
                "nextDueDate": "2026-08-05",
                "disbursedDate": "2025-09-01"
              }
            },
            {
              "sourceLoanNumber": "LN-2026-000124",
              "borrower": {
                "name": "Priya Nair",
                "phone": "9123456789",
                "address": {
                  "line1": "Flat 4B, Sea View Apartments",
                  "city": "Kochi",
                  "state": "Kerala",
                  "pincode": "682001",
                  "latitude": "9.965389",
                  "longitude": "76.242083"
                }
              },
              "loan": {
                "outstandingAmount": 8200,
                "dpd": "61-90"
              }
            }
          ]
        }
      },
      "PushSummary": {
        "type": "object",
        "required": [
          "totalRowsInCsv",
          "validRows",
          "created",
          "updatedSnapshot",
          "unchanged",
          "flaggedNeedsReview",
          "errored",
          "warned"
        ],
        "properties": {
          "totalRowsInCsv": {
            "type": "integer",
            "description": "Rows received in this batch (the field name is historical — the same importer serves CSV uploads).",
            "example": 3
          },
          "validRows": {
            "type": "integer",
            "description": "Rows that passed row-level validation.",
            "example": 2
          },
          "created": {
            "type": "integer",
            "description": "New cases opened by this batch (each emits `case.received`).",
            "example": 1
          },
          "updatedSnapshot": {
            "type": "integer",
            "description": "Existing active cases updated in place.",
            "example": 1
          },
          "unchanged": {
            "type": "integer",
            "description": "Rows whose data matched the current case snapshot — no change written.",
            "example": 0
          },
          "flaggedNeedsReview": {
            "type": "integer",
            "description": "With `fullSnapshot:true`: active cases absent from the batch that were flagged for ops review (`snapshot_dropped`). Otherwise 0.",
            "example": 0
          },
          "errored": {
            "type": "integer",
            "description": "Rows rejected individually. This is the true count; `errors[]` lists at most 50 of them.",
            "example": 1
          },
          "warned": {
            "type": "integer",
            "description": "Number of ROWS that were imported (on a dry run: would be) with at least one warning. `warnings[]` holds one entry per warning — a row can have several (e.g. during a grace period a row missing both `city` and coordinates gets two entries) — and is capped at 50, so `summary.warned` can be smaller or larger than `warnings.length`.",
            "example": 1
          }
        }
      },
      "PushRowError": {
        "type": "object",
        "description": "One entry of `errors[]` (a rejected row) or `warnings[]` (a row that was imported but needs your attention).",
        "required": [
          "index",
          "reason"
        ],
        "properties": {
          "index": {
            "type": "integer",
            "description": "0-based position of the row in `rows[]` (`null` only for a rare database write failure that could not be traced back to a row).",
            "example": 2,
            "nullable": true
          },
          "sourceLoanNumber": {
            "type": "string",
            "nullable": true,
            "description": "The row's `sourceLoanNumber`, when it was present.",
            "example": "LN-2026-000125"
          },
          "reason": {
            "type": "string",
            "description": "Why the row was rejected (`errors[]`) or flagged (`warnings[]`). Usually prefixed `Row N (LOAN): `; the prefix is `Row N: ` when the row has no usable `sourceLoanNumber`, and a rare database write failure starts with `DB write failed`. Do not parse this text — use `index` / `sourceLoanNumber`.",
            "example": "Row 2 (LN-2026-000125): borrower.address.latitude/longitude need at least 4 decimal places (≈11 m) — got 12.97, 77.6. Send the coordinates of the door, not a rounded or city-level point"
          }
        }
      },
      "PushResponse": {
        "type": "object",
        "required": [
          "success",
          "dryRun",
          "batchId",
          "idempotentReplay",
          "summary",
          "errors",
          "warnings"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "dryRun": {
            "type": "boolean",
            "description": "`true` when the request was sent with `?dryRun=1` — validated only, nothing written, no events emitted."
          },
          "batchId": {
            "type": "string",
            "description": "Identifier of this batch. Quote it to partners@fluxusforge.in when asking about an import.",
            "example": "66c1f0a2b3c4d5e6f7a8b9c0"
          },
          "idempotentReplay": {
            "type": "boolean",
            "description": "`true` when the batch content-hash matched an already COMMITTED batch and EVERY `sourceLoanNumber` in it (rejected rows included) currently has a live case: nothing was written and `summary`, `errors[]` and `warnings[]` are the original result. If any loan in the batch has no live case — its case was collected, closed or recalled, or its row was rejected so no case was ever created — the batch is processed normally and this is `false`. A batch committed under strict address rules and re-sent unchanged after your organisation's coordinate grace period starts is also processed again (`false`). Distinct from the `Idempotency-Key` header replay, which returns the original body verbatim with `X-Idempotent-Replay: true`."
          },
          "summary": {
            "$ref": "#/components/schemas/PushSummary"
          },
          "errors": {
            "type": "array",
            "maxItems": 50,
            "description": "Per-row rejections, capped at 50 entries. `summary.errored` is the true count.",
            "items": {
              "$ref": "#/components/schemas/PushRowError"
            }
          },
          "warnings": {
            "type": "array",
            "maxItems": 50,
            "description": "Rows that WERE imported (on a dry run: would be) but need your attention — a pin more than 50 km from Fieldproof's reference point for the pincode, or, while your organisation is on a coordinate grace period, missing coordinates / address fields that become errors when the grace ends. Same item shape as `errors[]`, one entry per warning (a row can appear more than once); capped at 50 entries. `summary.warned` counts the ROWS with at least one warning.",
            "items": {
              "$ref": "#/components/schemas/PushRowError"
            }
          }
        },
        "example": {
          "success": true,
          "dryRun": false,
          "batchId": "66c1f0a2b3c4d5e6f7a8b9c0",
          "idempotentReplay": false,
          "summary": {
            "totalRowsInCsv": 4,
            "validRows": 3,
            "created": 2,
            "updatedSnapshot": 1,
            "unchanged": 0,
            "flaggedNeedsReview": 0,
            "errored": 1,
            "warned": 1
          },
          "errors": [
            {
              "index": 2,
              "sourceLoanNumber": "LN-2026-000125",
              "reason": "Row 2 (LN-2026-000125): borrower.address.latitude/longitude need at least 4 decimal places (≈11 m) — got 12.97, 77.6. Send the coordinates of the door, not a rounded or city-level point"
            }
          ],
          "warnings": [
            {
              "index": 3,
              "sourceLoanNumber": "LN-2026-000126",
              "reason": "Row 3 (LN-2026-000126): borrower.address.latitude/longitude are about 62 km from our reference point for pincode 560001 — imported, but please verify they are this borrower's address"
            }
          ]
        }
      },
      "Visit": {
        "type": "object",
        "properties": {
          "visitAt": {
            "type": "string",
            "format": "date-time",
            "description": "When the visit happened."
          },
          "outcome": {
            "type": "string",
            "nullable": true,
            "description": "Visit outcome as recorded by the field partner (same vocabulary as `visit.completed.payload.outcome`), or `null`."
          },
          "amountCollected": {
            "type": "number",
            "description": "Amount the partner recorded for this visit, whole INR rupees (0 when none). In static-QR mode this is the partner's UNVERIFIED claim until Fieldproof ops verify the proof — trust `payment.collected` events for the confirmed amount."
          },
          "paymentMode": {
            "type": "string",
            "nullable": true,
            "description": "Payment mode recorded by the partner (e.g. `upi`), or `null`."
          },
          "paymentReference": {
            "type": "string",
            "nullable": true,
            "description": "UTR / reference recorded by the partner, or `null`."
          },
          "ptpDate": {
            "type": "string",
            "nullable": true,
            "description": "Promise-to-pay date (ISO 8601, IST midnight of the promised day) when the borrower promised to pay on this visit (recorded with outcome `delivered_acknowledged`), otherwise `null`."
          }
        }
      },
      "CaseSnapshot": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "status",
          "isActive",
          "totalCollected",
          "visits",
          "createdAt",
          "updatedAt"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "description": "Fieldproof case identifier. A loan gets a NEW caseId every time a closed case is re-pushed.",
            "example": "CC-2026-7K3M9QA"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "in_progress",
              "collected",
              "closed_unrecovered"
            ],
            "description": "`pending` — received, awaiting a field partner · `in_progress` — assigned / being worked · `collected` — fully collected · `closed_unrecovered` — closed without full recovery (recalled, written off, …). A case can go back from `in_progress` to `pending` (open on the marketplace again) WITHOUT any event — the partner's lease lapsed, a payment-pending or in-progress timeout, the partner declined, a cool-down release after a visit, or an ops review. Only this endpoint shows it; do not treat `in_progress` as one-way."
          },
          "isActive": {
            "type": "boolean",
            "description": "`true` while the case is open and workable."
          },
          "assignedAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When a field partner was assigned, or `null`."
          },
          "totalCollected": {
            "type": "number",
            "description": "Total collected on this case, whole INR rupees.",
            "example": 4500
          },
          "outstandingAmount": {
            "type": "number",
            "nullable": true,
            "description": "Remaining outstanding on this case, whole INR rupees.",
            "example": 14000
          },
          "visits": {
            "type": "array",
            "maxItems": 20,
            "description": "The last 20 visits, oldest first.",
            "items": {
              "$ref": "#/components/schemas/Visit"
            }
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "updatedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "CaseResponse": {
        "type": "object",
        "required": [
          "success",
          "case"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "case": {
            "$ref": "#/components/schemas/CaseSnapshot"
          }
        },
        "example": {
          "success": true,
          "case": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "status": "in_progress",
            "isActive": true,
            "assignedAt": "2026-08-12T04:10:22.000Z",
            "totalCollected": 4500,
            "outstandingAmount": 14000,
            "visits": [
              {
                "visitAt": "2026-08-14T09:32:00.000Z",
                "outcome": "partial",
                "amountCollected": 4500,
                "paymentMode": "upi",
                "paymentReference": "UPI/512345678901",
                "ptpDate": null
              }
            ],
            "createdAt": "2026-08-11T18:30:00.000Z",
            "updatedAt": "2026-08-14T09:35:12.000Z"
          }
        }
      },
      "RecallRequest": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string",
            "maxLength": 200,
            "description": "Optional free-text reason (≤ 200 chars) recorded on the case history.",
            "example": "Borrower settled directly with us"
          }
        },
        "example": {
          "reason": "Borrower settled directly with us"
        },
        "description": "Optional body fields — `{}` is fine. Unknown fields are silently dropped."
      },
      "RecallResponse": {
        "type": "object",
        "required": [
          "success",
          "alreadyClosed",
          "caseId",
          "status"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "alreadyClosed": {
            "type": "boolean",
            "description": "`false` — this call closed the case (a `case.closed` event with `reason: recalled` was emitted). `true` — the case was already terminal; `status` shows its existing state and nothing changed."
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "in_progress",
              "collected",
              "closed_unrecovered"
            ],
            "description": "`closed_unrecovered` on a fresh recall; the existing terminal status when `alreadyClosed` is `true`."
          }
        },
        "example": {
          "success": true,
          "alreadyClosed": false,
          "caseId": "CC-2026-7K3M9QA",
          "status": "closed_unrecovered"
        }
      },
      "ConfirmRequest": {
        "type": "object",
        "description": "Body of a gateway-payment confirmation. Unknown fields are silently dropped (not rejected).",
        "required": [
          "amount",
          "reference"
        ],
        "additionalProperties": false,
        "properties": {
          "amount": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true,
            "maximum": 1000000000,
            "description": "Captured amount in whole INR rupees (> 0, ≤ 1,000,000,000). Never paise — a `₹4,500` capture is `4500`. Rounded to the nearest whole rupee before booking (`4500.4` → `4500`); an amount that rounds to 0 is `422 VALIDATION_FAILED`.",
            "example": 4500
          },
          "reference": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128,
            "description": "Your gateway's payment id (surrounding whitespace is trimmed; whitespace-only is `422`). This is the idempotency key: the same (`sourceLoanNumber`, `reference`) is booked once — a repeat returns `409 DUPLICATE_CONFIRMATION`.",
            "example": "pay_Nq7Xk2Lm9RtY3z"
          },
          "paidAt": {
            "type": "string",
            "format": "date-time",
            "description": "Optional time the borrower paid (ISO 8601). Defaults to the time we receive the call. Becomes `collectedAt` (and `occurredAt`) on the resulting `payment.collected`. An unparseable value is `422 VALIDATION_FAILED` (no `details`).",
            "example": "2026-08-14T09:35:12.000Z"
          },
          "mode": {
            "type": "string",
            "maxLength": 20,
            "default": "link",
            "description": "Optional payment mode, echoed as `mode` on the resulting `payment.collected` event. Recommended values (exact, lower-case): `upi`, `card`, `netbanking`, `wallet`, `online`, `link`, `neft`, `nach`, `cheque`, `razorpay`. Any other value — including a mis-cased one such as `UPI` — is NOT rejected: it is booked and echoed as `link`. `cash` (in any letter case) is rejected with `422 VALIDATION_FAILED` (no `details`) — org_gateway confirms are online captures, so cash is never accepted here. Defaults to `link`.",
            "example": "upi"
          },
          "linkId": {
            "type": "string",
            "maxLength": 128,
            "description": "Optional: the `linkId` you returned from your mint-link endpoint for this payment.",
            "example": "plink_8Hs2kD9"
          }
        },
        "example": {
          "amount": 4500,
          "reference": "pay_Nq7Xk2Lm9RtY3z",
          "paidAt": "2026-08-14T09:35:12.000Z",
          "mode": "upi",
          "linkId": "plink_8Hs2kD9"
        }
      },
      "ConfirmResponse": {
        "type": "object",
        "required": [
          "success",
          "caseId",
          "amount",
          "outstandingAfter",
          "status"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "amount": {
            "type": "number",
            "description": "Amount booked, whole INR rupees (your `amount` rounded to the nearest rupee).",
            "example": 4500
          },
          "outstandingAfter": {
            "type": "number",
            "description": "Remaining outstanding on the case after this booking, whole INR rupees.",
            "example": 14000
          },
          "status": {
            "type": "string",
            "enum": [
              "in_progress",
              "collected"
            ],
            "description": "`collected` when this booking cleared the case (amount ≥ 99% of the remaining outstanding); otherwise `in_progress`."
          }
        },
        "example": {
          "success": true,
          "caseId": "CC-2026-7K3M9QA",
          "amount": 4500,
          "outstandingAfter": 14000,
          "status": "in_progress"
        }
      },
      "EventEnvelopeBase": {
        "type": "object",
        "description": "Fields common to every event. The webhook body and the poll-feed item are identical.",
        "required": [
          "eventId",
          "type",
          "occurredAt",
          "version",
          "lenderCode",
          "sourceLoanNumber",
          "sequence",
          "payload"
        ],
        "properties": {
          "eventId": {
            "type": "string",
            "pattern": "^evt_[0-9a-f]{24}$",
            "description": "Globally unique event id (`evt_<24 hex>`). Deliveries are at-least-once — dedupe on this.",
            "example": "evt_66c1f2a9d4e5f60718293a4b"
          },
          "type": {
            "type": "string",
            "enum": [
              "case.received",
              "case.assigned",
              "visit.completed",
              "payment.collected",
              "case.closed"
            ],
            "description": "Event type. Default subscription: `case.received`, `payment.collected`, `case.closed`; the others are opt-in via Fieldproof ops (there is no self-serve subscription API yet). The poll feed carries ALL types regardless of subscription. (`verification.completed` belongs to the separate address-verification product and is never emitted for collection cases.)"
          },
          "occurredAt": {
            "type": "string",
            "format": "date-time",
            "description": "When the underlying change happened."
          },
          "version": {
            "type": "integer",
            "enum": [
              1
            ],
            "description": "Envelope version. Currently always 1."
          },
          "lenderCode": {
            "type": "string",
            "description": "Your organisation code.",
            "example": "YOURORG"
          },
          "sourceLoanNumber": {
            "type": "string",
            "description": "Your loan number.",
            "example": "LN-2026-000123"
          },
          "sequence": {
            "type": "integer",
            "minimum": 1,
            "description": "Per-CASE ordering number starting at 1. `sequence` is per **case** (not per loan) and starts at 1 for every new case — a loan whose case closed and was re-pushed gets a NEW `caseId` and restarts at 1, so key your watermark on (`sourceLoanNumber`, `caseId`) or reset it when you see `case.received`. Sequence counts ALL event types including ones you are not subscribed to, so default subscribers legitimately see gaps (e.g. 1 → 4). Apply any event whose sequence is greater than your watermark — gaps are normal, never wait for them to fill; on a gap you may reconcile via `GET /api/v1/partner/cases/{sourceLoanNumber}`. Never skip a `payment.collected` because of ordering: book it (idempotent on `eventId` / `reference`) and gate only your case-state fields."
          },
          "payload": {
            "type": "object",
            "description": "Type-specific payload — see the per-type schemas."
          }
        }
      },
      "CaseReceivedPayload": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "status"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending"
            ]
          }
        }
      },
      "CaseAssignedPayload": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "assignedAt"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "assignedAt": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "VisitCompletedPayload": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "outcome",
          "visitAt",
          "ptpDate",
          "notes"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "outcome": {
            "type": "string",
            "enum": [
              "delivered_acknowledged",
              "collected",
              "partial",
              "rtp",
              "refused",
              "not_available",
              "wrong_address",
              "shifted"
            ],
            "description": "`delivered_acknowledged` — the borrower was reached and acknowledged; when they promised to pay, `ptpDate` carries the promised date (a promise-to-pay always arrives this way — there is no `ptp` outcome; it was retired before this event existed and is never sent) · `rtp` = refuse to pay."
          },
          "visitAt": {
            "type": "string",
            "format": "date-time"
          },
          "ptpDate": {
            "type": "string",
            "nullable": true,
            "description": "Promised payment date (`YYYY-MM-DD`) when the borrower promised to pay — sent with outcome `delivered_acknowledged`; otherwise `null`."
          },
          "notes": {
            "type": "string",
            "nullable": true,
            "description": "Field partner's notes (truncated to 500 characters), or `null`."
          }
        }
      },
      "PaymentCollectedPayload": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "amount",
          "mode",
          "reference",
          "totalCollected",
          "outstandingAfter",
          "collectedAt"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "amount": {
            "type": "number",
            "description": "INCREMENTAL amount of this payment, whole INR rupees. In static-QR mode this is the operator-confirmed amount (it may differ from the partner's claim — trust the event).",
            "example": 4500
          },
          "mode": {
            "type": "string",
            "enum": [
              "upi",
              "card",
              "netbanking",
              "wallet",
              "online",
              "link",
              "neft",
              "nach",
              "cheque",
              "razorpay",
              "other"
            ],
            "description": "org_gateway confirmations echo the `mode` you sent (default `link`; an unrecognised or mis-cased value becomes `link`); static-QR verifications carry the partner-recorded mode (usually `upi`). A payment Fieldproof's collection team recorded on the case carries the recorded mode when it is in this list, otherwise `other` (e.g. `cash`, `imps`). `other` is also used when the team closed the case directly with an amount (`reference` is then `null`)."
          },
          "reference": {
            "type": "string",
            "nullable": true,
            "description": "UTR / gateway payment id (for a collection-team payment, the reference they entered), or `null`.",
            "example": "UPI/512345678901"
          },
          "totalCollected": {
            "type": "number",
            "description": "ABSOLUTE total collected on the case after this payment, whole INR rupees.",
            "example": 4500
          },
          "outstandingAfter": {
            "type": "number",
            "description": "ABSOLUTE remaining outstanding on the case after this payment, whole INR rupees.",
            "example": 14000
          },
          "collectedAt": {
            "type": "string",
            "format": "date-time",
            "description": "When the payment happened according to its source — NOT when Fieldproof booked it. Static QR: the field partner's visit check-out time; org_gateway: the `paidAt` you sent on `payments/confirm` (the time we received the call if you omitted it); Fieldproof operations closing a case directly: the time of that close; a payment recorded by Fieldproof's collection team: the payment time they entered (the time of recording if none). For month-end reconciliation filter on `payload.collectedAt`, not on the poll feed's `since` (server receipt time)."
          }
        }
      },
      "CaseClosedPayload": {
        "type": "object",
        "required": [
          "sourceLoanNumber",
          "caseId",
          "status",
          "reason",
          "totalCollected"
        ],
        "properties": {
          "sourceLoanNumber": {
            "type": "string",
            "example": "LN-2026-000123"
          },
          "caseId": {
            "type": "string",
            "example": "CC-2026-7K3M9QA"
          },
          "status": {
            "type": "string",
            "enum": [
              "collected",
              "closed_unrecovered"
            ]
          },
          "reason": {
            "type": "string",
            "enum": [
              "full_settlement",
              "closed_by_operations",
              "recalled",
              "not_available",
              "refused",
              "written_off",
              "legal_handover"
            ],
            "description": "`full_settlement` and `closed_by_operations` accompany `status: collected` — `closed_by_operations` means Fieldproof operations closed the case with a balance left: closing it directly (also with no amount recorded) or force-closing it while recording a payment. Any amount they recorded arrives first as `payment.collected`. No case fee is billed for a `closed_by_operations` close. The rest accompany `closed_unrecovered` (`recalled` = you called the recall endpoint; `not_available` / `refused` = visit attempts exhausted; `written_off`; `legal_handover`)."
          },
          "totalCollected": {
            "type": "number",
            "description": "Total collected on the case at close, whole INR rupees.",
            "example": 18500
          }
        }
      },
      "PingPayload": {
        "type": "object",
        "required": [
          "message"
        ],
        "properties": {
          "message": {
            "type": "string",
            "example": "webhook connectivity test — respond 2xx and dedupe on eventId"
          }
        }
      },
      "CaseReceivedEvent": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EventEnvelopeBase"
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "case.received"
                ]
              },
              "payload": {
                "$ref": "#/components/schemas/CaseReceivedPayload"
              }
            }
          }
        ],
        "description": "A new case was opened for one of your rows (each `created` row of a committed push). Not emitted for in-place updates or dry runs.",
        "example": {
          "eventId": "evt_66c1f2a9d4e5f60718293a4b",
          "type": "case.received",
          "occurredAt": "2026-08-11T18:30:00.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 1,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "status": "pending"
          }
        }
      },
      "CaseAssignedEvent": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EventEnvelopeBase"
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "case.assigned"
                ]
              },
              "payload": {
                "$ref": "#/components/schemas/CaseAssignedPayload"
              }
            }
          }
        ],
        "description": "A field partner took the case — by accepting it from the marketplace, or by being assigned / reassigned by Fieldproof operations or from your organisation dashboard. Opt-in event.",
        "example": {
          "eventId": "evt_66c2a0b1c2d3e4f5a6b7c8d9",
          "type": "case.assigned",
          "occurredAt": "2026-08-12T04:10:22.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 2,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "assignedAt": "2026-08-12T04:10:22.000Z"
          }
        }
      },
      "VisitCompletedEvent": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EventEnvelopeBase"
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "visit.completed"
                ]
              },
              "payload": {
                "$ref": "#/components/schemas/VisitCompletedPayload"
              }
            }
          }
        ],
        "description": "The field partner completed a visit. Opt-in event. A static-QR visit that submits a payment proof emits NO `visit.completed` — the `payment.collected` that follows Fieldproof's verification is the signal.",
        "example": {
          "eventId": "evt_66c4d1e2f3a4b5c6d7e8f9a0",
          "type": "visit.completed",
          "occurredAt": "2026-08-14T09:32:00.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 3,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "outcome": "delivered_acknowledged",
            "visitAt": "2026-08-14T09:32:00.000Z",
            "ptpDate": "2026-08-20",
            "notes": "Borrower promised to pay after salary credit"
          }
        }
      },
      "PaymentCollectedEvent": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EventEnvelopeBase"
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "payment.collected"
                ]
              },
              "payload": {
                "$ref": "#/components/schemas/PaymentCollectedPayload"
              }
            }
          }
        ],
        "description": "A payment was booked against the case: an operator-verified static-QR proof, your own `payments/confirm` call (org_gateway), or a payment Fieldproof's collection team recorded on the case — through \"record payment\" (any mode; modes outside the `mode` list arrive as `other`) or while closing the case directly (mode `other`). When the same action also closes the case, this event always comes first (lower `sequence`) and `case.closed` follows. `amount` is incremental; `totalCollected` / `outstandingAfter` are absolute. Default-subscribed. Never skip this event because of ordering — book it (idempotent on `eventId` / `reference`).",
        "example": {
          "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
          "type": "payment.collected",
          "occurredAt": "2026-08-14T09:35:12.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 4,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "amount": 4500,
            "mode": "upi",
            "reference": "UPI/512345678901",
            "totalCollected": 4500,
            "outstandingAfter": 14000,
            "collectedAt": "2026-08-14T09:35:12.000Z"
          }
        }
      },
      "CaseClosedEvent": {
        "allOf": [
          {
            "$ref": "#/components/schemas/EventEnvelopeBase"
          },
          {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "case.closed"
                ]
              },
              "payload": {
                "$ref": "#/components/schemas/CaseClosedPayload"
              }
            }
          }
        ],
        "description": "The case reached a terminal state. On full clearance it follows `payment.collected` (`status: collected`, `reason: full_settlement`); on recall it carries `status: closed_unrecovered`, `reason: recalled`. Default-subscribed. Treat it as \"closed as of now\", not as a guaranteed last event: Fieldproof operations can re-open a `closed_unrecovered` case (admin review, an address correction or an attempts reset; a `collected` case is not re-opened), after which further events — and a later `case.closed` — can follow on the same `caseId`; let such an event re-open the case in your LMS. A re-opened case that closes again gets a NEW `case.closed`, even when it closes the same way, once any other event has been emitted on the case in between. A same-kind closure with no event since the previous `case.closed` is treated as a retry and not re-sent (you never saw the case re-open, so it is still closed on your side).",
        "example": {
          "eventId": "evt_66c9e5f6a7b8c9d0e1f2a3b4",
          "type": "case.closed",
          "occurredAt": "2026-08-18T11:02:45.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 6,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "status": "collected",
            "reason": "full_settlement",
            "totalCollected": 18500
          }
        }
      },
      "EventEnvelope": {
        "description": "One case event — identical whether it arrives on your webhook or in `GET /api/v1/partner/cases/updates`. Discriminated by `type`. `sequence` is per **case** (not per loan) and starts at 1 for every new case — a loan whose case closed and was re-pushed gets a NEW `caseId` and restarts at 1, so key your watermark on (`sourceLoanNumber`, `caseId`) or reset it when you see `case.received`. Sequence counts ALL event types including ones you are not subscribed to, so default subscribers legitimately see gaps (e.g. 1 → 4). Apply any event whose sequence is greater than your watermark — gaps are normal, never wait for them to fill; on a gap you may reconcile via `GET /api/v1/partner/cases/{sourceLoanNumber}`. Never skip a `payment.collected` because of ordering: book it (idempotent on `eventId` / `reference`) and gate only your case-state fields.",
        "oneOf": [
          {
            "$ref": "#/components/schemas/CaseReceivedEvent"
          },
          {
            "$ref": "#/components/schemas/CaseAssignedEvent"
          },
          {
            "$ref": "#/components/schemas/VisitCompletedEvent"
          },
          {
            "$ref": "#/components/schemas/PaymentCollectedEvent"
          },
          {
            "$ref": "#/components/schemas/CaseClosedEvent"
          }
        ],
        "discriminator": {
          "propertyName": "type",
          "mapping": {
            "case.received": "#/components/schemas/CaseReceivedEvent",
            "case.assigned": "#/components/schemas/CaseAssignedEvent",
            "visit.completed": "#/components/schemas/VisitCompletedEvent",
            "payment.collected": "#/components/schemas/PaymentCollectedEvent",
            "case.closed": "#/components/schemas/CaseClosedEvent"
          }
        },
        "example": {
          "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
          "type": "payment.collected",
          "occurredAt": "2026-08-14T09:35:12.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 4,
          "payload": {
            "sourceLoanNumber": "LN-2026-000123",
            "caseId": "CC-2026-7K3M9QA",
            "amount": 4500,
            "mode": "upi",
            "reference": "UPI/512345678901",
            "totalCollected": 4500,
            "outstandingAfter": 14000,
            "collectedAt": "2026-08-14T09:35:12.000Z"
          }
        }
      },
      "PingEvent": {
        "type": "object",
        "description": "Sent to your callback URL by `POST /api/v1/partner/webhooks/test` only — never appears in the poll feed. Same envelope shape, but `sourceLoanNumber` and `sequence` are `null` (receivers must tolerate this) and `eventId` is `evt_ping_<16 hex>`. Respond 2xx and dedupe on `eventId` like any other event.",
        "required": [
          "eventId",
          "type",
          "occurredAt",
          "version",
          "lenderCode",
          "sourceLoanNumber",
          "sequence",
          "payload"
        ],
        "properties": {
          "eventId": {
            "type": "string",
            "pattern": "^evt_ping_[0-9a-f]{16}$",
            "example": "evt_ping_9f8e7d6c5b4a3f21",
            "description": "`evt_ping_` followed by 16 lowercase hex characters."
          },
          "type": {
            "type": "string",
            "enum": [
              "ping"
            ]
          },
          "occurredAt": {
            "type": "string",
            "format": "date-time"
          },
          "version": {
            "type": "integer",
            "enum": [
              1
            ]
          },
          "lenderCode": {
            "type": "string",
            "example": "YOURORG"
          },
          "sourceLoanNumber": {
            "type": "string",
            "nullable": true,
            "description": "Always present and always `null` for ping."
          },
          "sequence": {
            "type": "integer",
            "nullable": true,
            "description": "Always present and always `null` for ping."
          },
          "payload": {
            "$ref": "#/components/schemas/PingPayload"
          }
        },
        "example": {
          "eventId": "evt_ping_9f8e7d6c5b4a3f21",
          "type": "ping",
          "occurredAt": "2026-08-18T10:00:00.000Z",
          "version": 1,
          "lenderCode": "YOURORG",
          "sourceLoanNumber": null,
          "sequence": null,
          "payload": {
            "message": "webhook connectivity test — respond 2xx and dedupe on eventId"
          }
        }
      },
      "UpdatesResponse": {
        "type": "object",
        "required": [
          "success",
          "events",
          "nextCursor",
          "hasMore"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "events": {
            "type": "array",
            "description": "Events oldest-first — ALL event types regardless of your webhook subscription.",
            "items": {
              "$ref": "#/components/schemas/EventEnvelope"
            }
          },
          "nextCursor": {
            "type": "string",
            "nullable": true,
            "description": "Opaque cursor to pass as `?cursor=` on the next call. Persist it only AFTER you have processed every event on this page. On an empty page it echoes the cursor you passed (or is `null` on a first call that found no events yet).",
            "example": "66c4d3a4b5c6d7e8f9a0b1c2"
          },
          "hasMore": {
            "type": "boolean",
            "description": "`true` when a further page is likely available — call again immediately with `nextCursor`."
          }
        },
        "example": {
          "success": true,
          "events": [
            {
              "eventId": "evt_66c1f2a9d4e5f60718293a4b",
              "type": "case.received",
              "occurredAt": "2026-08-11T18:30:00.000Z",
              "version": 1,
              "lenderCode": "YOURORG",
              "sourceLoanNumber": "LN-2026-000123",
              "sequence": 1,
              "payload": {
                "sourceLoanNumber": "LN-2026-000123",
                "caseId": "CC-2026-7K3M9QA",
                "status": "pending"
              }
            },
            {
              "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
              "type": "payment.collected",
              "occurredAt": "2026-08-14T09:35:12.000Z",
              "version": 1,
              "lenderCode": "YOURORG",
              "sourceLoanNumber": "LN-2026-000123",
              "sequence": 4,
              "payload": {
                "sourceLoanNumber": "LN-2026-000123",
                "caseId": "CC-2026-7K3M9QA",
                "amount": 4500,
                "mode": "upi",
                "reference": "UPI/512345678901",
                "totalCollected": 4500,
                "outstandingAfter": 14000,
                "collectedAt": "2026-08-14T09:35:12.000Z"
              }
            }
          ],
          "nextCursor": "66c4d3a4b5c6d7e8f9a0b1c2",
          "hasMore": false
        }
      },
      "DeliveryRow": {
        "type": "object",
        "required": [
          "eventId",
          "type",
          "status",
          "attempts",
          "createdAt"
        ],
        "properties": {
          "eventId": {
            "type": "string",
            "example": "evt_66c4d3a4b5c6d7e8f9a0b1c2"
          },
          "sourceLoanNumber": {
            "type": "string",
            "nullable": true,
            "example": "LN-2026-000123"
          },
          "sequence": {
            "type": "integer",
            "nullable": true,
            "example": 4
          },
          "type": {
            "type": "string",
            "description": "Event type of the delivered envelope.",
            "example": "payment.collected"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "in_flight",
              "delivered",
              "exhausted"
            ],
            "description": "`pending` — queued for (re)delivery · `in_flight` — a POST is in progress · `delivered` — your callback answered 2xx · `exhausted` — all 7 attempts failed, or no callback was configured / active when the delivery was due (then `attempts` is 0). The row is kept 30 days after it finishes; the event stays replayable for about 13 months."
          },
          "attempts": {
            "type": "integer",
            "description": "Attempts made so far (max 7 on the ladder 0s, 30s, 2m, 10m, 1h, 6h, 24h). Reset to 0 by a replay. `0` on an `exhausted` row means your callback was not configured / active when the delivery was due.",
            "example": 1
          },
          "nextAttemptAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When the next attempt is due while the row is `pending`. On `delivered` and `exhausted` rows it keeps its last scheduled value (it is not cleared to `null`) — ignore it unless `status` is `pending`."
          },
          "deliveredAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "lastStatusCode": {
            "type": "integer",
            "nullable": true,
            "description": "HTTP status your callback returned on the last attempt, or `null` if the connection failed.",
            "example": 200
          },
          "lastError": {
            "type": "string",
            "nullable": true,
            "description": "Transport / HTTP error of the last failed attempt, or `null`."
          },
          "replayedAt": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "When you last replayed this delivery, or `null`."
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          }
        },
        "example": {
          "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
          "sourceLoanNumber": "LN-2026-000123",
          "sequence": 4,
          "type": "payment.collected",
          "status": "delivered",
          "attempts": 1,
          "nextAttemptAt": "2026-08-14T09:35:12.900Z",
          "deliveredAt": "2026-08-14T09:35:13.412Z",
          "lastStatusCode": 200,
          "lastError": null,
          "replayedAt": null,
          "createdAt": "2026-08-14T09:35:12.900Z"
        }
      },
      "DeliveriesResponse": {
        "type": "object",
        "required": [
          "success",
          "deliveries"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "deliveries": {
            "type": "array",
            "description": "Newest first.",
            "items": {
              "$ref": "#/components/schemas/DeliveryRow"
            }
          }
        },
        "example": {
          "success": true,
          "deliveries": [
            {
              "eventId": "evt_66c9e5f6a7b8c9d0e1f2a3b4",
              "sourceLoanNumber": "LN-2026-000123",
              "sequence": 6,
              "type": "case.closed",
              "status": "exhausted",
              "attempts": 7,
              "nextAttemptAt": "2026-08-19T18:15:15.300Z",
              "deliveredAt": null,
              "lastStatusCode": 503,
              "lastError": "HTTP 503",
              "replayedAt": null,
              "createdAt": "2026-08-18T11:02:45.300Z"
            },
            {
              "eventId": "evt_66c4d3a4b5c6d7e8f9a0b1c2",
              "sourceLoanNumber": "LN-2026-000123",
              "sequence": 4,
              "type": "payment.collected",
              "status": "delivered",
              "attempts": 1,
              "nextAttemptAt": "2026-08-14T09:35:12.900Z",
              "deliveredAt": "2026-08-14T09:35:13.412Z",
              "lastStatusCode": 200,
              "lastError": null,
              "replayedAt": null,
              "createdAt": "2026-08-14T09:35:12.900Z"
            }
          ]
        }
      },
      "ReplayResponse": {
        "type": "object",
        "required": [
          "success",
          "status",
          "message"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "in_flight"
            ],
            "description": "`pending` — re-delivery queued with a fresh retry ladder. `in_flight` / `pending` with an \"already queued\" message — the delivery was already scheduled; nothing changed."
          },
          "message": {
            "type": "string",
            "example": "re-delivery queued"
          }
        },
        "example": {
          "success": true,
          "status": "pending",
          "message": "re-delivery queued"
        }
      },
      "WebhookTestResponse": {
        "type": "object",
        "required": [
          "success",
          "delivered",
          "statusCode",
          "latencyMs",
          "error",
          "bodyExcerpt"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ],
            "description": "`true` means the test RAN — check `delivered` for the result."
          },
          "delivered": {
            "type": "boolean",
            "description": "`true` when your callback answered 2xx within 10 s."
          },
          "statusCode": {
            "type": "integer",
            "description": "HTTP status your callback returned; `0` when no HTTP response was obtained (connection failure, timeout, or the URL was rejected — see `error`).",
            "example": 200
          },
          "latencyMs": {
            "type": "integer",
            "description": "Round-trip time of the ping.",
            "example": 143
          },
          "error": {
            "type": "string",
            "nullable": true,
            "description": "Transport error when the POST could not complete, otherwise `null`."
          },
          "bodyExcerpt": {
            "type": "string",
            "nullable": true,
            "description": "First 1,024 characters of your callback's response body, or `null`."
          }
        },
        "example": {
          "success": true,
          "delivered": true,
          "statusCode": 200,
          "latencyMs": 143,
          "error": null,
          "bodyExcerpt": "{\"ok\":true}"
        }
      },
      "EchoSignatureResponse": {
        "type": "object",
        "required": [
          "success",
          "canonicalString",
          "canonicalParts",
          "expectedSignature",
          "receivedSignature",
          "signatureMatches",
          "timestampWithinSkew",
          "note"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "canonicalString": {
            "type": "string",
            "description": "The exact canonical string the server built for THIS request (`METHOD\\nPATH\\nTIMESTAMP\\nRAW_BODY`). Diff it against yours.",
            "example": "POST\n/api/v1/partner/debug/echo-signature\n1755500000000\n{\"probe\":true}"
          },
          "canonicalParts": {
            "type": "object",
            "required": [
              "method",
              "path",
              "timestamp",
              "bodyBytes",
              "bodySha256"
            ],
            "properties": {
              "method": {
                "type": "string",
                "example": "POST"
              },
              "path": {
                "type": "string",
                "description": "Request path as received, without query string.",
                "example": "/api/v1/partner/debug/echo-signature"
              },
              "timestamp": {
                "type": "string",
                "description": "The `X-Fieldproof-Timestamp` value received.",
                "example": "1755500000000"
              },
              "bodyBytes": {
                "type": "integer",
                "description": "Byte length of the raw body the server received.",
                "example": 14
              },
              "bodySha256": {
                "type": "string",
                "description": "SHA-256 (hex) of the raw body bytes — compare with a hash of what you signed.",
                "example": "c775500ea34eded73c2a3c3bede193f0d839e6c14b36f21b6cc31472e0720a91"
              }
            }
          },
          "expectedSignature": {
            "type": "string",
            "description": "Lowercase-hex HMAC the server expects for this request with your secret.",
            "example": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210"
          },
          "receivedSignature": {
            "type": "string",
            "nullable": true,
            "description": "The signature header you sent (as received), or `null`.",
            "example": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
          },
          "signatureMatches": {
            "type": "boolean",
            "description": "Case-insensitive comparison of received vs expected."
          },
          "timestampWithinSkew": {
            "type": "boolean",
            "description": "`true` when the timestamp is within ±5 minutes of server time."
          },
          "note": {
            "type": "string",
            "example": "Sign hex(HMAC-SHA256(canonicalString, hmacSecret)) over the EXACT raw body bytes — do not re-serialize JSON after signing."
          }
        },
        "example": {
          "success": true,
          "canonicalString": "POST\n/api/v1/partner/debug/echo-signature\n1755500000000\n{\"probe\":true}",
          "canonicalParts": {
            "method": "POST",
            "path": "/api/v1/partner/debug/echo-signature",
            "timestamp": "1755500000000",
            "bodyBytes": 14,
            "bodySha256": "c775500ea34eded73c2a3c3bede193f0d839e6c14b36f21b6cc31472e0720a91"
          },
          "expectedSignature": "9d5b1a3fbd0e4c8a2f7e6d5c4b3a29181716151413121110fedcba9876543210",
          "receivedSignature": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
          "signatureMatches": false,
          "timestampWithinSkew": true,
          "note": "Sign hex(HMAC-SHA256(canonicalString, hmacSecret)) over the EXACT raw body bytes — do not re-serialize JSON after signing."
        }
      },
      "HealthResponse": {
        "type": "object",
        "description": "Flat object — note there is no `success` field and no `data` envelope.",
        "required": [
          "ok",
          "lenderCode",
          "env",
          "serverTime"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "lenderCode": {
            "type": "string",
            "description": "The organisation code your key is bound to.",
            "example": "YOURORG"
          },
          "env": {
            "type": "string",
            "enum": [
              "test",
              "live"
            ],
            "description": "`test` for a sandbox key, `live` for a production key."
          },
          "serverTime": {
            "type": "string",
            "format": "date-time",
            "description": "Server clock — compare with yours when debugging `TIMESTAMP_SKEW`.",
            "example": "2026-08-18T10:00:00.000Z"
          }
        },
        "example": {
          "ok": true,
          "lenderCode": "YOURORG",
          "env": "test",
          "serverTime": "2026-08-18T10:00:00.000Z"
        }
      },
      "EmptyBody": {
        "type": "object",
        "description": "No parameters. Send an empty JSON object `{}` with `Content-Type: application/json` and include those exact two bytes as `RAW_BODY` in the canonical string.",
        "additionalProperties": true,
        "example": {}
      },
      "BillingActivity": {
        "type": "object",
        "description": "The month's activity the charges were computed from. Money values are whole INR rupees.",
        "required": [
          "collectedAmount",
          "payments",
          "resolvedCases",
          "completedVisits",
          "collectedByBucket"
        ],
        "properties": {
          "collectedAmount": {
            "type": "number",
            "description": "Total of the payments on your cases whose payment time falls in the month.",
            "example": 100000
          },
          "payments": {
            "type": "integer",
            "description": "Number of those payments.",
            "example": 1
          },
          "resolvedCases": {
            "type": "integer",
            "description": "Cases fully resolved in the month: `case.closed` events with `status: collected` whose `reason` is NOT `closed_by_operations` (an operations close that left a balance is not billed a case fee), counted by event `occurredAt` in the IST month.",
            "example": 1
          },
          "completedVisits": {
            "type": "integer",
            "description": "Field visits completed on your cases in the month (`visit.completed` events).",
            "example": 1
          },
          "collectedByBucket": {
            "type": "object",
            "description": "`collectedAmount` split by the case's DPD bucket (`0-30`, `31-60`, `61-90`, `91-180`, `181+`, or `unknown`) — the basis for tiered commission.",
            "additionalProperties": {
              "type": "number"
            },
            "example": {
              "0-30": 100000
            }
          }
        }
      },
      "BillingCharges": {
        "type": "object",
        "description": "Billed charge lines, whole INR rupees.",
        "required": [
          "commission",
          "caseFees",
          "visitFees",
          "retainer",
          "minimumTopUp",
          "adjustmentBroughtForward",
          "adjustmentCarriedForward",
          "subtotal",
          "gstPct",
          "gstAmount",
          "total"
        ],
        "properties": {
          "commission": {
            "type": "number",
            "description": "Commission on collections at your per-bucket rates. Can be negative in a month dominated by refunds.",
            "example": 5000
          },
          "caseFees": {
            "type": "number",
            "description": "Fees per resolved case (`activity.resolvedCases` — a `closed_by_operations` close is not billed).",
            "example": 100
          },
          "visitFees": {
            "type": "number",
            "description": "Fees per completed visit.",
            "example": 0
          },
          "retainer": {
            "type": "number",
            "description": "Retainer charged this month. In `floor` mode it is the top-up that lifts usage to your (pro-rated) retainer — max(0, retainer − billable usage), so 0 once usage exceeds the retainer. In `plus` mode it is the full (pro-rated) retainer, added on top of usage.",
            "example": 0
          },
          "minimumTopUp": {
            "type": "number",
            "description": "Legacy minimum-monthly-fee top-up: when your rate card has a minimum monthly fee and the subtotal before it (billable usage + retainer) is below that fee, the difference; otherwise 0.",
            "example": 0
          },
          "adjustmentBroughtForward": {
            "type": "number",
            "description": "≤ 0. Credit carried in from an earlier month whose usage netted negative.",
            "example": 0
          },
          "adjustmentCarriedForward": {
            "type": "number",
            "description": "≤ 0. This month's negative net usage, carried to the next statement — a month never produces a negative invoice.",
            "example": 0
          },
          "subtotal": {
            "type": "number",
            "description": "Pre-GST billable amount = max(0, `commission` + `caseFees` + `visitFees` + `adjustmentBroughtForward`) + `retainer` + `minimumTopUp`.",
            "example": 5100
          },
          "gstPct": {
            "type": "number",
            "description": "GST rate applied, percent.",
            "example": 18
          },
          "gstAmount": {
            "type": "number",
            "description": "GST on `subtotal`.",
            "example": 918
          },
          "total": {
            "type": "number",
            "description": "`subtotal` + `gstAmount`.",
            "example": 6018
          }
        }
      },
      "BillingStatement": {
        "type": "object",
        "description": "A finalized (immutable) monthly statement — only what you are charged; Fieldproof's internal payout and margin figures are never included.",
        "required": [
          "month",
          "status",
          "currency",
          "pricingModel",
          "activity",
          "charges",
          "invoice",
          "finalizedAt"
        ],
        "properties": {
          "month": {
            "type": "string",
            "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])$",
            "description": "IST calendar month, `YYYY-MM`.",
            "example": "2026-09"
          },
          "status": {
            "type": "string",
            "enum": [
              "final"
            ],
            "description": "Always `final` — only finalized months are returned."
          },
          "currency": {
            "type": "string",
            "enum": [
              "INR"
            ]
          },
          "pricingModel": {
            "type": "string",
            "enum": [
              "commission",
              "flat_per_case",
              "hybrid"
            ],
            "description": "Rate-card model the month was billed on: `commission` (percentage of collections), `flat_per_case` (fee per resolved case) or `hybrid` (both)."
          },
          "activity": {
            "$ref": "#/components/schemas/BillingActivity"
          },
          "charges": {
            "$ref": "#/components/schemas/BillingCharges"
          },
          "invoice": {
            "type": "object",
            "nullable": true,
            "description": "Summary of the month's GST tax invoice, or `null` when no invoice number was allocated at finalization (the invoice endpoints then return `409 NO_INVOICE` — contact partners@fluxusforge.in).",
            "required": [
              "number",
              "issuedAt",
              "dueAt",
              "status",
              "sacCode",
              "amountReceived"
            ],
            "properties": {
              "number": {
                "type": "string",
                "description": "Tax-invoice number, `<prefix>/<financial year>/<sequence>`.",
                "example": "FP/26-27/0001"
              },
              "issuedAt": {
                "type": "string",
                "format": "date-time"
              },
              "dueAt": {
                "type": "string",
                "format": "date-time",
                "description": "Payment due date."
              },
              "status": {
                "type": "string",
                "enum": [
                  "issued",
                  "part_paid",
                  "paid",
                  "overdue"
                ],
                "description": "`issued` → `part_paid` → `paid` as your payments are recorded; `overdue` is derived when an unpaid invoice is past `dueAt`."
              },
              "sacCode": {
                "type": "string",
                "description": "SAC code on the invoice.",
                "example": "997159"
              },
              "amountReceived": {
                "type": "number",
                "description": "Gross amount applied to this invoice so far — what you paid plus any TDS you deducted.",
                "example": 0
              }
            }
          },
          "finalizedAt": {
            "type": "string",
            "format": "date-time",
            "description": "When Fieldproof finalized the month."
          }
        },
        "example": {
          "month": "2026-09",
          "status": "final",
          "currency": "INR",
          "pricingModel": "hybrid",
          "activity": {
            "collectedAmount": 100000,
            "payments": 1,
            "resolvedCases": 1,
            "completedVisits": 1,
            "collectedByBucket": {
              "0-30": 100000
            }
          },
          "charges": {
            "commission": 5000,
            "caseFees": 100,
            "visitFees": 0,
            "retainer": 0,
            "minimumTopUp": 0,
            "adjustmentBroughtForward": 0,
            "adjustmentCarriedForward": 0,
            "subtotal": 5100,
            "gstPct": 18,
            "gstAmount": 918,
            "total": 6018
          },
          "invoice": {
            "number": "FP/26-27/0001",
            "issuedAt": "2026-10-05T06:30:00.000Z",
            "dueAt": "2026-10-20T06:30:00.000Z",
            "status": "issued",
            "sacCode": "997159",
            "amountReceived": 0
          },
          "finalizedAt": "2026-10-05T06:30:00.000Z"
        }
      },
      "BillingStatementsResponse": {
        "type": "object",
        "required": [
          "success",
          "count",
          "statements"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "count": {
            "type": "integer",
            "description": "Number of statements returned (≤ `limit`).",
            "example": 1
          },
          "statements": {
            "type": "array",
            "description": "Newest month first.",
            "items": {
              "$ref": "#/components/schemas/BillingStatement"
            }
          }
        },
        "example": {
          "success": true,
          "count": 1,
          "statements": [
            {
              "month": "2026-09",
              "status": "final",
              "currency": "INR",
              "pricingModel": "hybrid",
              "activity": {
                "collectedAmount": 100000,
                "payments": 1,
                "resolvedCases": 1,
                "completedVisits": 1,
                "collectedByBucket": {
                  "0-30": 100000
                }
              },
              "charges": {
                "commission": 5000,
                "caseFees": 100,
                "visitFees": 0,
                "retainer": 0,
                "minimumTopUp": 0,
                "adjustmentBroughtForward": 0,
                "adjustmentCarriedForward": 0,
                "subtotal": 5100,
                "gstPct": 18,
                "gstAmount": 918,
                "total": 6018
              },
              "invoice": {
                "number": "FP/26-27/0001",
                "issuedAt": "2026-10-05T06:30:00.000Z",
                "dueAt": "2026-10-20T06:30:00.000Z",
                "status": "issued",
                "sacCode": "997159",
                "amountReceived": 0
              },
              "finalizedAt": "2026-10-05T06:30:00.000Z"
            }
          ]
        }
      },
      "BillingStatementResponse": {
        "type": "object",
        "required": [
          "success",
          "statement"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "statement": {
            "$ref": "#/components/schemas/BillingStatement"
          }
        },
        "example": {
          "success": true,
          "statement": {
            "month": "2026-09",
            "status": "final",
            "currency": "INR",
            "pricingModel": "hybrid",
            "activity": {
              "collectedAmount": 100000,
              "payments": 1,
              "resolvedCases": 1,
              "completedVisits": 1,
              "collectedByBucket": {
                "0-30": 100000
              }
            },
            "charges": {
              "commission": 5000,
              "caseFees": 100,
              "visitFees": 0,
              "retainer": 0,
              "minimumTopUp": 0,
              "adjustmentBroughtForward": 0,
              "adjustmentCarriedForward": 0,
              "subtotal": 5100,
              "gstPct": 18,
              "gstAmount": 918,
              "total": 6018
            },
            "invoice": {
              "number": "FP/26-27/0001",
              "issuedAt": "2026-10-05T06:30:00.000Z",
              "dueAt": "2026-10-20T06:30:00.000Z",
              "status": "issued",
              "sacCode": "997159",
              "amountReceived": 0
            },
            "finalizedAt": "2026-10-05T06:30:00.000Z"
          }
        }
      },
      "BillingInvoice": {
        "type": "object",
        "description": "Structured GST tax invoice for one finalized month. Money values are whole INR rupees.",
        "required": [
          "number",
          "issuedAt",
          "dueAt",
          "status",
          "month",
          "sacCode",
          "seller",
          "buyer",
          "lines",
          "subtotal",
          "gstPct",
          "gstAmount",
          "total",
          "tds",
          "netPayable",
          "received",
          "notes"
        ],
        "properties": {
          "number": {
            "type": "string",
            "description": "Tax-invoice number, `<prefix>/<financial year>/<sequence>`.",
            "example": "FP/26-27/0001"
          },
          "issuedAt": {
            "type": "string",
            "format": "date-time"
          },
          "dueAt": {
            "type": "string",
            "format": "date-time"
          },
          "status": {
            "type": "string",
            "enum": [
              "issued",
              "part_paid",
              "paid",
              "overdue"
            ],
            "description": "`issued` → `part_paid` → `paid` as your payments are recorded; `overdue` is derived when an unpaid invoice is past `dueAt`."
          },
          "month": {
            "type": "string",
            "pattern": "^[0-9]{4}-(0[1-9]|1[0-2])$",
            "description": "IST calendar month, `YYYY-MM`.",
            "example": "2026-09"
          },
          "sacCode": {
            "type": "string",
            "example": "997159"
          },
          "seller": {
            "type": "object",
            "description": "Fieldproof's invoicing entity.",
            "properties": {
              "legalName": {
                "type": "string"
              },
              "gstin": {
                "type": "string"
              },
              "pan": {
                "type": "string"
              },
              "address": {
                "type": "string"
              },
              "email": {
                "type": "string"
              },
              "state": {
                "type": "string",
                "description": "Seller state (place of supply)."
              }
            }
          },
          "buyer": {
            "type": "object",
            "description": "Your organisation, from your onboarding profile (empty strings for anything not on file).",
            "properties": {
              "legalName": {
                "type": "string",
                "example": "Your Org"
              },
              "gstin": {
                "type": "string",
                "example": "27ZZZZZ9999Z1Z5"
              },
              "address": {
                "type": "string"
              },
              "email": {
                "type": "string",
                "description": "Billing e-mail."
              }
            }
          },
          "lines": {
            "type": "array",
            "description": "Billed line items; zero-amount lines are omitted. `desc` is one of `Collection commission`, `Case resolution fees`, `Field visit fees`, `Monthly retainer` (plus mode) / `Retainer (minimum monthly)` (floor mode), `Minimum monthly top-up`, `Adjustment brought forward`. Commission and the brought-forward adjustment can be negative.",
            "items": {
              "type": "object",
              "required": [
                "desc",
                "amount"
              ],
              "properties": {
                "desc": {
                  "type": "string",
                  "example": "Collection commission"
                },
                "amount": {
                  "type": "number",
                  "example": 5000
                }
              }
            }
          },
          "subtotal": {
            "type": "number",
            "description": "Pre-GST total.",
            "example": 5100
          },
          "gstPct": {
            "type": "number",
            "example": 18
          },
          "gstAmount": {
            "type": "number",
            "description": "GST on `subtotal`.",
            "example": 918
          },
          "total": {
            "type": "number",
            "description": "`subtotal` + `gstAmount`.",
            "example": 6018
          },
          "tds": {
            "type": "object",
            "description": "Indicative TDS on the pre-GST `subtotal` — deduct as applicable under law and share the certificate.",
            "properties": {
              "section": {
                "type": "string",
                "example": "194H"
              },
              "ratePct": {
                "type": "number",
                "example": 2
              },
              "expected": {
                "type": "number",
                "description": "round(`subtotal` × `ratePct` / 100).",
                "example": 102
              }
            }
          },
          "netPayable": {
            "type": "number",
            "description": "`total` − `tds.expected`.",
            "example": 5916
          },
          "received": {
            "type": "object",
            "description": "What has been recorded against this invoice so far.",
            "properties": {
              "gross": {
                "type": "number",
                "description": "Gross amount applied (your payments plus TDS deducted).",
                "example": 0
              },
              "tds": {
                "type": "number",
                "description": "TDS recorded as deducted.",
                "example": 0
              },
              "settledAt": {
                "type": "string",
                "format": "date-time",
                "nullable": true,
                "description": "When the invoice was fully paid, otherwise `null`."
              }
            }
          },
          "notes": {
            "type": "string",
            "description": "Free-text invoice notes."
          }
        },
        "example": {
          "number": "FP/26-27/0001",
          "issuedAt": "2026-10-05T06:30:00.000Z",
          "dueAt": "2026-10-20T06:30:00.000Z",
          "status": "issued",
          "month": "2026-09",
          "sacCode": "997159",
          "seller": {
            "legalName": "…",
            "gstin": "…",
            "pan": "…",
            "address": "…",
            "email": "…",
            "state": "…"
          },
          "buyer": {
            "legalName": "Your Org",
            "gstin": "27ZZZZZ9999Z1Z5",
            "address": "…",
            "email": "…"
          },
          "lines": [
            {
              "desc": "Collection commission",
              "amount": 5000
            },
            {
              "desc": "Case resolution fees",
              "amount": 100
            }
          ],
          "subtotal": 5100,
          "gstPct": 18,
          "gstAmount": 918,
          "total": 6018,
          "tds": {
            "section": "194H",
            "ratePct": 2,
            "expected": 102
          },
          "netPayable": 5916,
          "received": {
            "gross": 0,
            "tds": 0,
            "settledAt": null
          },
          "notes": "Fees for field-collection services. Money collected is remitted separately to the organisation."
        }
      },
      "BillingInvoiceResponse": {
        "type": "object",
        "required": [
          "success",
          "invoice"
        ],
        "properties": {
          "success": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "invoice": {
            "$ref": "#/components/schemas/BillingInvoice"
          }
        },
        "example": {
          "success": true,
          "invoice": {
            "number": "FP/26-27/0001",
            "issuedAt": "2026-10-05T06:30:00.000Z",
            "dueAt": "2026-10-20T06:30:00.000Z",
            "status": "issued",
            "month": "2026-09",
            "sacCode": "997159",
            "seller": {
              "legalName": "…",
              "gstin": "…",
              "pan": "…",
              "address": "…",
              "email": "…",
              "state": "…"
            },
            "buyer": {
              "legalName": "Your Org",
              "gstin": "27ZZZZZ9999Z1Z5",
              "address": "…",
              "email": "…"
            },
            "lines": [
              {
                "desc": "Collection commission",
                "amount": 5000
              },
              {
                "desc": "Case resolution fees",
                "amount": 100
              }
            ],
            "subtotal": 5100,
            "gstPct": 18,
            "gstAmount": 918,
            "total": 6018,
            "tds": {
              "section": "194H",
              "ratePct": 2,
              "expected": 102
            },
            "netPayable": 5916,
            "received": {
              "gross": 0,
              "tds": 0,
              "settledAt": null
            },
            "notes": "Fees for field-collection services. Money collected is remitted separately to the organisation."
          }
        }
      }
    }
  }
}
