openapi: 3.0.0

info:
  title: Sequifi Marketplace API
  version: 1.0.0
  description: >
    REST API for a Sequifi company's people, sales and pay data: users and
    onboarding, sales and milestones, payroll, timesheets, commissions,
    earnings and reserve balances. Guides, examples and a Markdown copy of
    every page are at https://apidocs.sequifi.com (start with /llms.txt).


    **Base URL:** `https://marketplace-api.sequifi.com`, the same for every
    company and every call. Every path in this document is relative to it, for
    example `GET https://marketplace-api.sequifi.com/v1/sales`.


    **Authentication:** every call sends `Authorization: Bearer <token>`. A
    token belongs to one company and decides whose data you read and write. An
    admin creates tokens in Sequifi under Admin, Tools, API Credentials; they
    last 60 days, and an integration renews them itself with
    `POST /v1/auth/refreshToken`. See the Authentication guide.


    **Responses:** JSON in the envelope `{ "status", "message", "data" }`,
    where `status` repeats the HTTP status code. Responses produced by the
    gateway in front of the API (`401`, `429`, `504`, and `403 Missing
    Authentication Token` for a path that does not exist) are just
    `{ "message": "..." }`.


    **Pace:** keep to about 10 requests a second overall. Traffic should be
    scheduled batches (an hourly sales push, a periodic onboarding poll), not a
    request per record: page with `per_page`, and pull only what changed where
    an endpoint offers an `updated_after` or `updated_since` filter. Treat
    `429` as retryable with exponential backoff.


    **Sending sales:** for `POST /v1/sales`, send no more than 30 requests a
    minute, one at a time, with up to 200 records each. A success response
    means the records are queued, not that the sales have changed yet. Read
    the Posting Sales guide before building a sync.

# ─── Server / Base URL ───────────────────────────────────────────────
# When `servers` is absent, OpenAPI 3.0 defines the default as [{ url: "/" }], a
# path relative to wherever the document happens to be served from. That is fine
# inside the hosted docs, but anything reading this file on its own (a downloaded
# copy, a Postman import, a codegen run, an AI agent) is then left with no host to
# call. The Marketplace API is served from exactly one public origin, so it is
# stated here rather than inferred. Keep this in sync with DEFAULT_BASE_URL in
# docs/app.js, which adopts servers[0].url at load time.
servers:
  - url: https://marketplace-api.sequifi.com
    description: >
      Production, the only public origin. All paths in this document are relative
      to this URL, and it does not change per tenant, per environment, or per call.

# ─── Vertical Labels (custom extension) ──────────────────────────────────────
# API keys are stable across all verticals (`kw`, `epc`, `gross_account_value`,
# …). Their **display label** changes per tenant `company_type`. Renderer reads
# this block to (a) populate the topbar vertical selector and (b) auto-render
# the "Vertical Labels" reference page tables. Per-property labels are also
# attached inline via `x-vertical-labels` on each affected schema property.
x-vertical-label-map:
  verticals:
    - { key: solar,    label: "Solar" }
    - { key: turf,     label: "Turf" }
    - { key: roofing,  label: "Roofing" }
    - { key: pest,     label: "Pest" }
    - { key: fiber,    label: "Fiber" }
    - { key: mortgage, label: "Mortgage" }
  fields:
    kw:                    { solar: "KW",                  turf: "Sq Ft",               roofing: "Sq Ft",               pest: null,                  fiber: null,                 mortgage: null }
    epc:                   { solar: "EPC",                 turf: "Gross $ / Sq ft",     roofing: "Gross $ / Sq ft",     pest: null,                  fiber: null,                 mortgage: "Gross Revenue" }
    net_epc:               { solar: "Net EPC",             turf: "Net $ / Sq ft",       roofing: "Net $ / Sq ft",       pest: null,                  fiber: null,                 mortgage: "Fee %" }
    gross_account_value:   { solar: "Gross Account Value", turf: "Gross Account Value", roofing: "Gross Account Value", pest: "Gross Account Value", fiber: "Gross Account Value", mortgage: "Loan Amount" }
    install_partner:       { solar: "Installer",           turf: "Installer",           roofing: "Installer",           pest: "Service Provider",    fiber: "Service Provider",   mortgage: "Broker" }
    adders:                { solar: "Adders",              turf: "Adders",              roofing: "Adders",              pest: null,                  fiber: null,                 mortgage: "Broker Fee" }
    dealer_fee_percentage: { solar: "Dealer Fee %",        turf: "Dealer Fee %",        roofing: "Dealer Fee %",        pest: null,                  fiber: null,                 mortgage: "Appraisal Fee" }
    dealer_fee_amount:     { solar: "Dealer Fee $",        turf: "Dealer Fee $",        roofing: "Dealer Fee $",        pest: null,                  fiber: null,                 mortgage: "Credit Report" }
    service_schedule:      { solar: null,                  turf: null,                  roofing: null,                  pest: "Service Schedule",    fiber: "Service Schedule",   mortgage: "Loan Type" }
    length_of_agreement:   { solar: null,                  turf: null,                  roofing: null,                  pest: "Length Of Agreement", fiber: "Length Of Agreement", mortgage: null }
    initial_service_cost:  { solar: null,                  turf: null,                  roofing: null,                  pest: "Initial Service Cost", fiber: "Initial Service Cost", mortgage: null }
    subscription_payment:  { solar: null,                  turf: null,                  roofing: null,                  pest: "Subscription Payment", fiber: "Subscription Payment", mortgage: null }
    card_on_file:          { solar: null,                  turf: null,                  roofing: null,                  pest: "Card on file",        fiber: "Card on file",       mortgage: null }
    auto_pay:              { solar: null,                  turf: null,                  roofing: null,                  pest: "Autopay",             fiber: "Autopay",            mortgage: null }
    service_completed:     { solar: null,                  turf: null,                  roofing: null,                  pest: "Services Completed",  fiber: "Services Completed", mortgage: null }
    last_service_date:     { solar: null,                  turf: null,                  roofing: null,                  pest: "Last Service Date",   fiber: "Last Service Date",  mortgage: null }
    bill_status:           { solar: null,                  turf: null,                  roofing: null,                  pest: "Bill Status",         fiber: "Bill Status",        mortgage: null }
    balance_age:           { solar: null,                  turf: null,                  roofing: null,                  pest: "Balance Age (Days)",  fiber: "Balance Age (Days)", mortgage: null }
    customer_signoff:      { solar: "Sale Date",           turf: "Sale Date",           roofing: "Sale Date",           pest: "Sale Date",           fiber: "Sale Date",          mortgage: "Closing Date" }
    job_status:            { solar: "Job Status",          turf: "Job Status",          roofing: "Job Status",          pest: "Job Status",          fiber: "Job Status",         mortgage: "Status" }
  roles:
    closer1_id: { solar: "Closer 1", turf: "Closer 1", roofing: "Closer 1", pest: "Sales Rep 1", fiber: "Sales Rep 1", mortgage: "MLO" }
    closer2_id: { solar: "Closer 2", turf: "Closer 2", roofing: "Closer 2", pest: "Sales Rep 2", fiber: "Sales Rep 2", mortgage: "Coordinator" }
    setter1_id: { solar: "Setter 1", turf: "Setter 1", roofing: "Setter 1", pest: null,          fiber: null,          mortgage: "LOA" }
    setter2_id: { solar: "Setter 2", turf: "Setter 2", roofing: "Setter 2", pest: null,          fiber: null,          mortgage: "Processor" }

# ─── Mandatory Fields (custom extension) ─────────────────────────────────────
# Per-vertical required-field map for POST /v1/sales. Mirrors the API's
# conditional-field validation. The docs renderer reads
# this to overlay a red `*` next to every label in `x-vertical-label-map`
# that's required for that vertical, plus the universal `always` list.
# Domain-conditional rules are noted in `notes`.
x-vertical-required:
  always: [pid, customer_name, customer_signoff]
  per_vertical:
    solar:    [customer_state, location_code]
    turf:     [kw, customer_state, location_code]
    roofing:  [kw, gross_account_value]
    pest:     [gross_account_value]
    fiber:    [gross_account_value]
    mortgage: [customer_state, location_code]
  notes:
    customer_signoff: "Required for ALL 6 verticals at POST time. Use this single field for the sale date across every vertical (label: 'Sale Date' on 5 verticals, 'Closing Date' on Mortgage)."
    customer_state:   "Turf: a company can be configured not to require it. Mortgage: required only for companies configured to require it. Your Sequifi contact can confirm your company's setting."
    location_code:    "Same rules as customer_state."

x-reference-pages:
  - name: Vertical Labels
    icon: "🏷"
    autoRender: vertical-labels
    description: >
      What each sales field is called in your company's Sequifi screens, by
      vertical, and which fields each vertical requires when you post a sale.


      **Why this exists:** Sequifi uses one set of field keys for every
      vertical, and many of them come from solar (`kw`, `epc`, `net_epc`). The
      keys in the API never change. Only the label your users see does: `kw`
      is "KW" for a solar company and "Sq Ft" for a turf company. Send and
      read the key; show your users the label.


      **Pick your vertical:** choose it in the Vertical menu at the top of the
      page. The tables below, and every endpoint page with labeled fields,
      highlight that vertical's column.


      **Hidden fields:** "hidden" means the field exists in the API but your
      vertical's screens don't show it. Don't show it to your users either.


      **Required fields:** a `*` marks a field that vertical requires when you
      post a sale. `pid`, `customer_name` and `customer_signoff` are required
      for every vertical.


      **Unknown vertical:** a company whose vertical isn't set uses the Solar
      labels.

  - name: Posting Sales
    icon: "📤"
    description: >
      How to send sales to Sequifi in bulk with `POST /v1/sales` so every
      record lands, and how to confirm that it did. Written for integrators
      and for AI agents running an integration: follow the rules in order. A
      reference script that applies every rule is published at
      https://apidocs.sequifi.com/examples/post_sales_bulk.py (Python 3.9+,
      no extra packages).


      **What a success response means:** A `201` or `200` from
      `POST /v1/sales` means the records passed validation and were queued.
      Sequifi then works through the queue in the background: each sale is
      created or updated and its commissions are recalculated. Until that
      finishes, `GET /v1/sales` still returns the old values, or `404` for a
      brand-new pid.

      Processing usually finishes within minutes. A large run, or one sent
      while other imports are running, can take an hour or more. A sale whose
      payroll is being finalized waits until that payroll completes and then
      processes on its own.


      **Rule 1, send the complete sale every time:** Every record carries
      `pid`, `customer_name`, `customer_signoff` (the sale date, `YYYY-MM-DD`)
      and the fields your vertical requires, marked `*` on the Vertical
      Labels page (for example `gross_account_value` for Pest, Fiber and
      Roofing, and `kw` for Turf and Roofing). Send them on updates
      too, not only on new sales.

      Why: An update to a sale Sequifi already has is merged into that sale,
      so a field you leave out keeps its current value. Sending the complete
      sale still keeps your system and Sequifi in step, and milestone dates
      always need the full list (below). `pid` is the key, so an update never
      creates a duplicate.

      Send one `milestone_dates` entry for every milestone in the product's schedule, in order, with `milestone_date: null` for those not reached yet. Dates are saved by position, so sending only the milestone that changed moves its date onto the first milestone and clears the rest. The list replaces the sale's list: a milestone you leave out is treated as removed.


      **Rule 2, turn on partial_success:** Set `"partial_success": true` at
      the top level of every request. Without it, one bad record rejects the
      whole request with `400` and nothing in the batch is queued. With it, the good records are queued and each bad one comes back in `data.rejected[]` with its reason. A rejected record is not saved, whether it is a new sale or an update; fix it and resend it. A duplicate `pid` inside one request
      still rejects the whole request, so remove duplicates first.


      **Rule 3, batch and pace:** Put up to 200 records in each request. Send
      one request at a time and wait for its response before sending the
      next. Stay under 30 requests a minute to this endpoint: above that, the
      processing of a batch can wait until your next request. Do not pause
      between batches to wait for processing; queued batches are processed
      in the order they arrive. One request per record is the wrong shape for
      a bulk run.


      **Rule 4, read every response:**

      - `201` or `200`: compare `recordsProcessed` with the number you sent (a request where every record was rejected still returns `201`, with `recordsProcessed` of 0). Fix and resend each record in `data.rejected[]`. Check `data.warnings[]` for fields that were ignored, and fix your mapping. `warnings[]` lists a product that could not be matched, but not a closer or setter: check `closer1_id` in `data.sales[]`.

      - `400`: nothing in the request was queued. Fix the records named in
      `data.errors` and resend the whole request.

      - `429`, `500`, `502`, `503`, `504` or a timeout: resend the same request after a pause: wait 2, 4, 8 and 16 seconds between attempts. Resending is safe
      because `pid` is the key.


      **Rule 5, confirm, and do not resend what is still queued:** After the
      last batch, wait (allow an hour for a large run), then call
      `GET /v1/sales/{pid}` for each pid and compare it with what you sent:
      `customer_signoff`, the product, and
      `data.sale.milestone_dates[]`. Do not resend a record only because it has
      not shown up yet. If you send the same pid again before the first copy
      is processed, the newer copy replaces it and goes to the back of the
      queue. If a sale still does not match a few hours later, send its pid
      to Sequifi support.


      **Records rejected during processing:** A queued record can still be
      rejected when it is processed. The API does not report this today, so
      the check in Rule 5 is how you catch it. The causes:

      - a milestone date earlier than `customer_signoff`;

      - changing or removing a milestone date that has already been paid;

      - removing or changing the product, or changing a closer or setter,
      after commission on the sale has been paid.

      Make those corrections in Sequifi, or ask support to make them.


      **Do not send:** `data_source_type` (leave it out); commission or paid
      amounts, which Sequifi calculates; flat fields such as
      `milestone_date` or `m1_payable_date`, which are ignored. Milestone
      dates go only in `milestone_dates[]`.

tags:
  - name: Authentication
    description: >
      Keep an integration's access alive without an admin: exchange the
      refresh token for a new pair before the access token expires. Tokens
      are created, paused and deleted by an admin in Sequifi, under Admin >
      Tools > API Credentials.
  - name: Users
    description: >
      Read and update the people in your company: reps, managers and admins,
      with their position, office and status. This is where a hired rep lives;
      people still being hired are under Onboarding.


      **Changes that run through Sequifi:** terminate, transfer and position
      changes apply the same rules and history as the app, so payroll and
      commissions follow them.
  - name: Locations
    description: >
      Your company's offices and the states they cover. Use a location's code
      when you post sales and its id when you transfer a rep.
  - name: Positions
    description: >
      The job positions your company pays by (for example Closer, Setter,
      Manager), each with its pay setup. Every user and onboarding record
      points at one.
  - name: Onboarding
    description: >
      People being hired: create a record from your ATS, send the offer letter,
      then hire them into Users.


      **Typical flow:** create (status Draft), send the offer, hire. Read the
      hire endpoint before you rely on it: it does less than Hire in the app.
  - name: Teams
    description: >
      Team rosters, as on the in-app Teams page: a Team Manager and Team
      Members. Teams and memberships are effective-dated, so reads default to
      who is on the team today, and a create is refused if it would put a rep
      on two teams at once.
  - name: Candidates
    description: >
      The hiring pipeline before onboarding (the Candidates page in the app):
      the people you are recruiting and the stage each one is at.
  - name: Milestones
    description: >
      The milestone schedules your company pays commissions on (for example
      M1 at install, M2 at activation). Look these up before you send
      milestone dates on a sale.
  - name: Payroll
    description: >
      Pay runs and pay stubs: what each rep is about to be paid (open payroll)
      and what they were paid (payroll history), down to the line items on a
      stub.
  - name: Requests
    description: >
      Bonuses, fines and fees, and reimbursements, as on the Requests &
      Approvals page. Requests you create wait for an admin to approve them;
      nothing is paid until they do.
  - name: Timesheet
    description: >
      Hours: clock-in and clock-out entries for hourly reps, read by pay period
      or added from a field tool.
  - name: Sales
    description: >
      Create, update and read sales (loans, for mortgage companies). Posting a
      sale is how commissions get calculated; your own `pid` is the key that
      makes a re-send update instead of duplicate.


      **Start with the Posting Sales guide** before you build a sync: a
      success response means queued, not processed.
  - name: Pay Frequency
    description: >
      The pay schedules your company uses (weekly, every two weeks, twice a
      month, monthly) and their ids.
  - name: Custom Fields
    description: >
      The extra fields your company has added to sales, payroll and onboarding
      records, with their types and options, so you can send and read their
      values.
  - name: Products
    description: >
      Your product catalog. Every sale belongs to a product, and the product
      decides how its commissions and milestones are paid.
  - name: Commissions
    description: >
      A rep's commission setup (the Commission tab on their profile): rates
      per product and role (closer, setter, self-gen), in one normalized unit
      across every vertical. This is the rate card, not money earned.
  - name: Earnings
    description: >
      What a rep has earned (the Earnings page in the app): pending, paid,
      projected and clawed back, for commissions and overrides, with the line
      items behind the totals. For the rates behind them use Commissions; for
      pay runs use Payroll.
  - name: Reserve
    description: >
      A rep's reserve balance (for companies with Reserve Balances): the part
      of their earnings held back from payroll and paid out later, with the
      ledger behind it. Held-back amounts never appear on a pay stub, so they
      live here instead.
  - name: Documents
    description: >
      Files stored on your people: uploaded onboarding documents (driver's
      licenses, W-9s and so on), signed agreements and profile photos. The list
      returns details only; each download is a link that expires after 10
      minutes.
  - name: Integrations
    description: >
      Raw records from a connected CRM or lender system, stored as received so
      Sequifi can map them into sales. Posting raw data does not create sales
      by itself.

# Groups the tags above into the domains the docs sidebar shows. The Redoc
# convention, read by docs/app.js and scripts/build-docs.js.
x-tagGroups:
  - name: Access
    tags: [Authentication]
  - name: People
    tags: [Users, Onboarding, Candidates, Teams, Positions, Locations, Documents]
  - name: Sales
    tags: [Sales, Milestones, Products, Custom Fields, Integrations]
  - name: Pay
    tags: [Payroll, Requests, Pay Frequency, Timesheet, Commissions, Earnings, Reserve]

paths:
  /v1/auth/refreshToken:
    post:
      operationId: refreshAccessToken
      tags:
        - Authentication
      summary: Refresh an access token
      description: |
        Exchanges a refresh token for a new access token and a new refresh token, so an integration can keep working past the access token's 60 days without an admin. Send the refresh token in the body; this call takes no `Authorization` header.

        **Before you call:**

        - You need the refresh token from the credentials an admin created under Admin > Tools > API Credentials, or from your last refresh.
        - Refresh before the access token expires (60 days). The refresh token itself lasts 66 days; after that an admin has to create new credentials.

        **What happens:**

        - The refresh token is checked. If it is valid you get a new access token (60 days) and a new refresh token (66 days), counted from now. Refreshing on a schedule keeps an integration running indefinitely.
        - The old pair stops working: the old access token within about five minutes, the old refresh token at once. Each refresh token works once.
        - Store the new refresh token before you use the new access token. You need it for the next refresh.
        - The credential keeps its name, and an admin still controls it: Pause or Delete in the web app stops refreshing too.

        **Idempotency and retries:**

        - If a refresh response is lost, retry with the same refresh token within 60 seconds and you get the same new pair. Two workers refreshing at once also get the same pair.
        - After 60 seconds, a refresh token that was already used is treated as stolen: the credential is paused and the call returns `401`. An admin can resume it or create a new one. Keep one copy of the refresh token and refresh from one place.

        **Formats:**

        - Body: `{"refresh_token": "<token>"}`. Leading and trailing spaces are trimmed.
        - Expiry times are `YYYY-MM-DD HH:MM:SS` in UTC.

        **Errors:**

        - `400 Invalid JSON body` or `400 Missing required field: refresh_token`.
        - `401 Invalid or expired refresh token`: unknown, expired, paused or deleted credentials, or a company whose API access is off. The message is the same for all of them.
        - `401` with a message saying the token was already used and the credential is paused: see retries above. An admin has to resume or replace the credential.
        - Don't retry a `401` in a loop.

        **Related:**

        - The Authentication guide covers creating tokens and rotating them by hand.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - refresh_token
              properties:
                refresh_token:
                  type: string
                  description: The current refresh token. Each one works once.
                  example: "9f2c...e41a"
            example:
              refresh_token: "<your current refresh token>"
      responses:
        "200":
          description: Refreshed. Use the new access token from now on and store the new refresh token for the next refresh.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: "Token refreshed successfully"
                  data:
                    type: object
                    properties:
                      name:
                        type: string
                        description: The credential's name, as set when an admin created it.
                      access_token:
                        type: string
                        description: 'Send as `Authorization: Bearer <access_token>`.'
                      access_token_expires_at:
                        type: string
                        description: When the access token stops working, `YYYY-MM-DD HH:MM:SS` UTC (60 days).
                      refresh_token:
                        type: string
                        description: Use for the next refresh. Works once.
                      refresh_token_expires_at:
                        type: string
                        description: Last moment to refresh, `YYYY-MM-DD HH:MM:SS` UTC (66 days).
              example:
                status: 200
                message: "Token refreshed successfully"
                data:
                  name: "CRM sync (production)"
                  access_token: "0f3a...:9c1d...:7be2..."
                  access_token_expires_at: "2026-12-07 18:00:00"
                  refresh_token: "9b41...c07e"
                  refresh_token_expires_at: "2026-12-13 18:00:00"
        "400":
          description: The body is not JSON or has no `refresh_token`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Missing required field: refresh_token"
                data: {}
        "401":
          description: The refresh token can't be used, or it was already used and the credential is now paused.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid:
                  summary: Unknown, expired, paused or deleted
                  value:
                    status: 401
                    message: "Invalid or expired refresh token"
                    data: {}
                reused:
                  summary: Already used more than 60 seconds ago
                  value:
                    status: 401
                    message: "This refresh token was already used, so the credential has been paused to protect it. An admin can resume or replace it under Admin > Tools > API Credentials."
                    data: {}
        "500":
          description: Server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/users:
    get:
      operationId: listUsers
      tags:
        - Users
      summary: List users
      description: |
        Returns your company's employees (reps, managers and admins), newest first, with their office, position, manager, recruiter, onboarding state and home address. Use it for roster syncs and to find the user `id` every other user endpoint needs. Users of every status are returned unless you pass `status`, and the list includes one system user named "Marketplace API" that you should skip.

        **Filtering and paging:**

        - All filters are optional and combine with AND. Any other query parameter returns `400`.
        - `first_name`, `last_name`, `full_name`, `email` and `employee_id` are case-insensitive "contains" matches, not exact lookups: `employee_id=12` also matches `EMP120`. `%` and `_` in a value act as wildcards. To find one person, filter by `email`, then compare the address exactly on your side.
        - `full_name` matches "first last" with one space. Middle names are not part of it.
        - `status=active` returns users whose `status_id` is `1`; `status=inactive` returns every other status. Users with no status at all appear only when you leave `status` out.
        - `is_manager` takes `0` or `1`. Any other value is ignored and the list comes back unfiltered.
        - `status` and `onboarding_complete` sent with an empty value count as not sent.
        - `per_page` is 1 to 200 (default 20). `page` starts at 1. A page past the end returns an empty `users` array, and `last_page` is `0` when nothing matches.
        - Results are ordered by `id`, newest first, with offset paging. Users added while you page can shift later pages by a row, so de-duplicate by `id`.

        **Optional fields:**

        - Add `include=additional_offices` to return current Additional Office assignments. The field is omitted by default.

        **Formats:**

        - `created_at` and `updated_at` are ISO 8601 UTC strings, for example `2024-01-15T10:00:00.000Z`. `dob` is `YYYY-MM-DD` or `null`.
        - Home address fields are `null` until the rep completes the profile step of onboarding. `home_address` is the formatted single line; the other `home_address_*` fields are its parts and use the same names `POST /v1/users` accepts.
        - `position_id` is the primary position. `sub_position_id` is the position in effect today in your company's time zone. They can differ.
        - `hiring_status_id` and `hiring_status_name` come from the rep's latest hiring record (`7` = still completing self-onboarding, `14` = finished). They are `null` for users added without going through hiring, for example by import. Your company can rename statuses, so branch on the id.
        - `onboarding_complete` is `1` once the rep has finished every required self-onboarding step (documents, banking details and profile), otherwise `0`.
        - `wages_status` is `1` when the rep's position pays wages (hourly or salary). It is a position setting, not a per-person flag.
        - `requestedBy` is the name of the API credential your token belongs to, not necessarily your company name.

        **Errors:**

        - `400` `Invalid query parameter(s)`, with `invalid_params` and `allowed_params` in `data`.
        - `400` for a bad `page`, `per_page`, `status` or `onboarding_complete` value (see the examples).
        - `400` for an unsupported or empty `include` value.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.
        - `500` if requested Additional Offices cannot be looked up; retry according to Errors and retries. A missing assignments table returns `[]`.

        **Common mistakes:**

        - Treating a name, email or `employee_id` filter as an exact match.
        - Forgetting that terminated and dismissed users are included unless you pass `status=active`.
        - Importing the "Marketplace API" system user (email `marketplace-api@system.sequifi.com`). Skip it by email.

        **Related:**

        - `GET /v1/users/{id}` returns one user.
        - `GET /v1/locations` and `GET /v1/positions` resolve `office_id`, `position_id` and `sub_position_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: include
          in: query
          required: false
          description: Request optional Additional Office assignments. Omit to leave additional_offices out of the response.
          schema:
            type: string
            enum: [additional_offices]
          example: additional_offices
        - name: page
          in: query
          required: false
          description: Page number, starting at 1. Must be a positive whole number.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Users per page, 1 to 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 20
          example: 20
        - name: first_name
          in: query
          required: false
          description: Case-insensitive "contains" match on first name.
          schema:
            type: string
          example: Alex
        - name: last_name
          in: query
          required: false
          description: Case-insensitive "contains" match on last name.
          schema:
            type: string
          example: Morgan
        - name: full_name
          in: query
          required: false
          description: Case-insensitive "contains" match on "first last" (one space, no middle name).
          schema:
            type: string
          example: Alex Morgan
        - name: email
          in: query
          required: false
          description: Case-insensitive "contains" match on email. Compare the result exactly on your side before treating it as the same person.
          schema:
            type: string
          example: alex.morgan@example.com
        - name: employee_id
          in: query
          required: false
          description: Case-insensitive "contains" match on your company's employee number.
          schema:
            type: string
          example: EMP-1042
        - name: is_manager
          in: query
          required: false
          description: "`1` for managers only, `0` for non-managers only. Any other value is ignored (no filter)."
          schema:
            type: integer
            enum: [0, 1]
          example: 1
        - name: status
          in: query
          required: false
          description: "`active` (`status_id` is 1) or `inactive` (any other status). Not case-sensitive. Leave it out for every status."
          schema:
            type: string
            enum: [active, inactive]
          example: active
        - name: onboarding_complete
          in: query
          required: false
          description: "`1` for reps who finished every required self-onboarding step, `0` for reps still onboarding. Leave it out for both."
          schema:
            type: integer
            enum: [0, 1]
          example: 1
      responses:
        '200':
          description: A page of users
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          current_page:
                            type: integer
                            description: The page returned.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Users matching the filters, across all pages.
                          last_page:
                            type: integer
                            description: Number of the last page. 0 when nothing matches.
                          filters:
                            type: object
                            nullable: true
                            description: The filters applied (trimmed), or null when none were sent.
                          users:
                            type: array
                            description: Users on this page, newest first.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: User id. Every other user endpoint takes this id.
                                employee_id:
                                  type: string
                                  nullable: true
                                  description: Your company's own employee number.
                                first_name:
                                  type: string
                                  description: First name.
                                last_name:
                                  type: string
                                  description: Last name.
                                email:
                                  type: string
                                  description: Email address.
                                mobile_no:
                                  type: string
                                  nullable: true
                                  description: Mobile number as stored. The format is not normalized.
                                dob:
                                  type: string
                                  format: date
                                  nullable: true
                                  description: Date of birth, YYYY-MM-DD.
                                home_address:
                                  type: string
                                  nullable: true
                                  description: Formatted single-line home address. Null until the rep completes the profile step of onboarding.
                                home_address_line_1:
                                  type: string
                                  nullable: true
                                  description: Street line.
                                home_address_line_2:
                                  type: string
                                  nullable: true
                                  description: Apartment or suite line. Usually null.
                                home_address_city:
                                  type: string
                                  nullable: true
                                  description: City.
                                home_address_state:
                                  type: string
                                  nullable: true
                                  description: State, normally a 2-letter code.
                                home_address_zip:
                                  type: string
                                  nullable: true
                                  description: ZIP code.
                                is_manager:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 if the user is a manager.
                                status_id:
                                  type: integer
                                  nullable: true
                                  description: Employment status. 1 is active; any other value is inactive (a dismissal through `POST /v1/users/termination` sets 2).
                                worker_type:
                                  type: string
                                  nullable: true
                                  description: Worker type, such as `1099` or `w2`. Compare case-insensitively.
                                office_id:
                                  type: integer
                                  nullable: true
                                  description: Current office. See `GET /v1/locations`.
                                office_name:
                                  type: string
                                  nullable: true
                                  description: Name of the current office.
                                state_id:
                                  type: integer
                                  nullable: true
                                  description: Work state id (not the home state).
                                state_code:
                                  type: string
                                  nullable: true
                                  description: Work state code, for example `TX`.
                                city_id:
                                  type: integer
                                  nullable: true
                                  description: Work city id.
                                position_id:
                                  type: integer
                                  nullable: true
                                  description: Primary position. See `GET /v1/positions`.
                                position_name:
                                  type: string
                                  nullable: true
                                  description: Name of the primary position.
                                sub_position_id:
                                  type: integer
                                  nullable: true
                                  description: Position in effect today in your company's time zone. Can differ from `position_id`.
                                sub_position_name:
                                  type: string
                                  nullable: true
                                  description: Name of the position in effect today in your company's time zone.
                                wages_status:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 when the rep's position pays wages (hourly or salary). A position setting, not a per-person flag.
                                onboarding_complete:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 once every required self-onboarding step (documents, banking details, profile) is done.
                                hiring_status_id:
                                  type: integer
                                  nullable: true
                                  description: Status of the rep's latest hiring record (7 = still completing self-onboarding, 14 = finished). Null when the user was not hired through hiring.
                                hiring_status_name:
                                  type: string
                                  nullable: true
                                  description: Label for `hiring_status_id`. Your company can rename it; use it for display only.
                                onboarding_step_name:
                                  type: string
                                  nullable: true
                                  description: >
                                    The self-onboarding step the rep is on, using the names on the
                                    Onboarding page: `Not Started` (never logged in), `Personal Details`,
                                    `Tax + Banking Info`, `Tax Info`, `Banking Info` or `Documents`. The
                                    steps a rep sees depend on your payroll setup and their worker type.
                                    Set only while `hiring_status_id` is `7`, otherwise `null`. Refreshed
                                    every 15 minutes, so it can lag the Onboarding page by up to 15 minutes.
                                onboarding_step_updated_at:
                                  type: string
                                  nullable: true
                                  description: When `onboarding_step_name` last changed (company database time). `null` when `onboarding_step_name` is `null`.
                                employee_personal_detail:
                                  type: array
                                  nullable: true
                                  description: Your company's custom personal fields for this user. Null when none are stored.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Custom field id from `GET /v1/custom-fields?type=employee`.
                                      field_name:
                                        type: string
                                        nullable: true
                                        description: Field label.
                                      field_type:
                                        type: string
                                        nullable: true
                                        description: Field type, for example `text`, `date` or `dropdown`.
                                      value:
                                        nullable: true
                                        description: Stored value, usually a string.
                                employee_admin_only_fields:
                                  type: array
                                  nullable: true
                                  description: Custom fields only admins can edit. Same item shape as `employee_personal_detail`. Write with `POST /v1/users`.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Custom field id.
                                      field_name:
                                        type: string
                                        nullable: true
                                        description: Field label.
                                      field_type:
                                        type: string
                                        nullable: true
                                        description: Field type.
                                      value:
                                        nullable: true
                                        description: Stored value, usually a string.
                                manager:
                                  type: object
                                  nullable: true
                                  description: The user's manager, or null.
                                  properties:
                                    id:
                                      type: integer
                                      description: Manager's user id.
                                    first_name:
                                      type: string
                                      description: First name.
                                    last_name:
                                      type: string
                                      description: Last name.
                                    email:
                                      type: string
                                      description: Email address.
                                recruiter:
                                  type: object
                                  nullable: true
                                  description: The user's recruiter, or null. Same fields as `manager`.
                                  properties:
                                    id:
                                      type: integer
                                      description: Recruiter's user id.
                                    first_name:
                                      type: string
                                      description: First name.
                                    last_name:
                                      type: string
                                      description: Last name.
                                    email:
                                      type: string
                                      description: Email address.
                                additional_offices:
                                  type: array
                                  description: >
                                    Only returned with `include=additional_offices`. The user's current
                                    Additional Office assignments, the same set the
                                    user's profile page shows under Employment Package, except that
                                    assignments to archived offices are left out. Current means started on
                                    or before today and not ended before today; when an office has more than
                                    one current assignment, only the newest is returned. One entry per
                                    office, ordered by office name. `[]` when the user has none or the
                                    tenant has no assignments table. Other lookup failures return 500.
                                    Override pay for these offices is not included.
                                    "Today" means today in your company's time zone.
                                  items:
                                    type: object
                                    properties:
                                      office_id:
                                        type: integer
                                        description: Office id. See `GET /v1/locations`.
                                      office_name:
                                        type: string
                                        nullable: true
                                        description: Office name.
                                      state_id:
                                        type: integer
                                        nullable: true
                                        description: State id of the assignment.
                                      state_code:
                                        type: string
                                        nullable: true
                                        description: State code, for example `TX`.
                                      effective_date:
                                        type: string
                                        format: date
                                        nullable: true
                                        description: Date the assignment started, YYYY-MM-DD. Null only for legacy records stored with a zero date.
                                      effective_end_date:
                                        type: string
                                        format: date
                                        nullable: true
                                        description: Last day of the assignment, YYYY-MM-DD, or null when it has no end date.
                                created_at:
                                  type: string
                                  format: date-time
                                  description: When the user was created, ISO 8601 UTC.
                                updated_at:
                                  type: string
                                  format: date-time
                                  description: When the user was last changed, ISO 8601 UTC.
              examples:
                active_users:
                  summary: Active users (status=active, include=additional_offices)
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 20
                      total: 23
                      last_page: 2
                      filters:
                        status: active
                      users:
                        - id: 4821
                          employee_id: "EMP-1042"
                          first_name: "Alex"
                          last_name: "Morgan"
                          email: "alex.morgan@example.com"
                          dob: "1990-01-15"
                          mobile_no: "5125550142"
                          is_manager: 0
                          status_id: 1
                          worker_type: "1099"
                          office_id: 31
                          home_address: "1200 Congress Ave, Austin, TX 78701, USA"
                          home_address_line_1: "1200 Congress Ave"
                          home_address_line_2: null
                          home_address_city: "Austin"
                          home_address_state: "TX"
                          home_address_zip: "78701"
                          state_id: 44
                          city_id: 1207
                          created_at: "2024-01-15T10:00:00.000Z"
                          updated_at: "2026-06-01T08:30:00.000Z"
                          employee_personal_detail:
                            - id: 2
                              field_name: "Preferred first name"
                              field_type: "text"
                              value: "Alex"
                          employee_admin_only_fields: null
                          state_code: "TX"
                          office_name: "Austin"
                          wages_status: 0
                          onboarding_complete: 1
                          hiring_status_id: 14
                          hiring_status_name: "Active"
                          onboarding_step_name: null
                          onboarding_step_updated_at: null
                          position_id: 4
                          position_name: "Sales Rep"
                          sub_position_id: 12
                          sub_position_name: "Senior Sales Rep"
                          manager:
                            id: 87
                            first_name: "Jordan"
                            last_name: "Lee"
                            email: "jordan.lee@example.com"
                          recruiter:
                            id: 55
                            first_name: "Taylor"
                            last_name: "Brooks"
                            email: "taylor.brooks@example.com"
                          additional_offices:
                            - office_id: 12
                              office_name: "Dallas"
                              state_id: 44
                              state_code: "TX"
                              effective_date: "2026-03-01"
                              effective_end_date: null
        '400':
          description: Unknown query parameter or invalid filter value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unknown_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["first"]
                      allowed_params: ["first_name", "last_name", "full_name", "email", "employee_id", "is_manager", "status", "onboarding_complete", "page", "per_page"]
                bad_page:
                  summary: page is not a positive whole number
                  value:
                    status: 400
                    message: "Bad Request: page must be a positive integer"
                    data: {}
                bad_per_page:
                  summary: per_page outside 1 to 200
                  value:
                    status: 400
                    message: "Bad Request: per_page must be a positive integer between 1 and 200"
                    data: {}
                bad_status:
                  summary: status is not active or inactive
                  value:
                    status: 400
                    message: "Bad Request: status must be 'active' or 'inactive'"
                    data: {}
                bad_onboarding_complete:
                  summary: onboarding_complete is not 0 or 1
                  value:
                    status: 400
                    message: "Bad Request: onboarding_complete must be 0 or 1"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

    post:
      operationId: updateUserProfile
      tags:
        - Users
      summary: Update a user's profile
      description: |
        Updates an existing, active employee's personal details: name, sex, date of birth, email, mobile number, home address, emergency contact, your company's custom personal fields and admin-only fields. It never creates a user. Sending `employee_personal_detail` replaces the employee's entire set of custom field values, so always send the full array.

        **Before you call:**

        - Find the user's `id` with `GET /v1/users?status=active`. Only active users (`status_id` 1) can be updated; anyone else returns `404`.
        - Get custom field ids from `GET /v1/custom-fields?type=employee`, and admin-only field ids from `GET /v1/custom-fields?type=employee_admin`.
        - To change custom fields, read the current `employee_personal_detail` from `GET /v1/users/{id}`, change the values you need, and send the whole array back.

        **What happens:**

        - Only the fields you send change. Fields you leave out keep their values.
        - `first_name`, `middle_name`, `last_name`, `dob`, `sex`, `email` and `mobile_no` cannot be cleared: `null` (or the string `"null"`) counts as not sent.
        - Home address and emergency contact fields are cleared by sending `null`.
        - `employee_personal_detail` replaces the stored array. A field you leave out is removed, and `null` removes them all.
        - `employee_admin_only_fields` is merged by `id`: only the fields you send change, and the rest keep their values. An unknown or deleted id returns `400` and nothing is saved. `null` is not allowed. If the employee's saved admin-only fields are in a format the API can't read, the request returns `409` and nothing is saved; update them in Sequifi instead.
        - A new `email`, `mobile_no`, `first_name` or `last_name` is also copied to the employee's hiring records.
        - Each changed field is recorded in the employee's profile history, attributed to the "Marketplace API" system user.
        - Fields this endpoint does not handle (for example `office_id`, `position_id` or `status_id`) are ignored without an error.

        **Idempotency and retries:**

        - Sending the same body again is safe: nothing changes except `updated_at`.
        - On `409`, another update to the same employee was in progress. Retry the same request.

        **Formats:**

        - `user_id` is a positive integer or a string of digits.
        - `email` must look like `name@domain.tld` and must not be in use by another active employee, or by a hiring record or lead that is not this employee's.
        - `mobile_no` needs at least 10 digits and has the same uniqueness rule as `email`. Numbers are compared exactly as stored, so `512-555-0142` and `5125550142` count as different numbers. Use one format everywhere.
        - `dob` is `YYYY-MM-DD` and must be a real date.
        - `sex` is `male`, `female` or `other`, in lowercase.
        - Each `employee_personal_detail` item needs an integer `id` (a JSON number, not a string) and a `value` key, which may be `null`. Ids must not repeat.
        - In the response, `dob` is `YYYY-MM-DD` and `created_at` / `updated_at` are `YYYY-MM-DD HH:MM:SS` in UTC with no zone marker. This differs from the ISO format `GET /v1/users` returns for the same fields.

        **Errors:**

        - `400` `Validation failed`, with one message per field in `data.errors`.
        - `400` `Invalid or missing user_id in request body`, `No fields provided to update`, `Invalid or missing JSON body`, `Request body must be a JSON object`, or `Duplicate value detected. Please ensure all unique fields have distinct values.`
        - `404` `User <id> not found` (no such user, or the user is not active), or `User <id> not found or no longer active`.
        - `409` concurrent update. Retry.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.
        - A duplicate `email` or `mobile_no` message names the employee who already uses the value. Do not show these messages to end users as they are.

        **Common mistakes:**

        - Using this endpoint to add a person. Hire through `POST /v1/onboarding` and `PUT /v1/onboarding/hire`.
        - Sending only the custom field you changed, which deletes the others.
        - Sending custom field ids as strings (`"2"`), which fails validation.
        - Updating a terminated or dismissed user.

        **Related:**

        - `POST /v1/users/{id}/transfer` changes the office; `POST /v1/users/{id}/position` changes the position.
        - `GET /v1/users/{id}` confirms the change.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - user_id
              properties:
                user_id:
                  type: integer
                  minimum: 1
                  description: Id of the active user to update, from `GET /v1/users`.
                  example: 4821
                first_name:
                  type: string
                  description: First name. Cannot be cleared.
                  example: "Alex"
                middle_name:
                  type: string
                  description: Middle name. Cannot be cleared.
                  example: "J"
                last_name:
                  type: string
                  description: Last name. Cannot be cleared.
                  example: "Morgan"
                sex:
                  type: string
                  enum: [male, female, other]
                  description: Lowercase. Cannot be cleared.
                  example: "female"
                dob:
                  type: string
                  format: date
                  description: Date of birth, YYYY-MM-DD. Cannot be cleared.
                  example: "1990-01-15"
                email:
                  type: string
                  format: email
                  description: Must be unused by any other active employee, hiring record or lead. Cannot be cleared.
                  example: "alex.morgan@example.com"
                mobile_no:
                  type: string
                  description: At least 10 digits. Same uniqueness rule as `email`, compared exactly as stored. Cannot be cleared.
                  example: "5125550142"
                home_address:
                  type: string
                  nullable: true
                  description: Formatted single-line home address. `null` clears it.
                  example: "1200 Congress Ave, Austin, TX 78701, USA"
                home_address_line_1:
                  type: string
                  nullable: true
                  description: Street line. `null` clears it.
                  example: "1200 Congress Ave"
                home_address_line_2:
                  type: string
                  nullable: true
                  description: Apartment or suite line. `null` clears it.
                home_address_city:
                  type: string
                  nullable: true
                  description: City (up to 100 characters).
                  example: "Austin"
                home_address_state:
                  type: string
                  nullable: true
                  description: State. Send the 2-letter code; the value is not checked.
                  example: "TX"
                home_address_zip:
                  type: string
                  nullable: true
                  description: ZIP code (up to 100 characters).
                  example: "78701"
                home_address_lat:
                  type: string
                  nullable: true
                  description: Latitude, as a string.
                home_address_long:
                  type: string
                  nullable: true
                  description: Longitude, as a string.
                home_address_timezone:
                  type: string
                  nullable: true
                  description: Time zone of the home address.
                emergency_contact_name:
                  type: string
                  nullable: true
                  description: Emergency contact's name. `null` clears it.
                emergency_contact_relationship:
                  type: string
                  nullable: true
                  description: Relationship to the employee.
                emergency_phone:
                  type: string
                  nullable: true
                  description: Emergency contact's phone number.
                emergency_address_line_1:
                  type: string
                  nullable: true
                  description: Emergency contact's street line.
                emergency_address_line_2:
                  type: string
                  nullable: true
                  description: Emergency contact's apartment or suite line.
                emergency_address_lat:
                  type: string
                  nullable: true
                  description: Latitude, as a string.
                emergency_address_long:
                  type: string
                  nullable: true
                  description: Longitude, as a string.
                emergency_address_timezone:
                  type: string
                  nullable: true
                  description: Time zone of the emergency contact's address.
                employee_personal_detail:
                  type: array
                  nullable: true
                  description: >
                    Your company's custom personal fields. Replaces the stored list:
                    send every field you want to keep. `null` removes them all. Get
                    ids from `GET /v1/custom-fields?type=employee`.
                  items:
                    type: object
                    required:
                      - id
                      - value
                    properties:
                      id:
                        type: integer
                        minimum: 1
                        description: Custom field id, as a JSON number.
                      value:
                        nullable: true
                        description: The value to store, usually a string. `null` is allowed.
                      field_name:
                        type: string
                        description: Optional label, stored with the value.
                      field_type:
                        type: string
                        description: Optional field type, stored with the value.
                employee_admin_only_fields:
                  type: array
                  description: >
                    Your company's admin-only custom fields. Merged by `id`: send only
                    the fields you want to change. The stored `field_name` comes from
                    the field definition. Get ids from
                    `GET /v1/custom-fields?type=employee_admin`.
                  items:
                    type: object
                    required:
                      - id
                      - value
                    properties:
                      id:
                        type: integer
                        minimum: 1
                        description: Admin-only field id, as a JSON number.
                      value:
                        nullable: true
                        description: The value to store, usually a string. `null` is allowed.
            examples:
              admin_only_fields:
                summary: Set an admin-only field
                value:
                  user_id: 4821
                  employee_admin_only_fields:
                    - id: 1
                      value: "Rookie Rep"
              contact_details:
                summary: Change email and mobile number
                value:
                  user_id: 4821
                  email: "alex.morgan@example.com"
                  mobile_no: "5125550142"
              custom_fields:
                summary: Update custom fields (send the full list)
                value:
                  user_id: 4821
                  employee_personal_detail:
                    - id: 1
                      value: "1991-05-15"
                    - id: 2
                      value: "Alex"
      responses:
        '200':
          description: Profile updated
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          data:
                            type: object
                            description: The updated user. In the rare case the user cannot be read back after saving, this holds only `id`; the update was still saved.
                            properties:
                              id:
                                type: integer
                                description: User id.
                              employee_id:
                                type: string
                                nullable: true
                                description: Your company's employee number.
                              first_name:
                                type: string
                                description: First name.
                              middle_name:
                                type: string
                                nullable: true
                                description: Middle name.
                              last_name:
                                type: string
                                description: Last name.
                              sex:
                                type: string
                                nullable: true
                                description: "`male`, `female` or `other`."
                              dob:
                                type: string
                                nullable: true
                                description: Date of birth, YYYY-MM-DD.
                              email:
                                type: string
                                description: Email address.
                              mobile_no:
                                type: string
                                nullable: true
                                description: Mobile number as stored.
                              home_address:
                                type: string
                                nullable: true
                                description: Formatted single-line home address. The response also returns every other `home_address_*` field, including `_lat`, `_long` and `_timezone`.
                              emergency_contact_name:
                                type: string
                                nullable: true
                                description: Emergency contact's name. The response also returns the other `emergency_*` fields.
                              employee_personal_detail:
                                type: array
                                nullable: true
                                description: The stored custom fields, as sent.
                                items:
                                  type: object
                              is_manager:
                                type: integer
                                description: 1 if the user is a manager.
                              status_id:
                                type: integer
                                description: Always 1 (only active users can be updated).
                              office_id:
                                type: integer
                                nullable: true
                                description: Current office id.
                              office_name:
                                type: string
                                nullable: true
                                description: Current office name.
                              state_code:
                                type: string
                                nullable: true
                                description: Work state code.
                              created_at:
                                type: string
                                description: "`YYYY-MM-DD HH:MM:SS`, UTC."
                              updated_at:
                                type: string
                                description: "`YYYY-MM-DD HH:MM:SS`, UTC."
              example:
                status: 200
                message: "User profile updated successfully"
                data:
                  requestedBy: "acme"
                  data:
                    id: 4821
                    employee_id: "EMP-1042"
                    first_name: "Alex"
                    middle_name: null
                    last_name: "Morgan"
                    sex: "female"
                    dob: "1990-01-15"
                    email: "alex.morgan@example.com"
                    mobile_no: "5125550142"
                    home_address: "1200 Congress Ave, Austin, TX 78701, USA"
                    home_address_line_1: "1200 Congress Ave"
                    home_address_line_2: null
                    home_address_city: "Austin"
                    home_address_state: "TX"
                    home_address_zip: "78701"
                    home_address_lat: null
                    home_address_long: null
                    home_address_timezone: null
                    emergency_contact_name: "Jamie Morgan"
                    emergency_contact_relationship: "Sibling"
                    emergency_phone: "5125550199"
                    emergency_address_line_1: null
                    emergency_address_line_2: null
                    emergency_address_lat: null
                    emergency_address_long: null
                    emergency_address_timezone: null
                    employee_personal_detail:
                      - id: 1
                        value: "1991-05-15"
                      - id: 2
                        value: "Alex"
                    is_manager: 0
                    status_id: 1
                    office_id: 31
                    created_at: "2024-01-15 10:00:00"
                    updated_at: "2026-10-08 15:04:05"
                    state_code: "TX"
                    office_name: "Austin"
        '400':
          description: Invalid body or failed validation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_user_id:
                  summary: user_id missing or not a positive integer
                  value:
                    status: 400
                    message: "Invalid or missing user_id in request body"
                    data: {}
                nothing_to_update:
                  summary: Only user_id (or only ignored fields) sent
                  value:
                    status: 400
                    message: "No fields provided to update"
                    data: {}
                validation_error:
                  summary: Field validation failed
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        email: "Invalid email format"
                        dob: "dob is not a valid calendar date"
                custom_field_error:
                  summary: Custom field id sent as a string
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        employee_personal_detail: "Element at index 0 must include both id and value"
                duplicate_email:
                  summary: Email already used by another active employee
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        email: "This email is being used by Jordan Lee (jordan.lee@example.com). Please use a different email."
                duplicate_mobile_hiring:
                  summary: Mobile number already on another hiring record
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        mobile_no: "Mobile number already exists in onboarding employees"
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: No active user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User 4821 not found"
                data: {}
        '409':
          description: Another update to the same user was in progress. Retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 409
                message: "Conflict: request could not be completed due to a concurrent update. Please retry."
                data: {}
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}:
    get:
      operationId: getUser
      tags:
        - Users
      summary: Get a user
      description: |
        Returns one user by id, whatever their status, with the same fields as `GET /v1/users`. The user is at `data.users[0]`: the response uses the list wrapper, not a single object.

        **Before you call:**

        - `id` is the user id from `GET /v1/users`, not an onboarding id or your `employee_id`.
        - Optional: `include=additional_offices` adds current Additional Office assignments. Other query parameters return `400`.

        **Formats:**

        - Same as `GET /v1/users`: `created_at` and `updated_at` are ISO 8601 UTC strings, `dob` is `YYYY-MM-DD` or `null`, and home address fields are `null` until the rep completes the profile step of onboarding.
        - `current_page`, `per_page`, `total` and `last_page` are always `1`, `50`, `1` and `1`. Ignore them.
        - `requestedBy` is the name of the API credential your token belongs to.

        **Errors:**

        - `400` `Invalid user id` when `id` does not start with a positive number. Trailing characters are ignored, so `4821abc` reads as `4821`.
        - `400` `Only include is allowed when fetching a single user by id`.
        - `400` for an unsupported or empty `include` value.
        - `404` `User not found`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.
        - `500` if requested Additional Offices cannot be looked up; retry according to Errors and retries. A missing assignments table returns `[]`.

        **Related:**

        - `GET /v1/users` lists and filters users.
        - `POST /v1/users` updates profile fields; `POST /v1/users/{id}/transfer`, `/position` and `/terminate` change assignment and employment.
      security:
        - bearerAuth: []
      parameters:
        - name: include
          in: query
          required: false
          description: Request optional Additional Office assignments. Omit to leave additional_offices out of the response.
          schema:
            type: string
            enum: [additional_offices]
          example: additional_offices
        - name: id
          in: path
          required: true
          description: User id from `GET /v1/users`.
          schema:
            type: integer
            minimum: 1
          example: 4821
      responses:
        '200':
          description: The user, as the only item of `data.users`
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          current_page:
                            type: integer
                            description: Always 1.
                          per_page:
                            type: integer
                            description: Always 50. Ignore it.
                          total:
                            type: integer
                            description: Always 1.
                          last_page:
                            type: integer
                            description: Always 1.
                          users:
                            type: array
                            description: Exactly one user.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: User id. Every other user endpoint takes this id.
                                employee_id:
                                  type: string
                                  nullable: true
                                  description: Your company's own employee number.
                                first_name:
                                  type: string
                                  description: First name.
                                last_name:
                                  type: string
                                  description: Last name.
                                email:
                                  type: string
                                  description: Email address.
                                mobile_no:
                                  type: string
                                  nullable: true
                                  description: Mobile number as stored. The format is not normalized.
                                dob:
                                  type: string
                                  format: date
                                  nullable: true
                                  description: Date of birth, YYYY-MM-DD.
                                home_address:
                                  type: string
                                  nullable: true
                                  description: Formatted single-line home address. Null until the rep completes the profile step of onboarding.
                                home_address_line_1:
                                  type: string
                                  nullable: true
                                  description: Street line.
                                home_address_line_2:
                                  type: string
                                  nullable: true
                                  description: Apartment or suite line. Usually null.
                                home_address_city:
                                  type: string
                                  nullable: true
                                  description: City.
                                home_address_state:
                                  type: string
                                  nullable: true
                                  description: State, normally a 2-letter code.
                                home_address_zip:
                                  type: string
                                  nullable: true
                                  description: ZIP code.
                                is_manager:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 if the user is a manager.
                                status_id:
                                  type: integer
                                  nullable: true
                                  description: Employment status. 1 is active; any other value is inactive (a dismissal through `POST /v1/users/termination` sets 2).
                                worker_type:
                                  type: string
                                  nullable: true
                                  description: Worker type, such as `1099` or `w2`. Compare case-insensitively.
                                office_id:
                                  type: integer
                                  nullable: true
                                  description: Current office. See `GET /v1/locations`.
                                office_name:
                                  type: string
                                  nullable: true
                                  description: Name of the current office.
                                state_id:
                                  type: integer
                                  nullable: true
                                  description: Work state id (not the home state).
                                state_code:
                                  type: string
                                  nullable: true
                                  description: Work state code, for example `TX`.
                                city_id:
                                  type: integer
                                  nullable: true
                                  description: Work city id.
                                position_id:
                                  type: integer
                                  nullable: true
                                  description: Primary position. See `GET /v1/positions`.
                                position_name:
                                  type: string
                                  nullable: true
                                  description: Name of the primary position.
                                sub_position_id:
                                  type: integer
                                  nullable: true
                                  description: Position in effect today in your company's time zone. Can differ from `position_id`.
                                sub_position_name:
                                  type: string
                                  nullable: true
                                  description: Name of the position in effect today in your company's time zone.
                                wages_status:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 when the rep's position pays wages (hourly or salary). A position setting, not a per-person flag.
                                onboarding_complete:
                                  type: integer
                                  enum: [0, 1]
                                  description: 1 once every required self-onboarding step (documents, banking details, profile) is done.
                                hiring_status_id:
                                  type: integer
                                  nullable: true
                                  description: Status of the rep's latest hiring record (7 = still completing self-onboarding, 14 = finished). Null when the user was not hired through hiring.
                                hiring_status_name:
                                  type: string
                                  nullable: true
                                  description: Label for `hiring_status_id`. Your company can rename it; use it for display only.
                                onboarding_step_name:
                                  type: string
                                  nullable: true
                                  description: >
                                    The self-onboarding step the rep is on, using the names on the
                                    Onboarding page: `Not Started` (never logged in), `Personal Details`,
                                    `Tax + Banking Info`, `Tax Info`, `Banking Info` or `Documents`. The
                                    steps a rep sees depend on your payroll setup and their worker type.
                                    Set only while `hiring_status_id` is `7`, otherwise `null`. Refreshed
                                    every 15 minutes, so it can lag the Onboarding page by up to 15 minutes.
                                onboarding_step_updated_at:
                                  type: string
                                  nullable: true
                                  description: When `onboarding_step_name` last changed (company database time). `null` when `onboarding_step_name` is `null`.
                                employee_personal_detail:
                                  type: array
                                  nullable: true
                                  description: Your company's custom personal fields for this user. Null when none are stored.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Custom field id from `GET /v1/custom-fields?type=employee`.
                                      field_name:
                                        type: string
                                        nullable: true
                                        description: Field label.
                                      field_type:
                                        type: string
                                        nullable: true
                                        description: Field type, for example `text`, `date` or `dropdown`.
                                      value:
                                        nullable: true
                                        description: Stored value, usually a string.
                                employee_admin_only_fields:
                                  type: array
                                  nullable: true
                                  description: Custom fields only admins can edit. Same item shape as `employee_personal_detail`. Write with `POST /v1/users`.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Custom field id.
                                      field_name:
                                        type: string
                                        nullable: true
                                        description: Field label.
                                      field_type:
                                        type: string
                                        nullable: true
                                        description: Field type.
                                      value:
                                        nullable: true
                                        description: Stored value, usually a string.
                                manager:
                                  type: object
                                  nullable: true
                                  description: The user's manager, or null.
                                  properties:
                                    id:
                                      type: integer
                                      description: Manager's user id.
                                    first_name:
                                      type: string
                                      description: First name.
                                    last_name:
                                      type: string
                                      description: Last name.
                                    email:
                                      type: string
                                      description: Email address.
                                recruiter:
                                  type: object
                                  nullable: true
                                  description: The user's recruiter, or null. Same fields as `manager`.
                                  properties:
                                    id:
                                      type: integer
                                      description: Recruiter's user id.
                                    first_name:
                                      type: string
                                      description: First name.
                                    last_name:
                                      type: string
                                      description: Last name.
                                    email:
                                      type: string
                                      description: Email address.
                                additional_offices:
                                  type: array
                                  description: >
                                    Only returned with `include=additional_offices`. The user's current
                                    Additional Office assignments, the same set the
                                    user's profile page shows under Employment Package, except that
                                    assignments to archived offices are left out. Current means started on
                                    or before today and not ended before today; when an office has more than
                                    one current assignment, only the newest is returned. One entry per
                                    office, ordered by office name. `[]` when the user has none or the
                                    tenant has no assignments table. Other lookup failures return 500.
                                    Override pay for these offices is not included.
                                    "Today" means today in your company's time zone.
                                  items:
                                    type: object
                                    properties:
                                      office_id:
                                        type: integer
                                        description: Office id. See `GET /v1/locations`.
                                      office_name:
                                        type: string
                                        nullable: true
                                        description: Office name.
                                      state_id:
                                        type: integer
                                        nullable: true
                                        description: State id of the assignment.
                                      state_code:
                                        type: string
                                        nullable: true
                                        description: State code, for example `TX`.
                                      effective_date:
                                        type: string
                                        format: date
                                        nullable: true
                                        description: Date the assignment started, YYYY-MM-DD. Null only for legacy records stored with a zero date.
                                      effective_end_date:
                                        type: string
                                        format: date
                                        nullable: true
                                        description: Last day of the assignment, YYYY-MM-DD, or null when it has no end date.
                                created_at:
                                  type: string
                                  format: date-time
                                  description: When the user was created, ISO 8601 UTC.
                                updated_at:
                                  type: string
                                  format: date-time
                                  description: When the user was last changed, ISO 8601 UTC.
              examples:
                with_additional_offices:
                  summary: With include=additional_offices
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 50
                      total: 1
                      last_page: 1
                      users:
                        - id: 4821
                          employee_id: "EMP-1042"
                          first_name: "Alex"
                          last_name: "Morgan"
                          email: "alex.morgan@example.com"
                          dob: "1990-01-15"
                          mobile_no: "5125550142"
                          is_manager: 0
                          status_id: 1
                          worker_type: "1099"
                          office_id: 31
                          home_address: "1200 Congress Ave, Austin, TX 78701, USA"
                          home_address_line_1: "1200 Congress Ave"
                          home_address_line_2: null
                          home_address_city: "Austin"
                          home_address_state: "TX"
                          home_address_zip: "78701"
                          state_id: 44
                          city_id: 1207
                          created_at: "2024-01-15T10:00:00.000Z"
                          updated_at: "2026-06-01T08:30:00.000Z"
                          employee_personal_detail:
                            - id: 2
                              field_name: "Preferred first name"
                              field_type: "text"
                              value: "Alex"
                          employee_admin_only_fields: null
                          state_code: "TX"
                          office_name: "Austin"
                          wages_status: 0
                          onboarding_complete: 1
                          hiring_status_id: 14
                          hiring_status_name: "Active"
                          onboarding_step_name: null
                          onboarding_step_updated_at: null
                          position_id: 4
                          position_name: "Sales Rep"
                          sub_position_id: 12
                          sub_position_name: "Senior Sales Rep"
                          manager:
                            id: 87
                            first_name: "Jordan"
                            last_name: "Lee"
                            email: "jordan.lee@example.com"
                          recruiter: null
                          additional_offices: []
        '400':
          description: Invalid id, unsupported include value, or a query parameter other than include
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive number
                  value:
                    status: 400
                    message: "Invalid user id"
                    data: {}
                query_params_with_id:
                  summary: Query parameter other than include sent with an id
                  value:
                    status: 400
                    message: "Only include is allowed when fetching a single user by id"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: No user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/candidates/stages:
    get:
      operationId: listCandidateStages
      tags:
        - Candidates
      summary: List candidate pipeline stages
      description: |
        Returns your company's candidate pipeline stages (the columns of the hiring pipeline in Sequifi) in display order. Use a stage's `status_name` as the `pipeline_status` filter on `GET /v1/candidates`. These stages are not onboarding statuses: those are the `status_id` values on `GET /v1/onboarding`.

        **What happens:**

        - Read-only. Hidden and deleted stages are left out.
        - Not paginated: every stage comes back in one response.
        - Query parameters are ignored.

        **Formats:**

        - `id` and `display_order` are integers. Candidates are filtered by stage name, not by stage id.
        - `colour_code` is a hex color string, for example `#E4E9FF`.

        **Related:**

        - `GET /v1/candidates?pipeline_status=<status_name>` lists the candidates in one stage.
      security:
        - bearerAuth: []
      responses:
        '200':
          description: The company's active pipeline stages, in display order.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      stages:
                        type: array
                        description: Active stages, ordered by `display_order`, then `id`.
                        items:
                          type: object
                          properties:
                            id:
                              type: integer
                              description: Stage id.
                            status_name:
                              type: string
                              description: Stage name. Pass it as `pipeline_status` on `GET /v1/candidates`.
                            display_order:
                              type: integer
                              description: Position of the stage in the pipeline.
                            colour_code:
                              type: string
                              description: Hex color shown for the stage in Sequifi.
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  stages:
                    - id: 1
                      status_name: "New"
                      display_order: 1
                      colour_code: "#E4E9FF"
                    - id: 3
                      status_name: "Phone Screen"
                      display_order: 3
                      colour_code: "#E4E9FF"
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/candidates:
    get:
      operationId: listCandidates
      tags:
        - Candidates
      summary: List candidates
      description: |
        Lists candidates: people in your recruiting pipeline who are not yet onboarding records. Results are newest first, 20 per page by default. There is no date filter, so a sync has to page through the whole list each time.

        **Filtering and paging:**

        - Filters combine with AND.
        - `first_name`, `last_name`, `full_name`, `email`, `mobile_no`, `source` and `lead_status` are partial, case-insensitive matches. `_` and `%` in a value act as wildcards, so `email=jo_n@example.com` also matches `join@example.com`. Compare exact values on your side before you treat a result as a match.
        - `lead_status` matches the candidate's free-text status (for example `Follow Up`). `pipeline_status` is an exact stage name from `GET /v1/candidates/stages` (case-insensitive).
        - `recruiter_id` is an exact user id.
        - `page` starts at 1. `per_page` defaults to 20, maximum 200. `last_page` is `0` when nothing matches, and a page past the end returns an empty `candidates` array.
        - Sorted by `id`, newest first. Candidates added while you page shift later pages, so de-duplicate on `id`.
        - Unknown query parameters are rejected with `400`.

        **Formats:**

        - `interview_date` and `pipeline_status_date` are calendar days returned as midnight UTC, for example `"2026-06-03T00:00:00.000Z"`. Use the first 10 characters. Converting them to a US time zone shows the previous day.
        - `interview_time` is free text as entered in Sequifi, for example `"14:30:00"` or `"2:30 PM"`.
        - `last_hired_date`, `created_at` and `updated_at` are UTC timestamps, for example `"2026-05-20T09:12:44.000Z"`.
        - `lead_rating`, `custom_rating` and `overall_rating` are decimal strings such as `"4.00"`, or null.
        - `custom_fields_detail` is an array of `{id, field_name, field_type, value}`. It is `[]` when cleared and null when never set.
        - `status` is the free-text status. `pipeline_status` is the stage name, or null when unset or when the stage was hidden or deleted.
        - `recruiter` and `reporting_manager` are `{id, first_name, last_name, email}`, or null when unset or when that user no longer exists.
        - `filters` echoes the filters you applied, keyed by parameter name, or is null.

        **Errors:**

        - `400 Invalid query parameter(s)`, with `data.invalid_params` and `data.allowed_params`.
        - `400 Bad Request: page must be a positive integer`
        - `400 Bad Request: per_page must be a positive integer between 1 and 200`
        - `400 Bad Request: recruiter_id must be a positive integer`

        **Related:**

        - `GET /v1/candidates/{id}` returns one candidate.
        - To start onboarding someone, call `POST /v1/onboarding` and pass the candidate `id` as `lead_id` to keep the link. Creating the onboarding record does not change the candidate.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          description: Page number, starting at 1.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Records per page. Default 20, maximum 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 20
          example: 20
        - name: first_name
          in: query
          required: false
          description: Partial, case-insensitive match on first name.
          schema:
            type: string
          example: Alex
        - name: last_name
          in: query
          required: false
          description: Partial, case-insensitive match on last name.
          schema:
            type: string
          example: Morgan
        - name: full_name
          in: query
          required: false
          description: Partial, case-insensitive match on first name, a space, then last name.
          schema:
            type: string
          example: Alex Morgan
        - name: email
          in: query
          required: false
          description: Partial, case-insensitive match on email. `_` and `%` act as wildcards; compare the exact address on your side.
          schema:
            type: string
          example: alex.morgan@example.com
        - name: mobile_no
          in: query
          required: false
          description: Partial match on mobile number.
          schema:
            type: string
          example: "5125550148"
        - name: lead_status
          in: query
          required: false
          description: Partial, case-insensitive match on the candidate's free-text status, for example `Follow Up`. Not the pipeline stage.
          schema:
            type: string
          example: Follow Up
        - name: pipeline_status
          in: query
          required: false
          description: Exact pipeline stage name (case-insensitive), from `GET /v1/candidates/stages`.
          schema:
            type: string
          example: Phone Screen
        - name: source
          in: query
          required: false
          description: Partial, case-insensitive match on the candidate's source.
          schema:
            type: string
          example: Referral
        - name: recruiter_id
          in: query
          required: false
          description: Exact recruiter user id.
          schema:
            type: integer
            minimum: 1
          example: 57
      responses:
        '200':
          description: One page of candidates. An empty page is still a `200`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      current_page:
                        type: integer
                        description: The page returned.
                      per_page:
                        type: integer
                        description: Page size used.
                      total:
                        type: integer
                        description: Number of candidates that match the filters.
                      last_page:
                        type: integer
                        description: Last page number. `0` when nothing matches.
                      filters:
                        type: object
                        nullable: true
                        description: The filters you applied, keyed by parameter name. Null when none.
                      candidates:
                        type: array
                        description: Candidates on this page, newest first.
                        items:
                          type: object
                          properties:
                            id:
                              type: integer
                              description: Candidate id. Pass it as `lead_id` on `POST /v1/onboarding`.
                            first_name:
                              type: string
                              description: First name.
                            last_name:
                              type: string
                              description: Last name.
                            email:
                              type: string
                              nullable: true
                              description: Email address.
                            mobile_no:
                              type: string
                              nullable: true
                              description: Mobile number as stored.
                            source:
                              type: string
                              nullable: true
                              description: Where the candidate came from.
                            status:
                              type: string
                              nullable: true
                              description: Free-text status, for example `Follow Up`.
                            pipeline_status:
                              type: string
                              nullable: true
                              description: Pipeline stage name, or null when unset, hidden or deleted.
                            pipeline_status_date:
                              type: string
                              nullable: true
                              description: Day the stage was set, as midnight UTC. Use the date part.
                            interview_date:
                              type: string
                              nullable: true
                              description: Interview day, as midnight UTC. Use the date part.
                            interview_time:
                              type: string
                              nullable: true
                              description: Interview time as free text.
                            last_hired_date:
                              type: string
                              nullable: true
                              description: UTC timestamp of the last hire, if any.
                            lead_rating:
                              type: string
                              nullable: true
                              description: Rating as a decimal string.
                            custom_rating:
                              type: string
                              nullable: true
                              description: Custom rating as a decimal string.
                            overall_rating:
                              type: string
                              nullable: true
                              description: Overall rating as a decimal string.
                            custom_fields_detail:
                              type: array
                              nullable: true
                              description: Candidate custom fields. `[]` when cleared, null when never set.
                              items:
                                type: object
                                properties:
                                  id: { type: integer, nullable: true, description: Custom field id. }
                                  field_name: { type: string, nullable: true, description: Field name. }
                                  field_type: { type: string, nullable: true, description: 'Field type, for example `text`.' }
                                  value: { description: Stored value as entered. Usually a string. }
                            comments:
                              type: string
                              nullable: true
                              description: Free-text comments.
                            state_code:
                              type: string
                              nullable: true
                              description: Two-letter state code.
                            office_name:
                              type: string
                              nullable: true
                              description: Office name.
                            recruiter:
                              type: object
                              nullable: true
                              description: '`{id, first_name, last_name, email}` of the recruiter, or null.'
                            reporting_manager:
                              type: object
                              nullable: true
                              description: '`{id, first_name, last_name, email}` of the reporting manager, or null.'
                            created_at:
                              type: string
                              description: UTC timestamp.
                            updated_at:
                              type: string
                              description: UTC timestamp.
              examples:
                list_response:
                  summary: One page of candidates
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 20
                      total: 1
                      last_page: 1
                      filters:
                        lead_status: "Follow Up"
                      candidates:
                        - id: 1093
                          first_name: "Alex"
                          last_name: "Morgan"
                          email: "alex.morgan@example.com"
                          mobile_no: "5125550148"
                          source: "Referral"
                          status: "Follow Up"
                          interview_date: "2026-06-03T00:00:00.000Z"
                          interview_time: "14:30:00"
                          last_hired_date: null
                          pipeline_status_date: "2026-05-27T00:00:00.000Z"
                          lead_rating: "4.00"
                          custom_rating: "3.50"
                          overall_rating: "3.75"
                          custom_fields_detail:
                            - id: 12
                              field_name: "Resume URL"
                              field_type: "text"
                              value: "https://example.com/resume.pdf"
                          comments: "Strong closer, available immediately."
                          created_at: "2026-05-20T09:12:44.000Z"
                          updated_at: "2026-05-27T16:03:10.000Z"
                          state_code: "TX"
                          office_name: "Austin"
                          pipeline_status: "Phone Screen"
                          recruiter:
                            id: 57
                            first_name: "Jamie"
                            last_name: "Chen"
                            email: "jamie.chen@example.com"
                          reporting_manager:
                            id: 312
                            first_name: "Riley"
                            last_name: "Brooks"
                            email: "riley.brooks@example.com"
                empty_response:
                  summary: No candidates match the filters
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 20
                      total: 0
                      last_page: 0
                      filters:
                        email: "nobody@example.com"
                      candidates: []
        '400':
          description: An unknown query parameter or an invalid paging or `recruiter_id` value.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["pipeline_status_id"]
                      allowed_params: ["first_name", "last_name", "full_name", "email", "mobile_no", "lead_status", "pipeline_status", "source", "recruiter_id", "page", "per_page"]
                invalid_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "Bad Request: per_page must be a positive integer between 1 and 200"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/candidates/{id}:
    get:
      operationId: getCandidate
      tags:
        - Candidates
      summary: Get a candidate
      description: |
        Returns one candidate by id. The response uses the list shape: a `candidates` array with one item, plus paging fields fixed at `current_page: 1`, `per_page: 50`, `total: 1` and `last_page: 1`.

        **Formats:**

        - Same fields and formats as `GET /v1/candidates`. Interview and stage dates are midnight UTC; use the date part.

        **Errors:**

        - `400 Invalid candidate id`: the id is not a positive whole number.
        - `400 Cannot use query parameters when fetching a single candidate by id`
        - `404 Candidate not found`: no candidate has this id. Onboarding ids and user ids are different numbers and also return `404`.

        **Related:**

        - `POST /v1/onboarding` with `lead_id` set to this id starts onboarding for the candidate.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Candidate id, from `GET /v1/candidates`.
          schema:
            type: integer
            minimum: 1
          example: 1093
      responses:
        '200':
          description: The candidate, as a one-item list.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      current_page:
                        type: integer
                        description: Always 1.
                      per_page:
                        type: integer
                        description: Always 50.
                      total:
                        type: integer
                        description: Always 1.
                      last_page:
                        type: integer
                        description: Always 1.
                      candidates:
                        type: array
                        description: Exactly one candidate, with the same fields as `GET /v1/candidates`.
                        items:
                          type: object
                          properties:
                            id: { type: integer, description: Candidate id. }
                            first_name: { type: string, description: First name. }
                            last_name: { type: string, description: Last name. }
                            email: { type: string, nullable: true, description: Email address. }
                            mobile_no: { type: string, nullable: true, description: Mobile number as stored. }
                            status: { type: string, nullable: true, description: Free-text status. }
                            pipeline_status: { type: string, nullable: true, description: 'Pipeline stage name, or null.' }
                            interview_date: { type: string, nullable: true, description: Interview day as midnight UTC. Use the date part. }
                            recruiter: { type: object, nullable: true, description: '`{id, first_name, last_name, email}`, or null.' }
                            reporting_manager: { type: object, nullable: true, description: '`{id, first_name, last_name, email}`, or null.' }
                            updated_at: { type: string, description: UTC timestamp. }
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 50
                  total: 1
                  last_page: 1
                  candidates:
                    - id: 1093
                      first_name: "Alex"
                      last_name: "Morgan"
                      email: "alex.morgan@example.com"
                      mobile_no: "5125550148"
                      source: "Referral"
                      status: "Follow Up"
                      interview_date: "2026-06-03T00:00:00.000Z"
                      interview_time: "14:30:00"
                      last_hired_date: null
                      pipeline_status_date: "2026-05-27T00:00:00.000Z"
                      lead_rating: "4.00"
                      custom_rating: "3.50"
                      overall_rating: "3.75"
                      custom_fields_detail:
                        - id: 12
                          field_name: "Resume URL"
                          field_type: "text"
                          value: "https://example.com/resume.pdf"
                      comments: "Strong closer, available immediately."
                      created_at: "2026-05-20T09:12:44.000Z"
                      updated_at: "2026-05-27T16:03:10.000Z"
                      state_code: "TX"
                      office_name: "Austin"
                      pipeline_status: "Phone Screen"
                      recruiter:
                        id: 57
                        first_name: "Jamie"
                        last_name: "Chen"
                        email: "jamie.chen@example.com"
                      reporting_manager:
                        id: 312
                        first_name: "Riley"
                        last_name: "Brooks"
                        email: "riley.brooks@example.com"
        '400':
          description: The id is invalid, or query parameters were sent with it.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid candidate id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single candidate by id"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: No candidate has this id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Candidate not found"
                data: {}
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/locations:
    get:
      operationId: listLocations
      tags:
        - Locations
      summary: List locations
      description: |
        Returns your company's offices, newest first, so you can map office names to the `office_id` that users, onboarding records and transfers use. Inactive offices are included unless you pass `status=active`. Archived offices and records without an office name are never returned.

        **Filtering and paging:**

        - `status=active` returns offices whose `office_status` is `1`; `status=inactive` returns the rest. Leave it out for both. Any other value returns `400`, and so does any other query parameter.
        - `per_page` defaults to 50 and has no upper limit. A value that is not a positive number is quietly replaced by 50.
        - `page` starts at 1. `0` or a non-number is read as 1. A negative `page` returns `500`, so always send a positive whole number.
        - Results are ordered by `id`, newest first, with offset paging. A page past the end returns an empty `locations` array, and `last_page` is `0` when nothing matches.
        - The metadata key is `requested_by` (snake_case) on this route but `requestedBy` on `GET /v1/locations/{id}`.

        **Formats:**

        - `office_status` is `1` for an active office. Any other value is inactive.
        - `created_at` and `updated_at` are ISO 8601 UTC strings, for example `2024-03-01T17:20:00.000Z`.
        - `lat` and `long` are numbers or `null`.
        - Each location also carries internal configuration fields that are not listed here (payroll setup, rate settings and similar). Do not depend on them: they can change or disappear without notice.

        **Errors:**

        - `400` `Invalid query parameter(s)`, with `invalid_params` and `allowed_params` in `data`.
        - `400` `Bad Request: status must be 'active' or 'inactive'`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/locations/{id}` returns one office.
        - `POST /v1/users/{id}/transfer` and `POST /v1/onboarding` take an `office_id` from this list. `GET /v1/users` reports each user's `office_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: per_page
          in: query
          required: false
          description: Offices per page. No upper limit. Values that are not a positive number become 50.
          schema:
            type: integer
            minimum: 1
            default: 50
          example: 50
        - name: page
          in: query
          required: false
          description: Page number, starting at 1. Send a positive whole number; a negative value returns 500.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: status
          in: query
          required: false
          description: "`active` (`office_status` is 1) or `inactive` (any other value). Not case-sensitive. Leave it out for both."
          schema:
            type: string
            enum: [active, inactive]
          example: active
      responses:
        '200':
          description: A page of offices
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Name of the API credential your token belongs to.
                          current_page:
                            type: integer
                            description: The page returned.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Offices matching the filter, across all pages.
                          last_page:
                            type: integer
                            description: Number of the last page. 0 when nothing matches.
                          filters:
                            type: object
                            nullable: true
                            description: "`{\"status\": \"active\"}` or `{\"status\": \"inactive\"}` when a status filter was applied, otherwise null."
                          locations:
                            type: array
                            description: Offices on this page, newest first.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Office id. Use it as `office_id` elsewhere.
                                office_name:
                                  type: string
                                  description: Office name.
                                office_status:
                                  type: integer
                                  description: 1 for active; any other value is inactive.
                                general_code:
                                  type: string
                                  nullable: true
                                  description: Your company's code for the office, if set.
                                work_site_id:
                                  type: string
                                  nullable: true
                                  description: Work site identifier, if set.
                                state_id:
                                  type: integer
                                  description: State the office is in.
                                city_id:
                                  type: integer
                                  nullable: true
                                  description: City the office is in.
                                business_address:
                                  type: string
                                  nullable: true
                                  description: Street address.
                                business_city:
                                  type: string
                                  nullable: true
                                  description: City.
                                business_state:
                                  type: string
                                  nullable: true
                                  description: State.
                                business_zip:
                                  type: string
                                  nullable: true
                                  description: ZIP code.
                                mailing_address:
                                  type: string
                                  nullable: true
                                  description: Mailing street address.
                                mailing_city:
                                  type: string
                                  nullable: true
                                  description: Mailing city.
                                mailing_state:
                                  type: string
                                  nullable: true
                                  description: Mailing state.
                                mailing_zip:
                                  type: string
                                  nullable: true
                                  description: Mailing ZIP code.
                                lat:
                                  type: number
                                  nullable: true
                                  description: Latitude.
                                long:
                                  type: number
                                  nullable: true
                                  description: Longitude.
                                time_zone:
                                  type: string
                                  nullable: true
                                  description: Office time zone, as entered in Sequifi.
                                created_at:
                                  type: string
                                  format: date-time
                                  nullable: true
                                  description: When the office was created, ISO 8601 UTC.
                                updated_at:
                                  type: string
                                  format: date-time
                                  nullable: true
                                  description: When the office was last changed, ISO 8601 UTC.
              examples:
                all_offices:
                  summary: Every non-archived office (no status filter)
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: "acme"
                      current_page: 1
                      per_page: 50
                      total: 2
                      last_page: 1
                      filters: null
                      locations:
                        - id: 31
                          office_name: "Austin"
                          office_status: 1
                          general_code: "ATX"
                          work_site_id: null
                          state_id: 44
                          city_id: 1207
                          business_address: "500 E 4th St"
                          business_city: "Austin"
                          business_state: "TX"
                          business_zip: "78701"
                          mailing_address: null
                          mailing_city: null
                          mailing_state: null
                          mailing_zip: null
                          lat: 30.2655
                          long: -97.7382
                          time_zone: null
                          created_at: "2024-03-01T17:20:00.000Z"
                          updated_at: "2026-02-11T09:05:00.000Z"
                        - id: 19
                          office_name: "Dallas"
                          office_status: 0
                          general_code: null
                          work_site_id: null
                          state_id: 44
                          city_id: 1188
                          business_address: null
                          business_city: null
                          business_state: null
                          business_zip: null
                          mailing_address: null
                          mailing_city: null
                          mailing_state: null
                          mailing_zip: null
                          lat: null
                          long: null
                          time_zone: null
                          created_at: "2023-08-14T15:00:00.000Z"
                          updated_at: "2025-11-30T12:00:00.000Z"
                no_offices:
                  summary: Nothing matches
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: "acme"
                      current_page: 1
                      per_page: 50
                      total: 0
                      last_page: 0
                      filters:
                        status: inactive
                      locations: []
        '400':
          description: Unknown query parameter or invalid `status`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unknown_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["office"]
                      allowed_params: ["page", "per_page", "status"]
                bad_status:
                  summary: status is not active or inactive
                  value:
                    status: 400
                    message: "Bad Request: status must be 'active' or 'inactive'"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error, including a negative `page`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/locations/{id}:
    get:
      operationId: getLocation
      tags:
        - Locations
      summary: Get a location
      description: |
        Returns one office by id, active or inactive, as a single object at `data.location`. Archived offices return `404`, so an `office_id` stored on an older user or record can return `404` here.

        **Before you call:**

        - Take the id from `GET /v1/locations` or from an `office_id` on a user or onboarding record.
        - Do not add query parameters. Any query parameter returns `400`.

        **Formats:**

        - Same fields as each item of `GET /v1/locations`, without a list wrapper.
        - By id, this route can also return internal rate records that have no office name (the list hides them). Treat a location whose `office_name` is empty or `null` as not an office.
        - The metadata key is `requestedBy` (camelCase) here but `requested_by` on the list.
        - Internal configuration fields that are not listed here can appear in the object. Do not depend on them.

        **Errors:**

        - `400` `Invalid location id` when `id` does not start with a positive number. Trailing characters are ignored, so `31abc` reads as `31`.
        - `400` `Cannot use query parameters when fetching a single location by id`.
        - `404` `Location not found` for an unknown or archived office.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/locations` lists offices.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Office id.
          schema:
            type: integer
            minimum: 1
          example: 31
      responses:
        '200':
          description: The office
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          location:
                            type: object
                            description: The office. Same fields as each item of `GET /v1/locations`.
                            properties:
                              id:
                                type: integer
                                description: Office id.
                              office_name:
                                type: string
                                nullable: true
                                description: Office name. Empty or null for internal rate records.
                              office_status:
                                type: integer
                                description: 1 for active; any other value is inactive.
                              general_code:
                                type: string
                                nullable: true
                                description: Your company's code for the office, if set.
                              state_id:
                                type: integer
                                description: State the office is in.
                              city_id:
                                type: integer
                                nullable: true
                                description: City the office is in.
                              business_address:
                                type: string
                                nullable: true
                                description: Street address. `business_city`, `business_state`, `business_zip` and the `mailing_*` fields are returned too.
                              lat:
                                type: number
                                nullable: true
                                description: Latitude.
                              long:
                                type: number
                                nullable: true
                                description: Longitude.
                              time_zone:
                                type: string
                                nullable: true
                                description: Office time zone, as entered in Sequifi.
                              created_at:
                                type: string
                                format: date-time
                                nullable: true
                                description: ISO 8601 UTC.
                              updated_at:
                                type: string
                                format: date-time
                                nullable: true
                                description: ISO 8601 UTC.
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  location:
                    id: 31
                    office_name: "Austin"
                    office_status: 1
                    general_code: "ATX"
                    work_site_id: null
                    state_id: 44
                    city_id: 1207
                    business_address: "500 E 4th St"
                    business_city: "Austin"
                    business_state: "TX"
                    business_zip: "78701"
                    mailing_address: null
                    mailing_city: null
                    mailing_state: null
                    mailing_zip: null
                    lat: 30.2655
                    long: -97.7382
                    time_zone: null
                    created_at: "2024-03-01T17:20:00.000Z"
                    updated_at: "2026-02-11T09:05:00.000Z"
        '400':
          description: Invalid id, or query parameters sent with an id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive number
                  value:
                    status: 400
                    message: "Invalid location id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with an id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single location by id"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: Unknown or archived office
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Location not found"
                data: {}
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/positions:
    get:
      operationId: listPositions
      tags:
        - Positions
      summary: List positions
      description: |
        Returns your company's active positions in id order (oldest first), with each position's department, permission group, pay frequency and child positions. Use it to map position names to the `position_id` that onboarding and position changes take. Inactive positions and built-in system positions are never returned, so a `position_id` or `sub_position_id` on a user may not appear here.

        **Filtering and paging:**

        - All filters are optional and combine with AND. Any other query parameter returns `400`.
        - `position_name` is a case-insensitive "contains" match. `%` and `_` act as wildcards.
        - `frequency_type_id` returns positions paid on that pay frequency (ids from `GET /v1/pay-frequency`).
        - `department_id` and `group_id` match the position's department and permission group ids.
        - `reconciliation` returns positions with at least one reconciliation setting whose override settlement equals the text you send, for example `Reconciliation`. Not case-sensitive.
        - Filter values are not validated. A value that matches nothing (including a non-numeric id) returns `200` with an empty list.
        - `per_page` defaults to 50 and has no upper limit. A value that is not a positive number is quietly replaced by 50.
        - `page` starts at 1. `0` or a non-number is read as 1. A negative `page` returns `500`, so always send a positive whole number.
        - Results are ordered by `id`, oldest first (the opposite of users and locations). A page past the end returns an empty `positions` array, and `last_page` is `0` when nothing matches. The response has no `filters` key.

        **Formats:**

        - `status` is always `1`, because only active positions are returned.
        - `is_selfgen`: `0` none, `1` self-gen, `2` closer, `3` setter.
        - `worker_type` is text such as `1099` or `w2`. Compare it case-insensitively.
        - `peoples_count` counts users of every status assigned to the position, including terminated and dismissed users.
        - From `pay_frequency`, use `frequency_type_id` and `frequency_type_name`. Its other fields are internal schedule settings; read pay schedules from `GET /v1/pay-frequency` instead.
        - `deduction_limit` and `reconciliation` hold one setting or `null`. A position can have several (per product or per date), but only one is returned and which one is not defined, so do not rely on them.
        - Nested objects carry extra internal fields that are not listed here. Do not depend on them.
        - The metadata key is `requested_by` (snake_case).

        **Errors:**

        - `400` `Invalid query parameter(s)`, with `invalid_params` and `allowed_params` in `data`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/positions/{id}` returns one position.
        - `POST /v1/users/{id}/position` and `POST /v1/onboarding` take a `position_id` from this list.
      security:
        - bearerAuth: []
      parameters:
        - name: position_name
          in: query
          required: false
          description: Case-insensitive "contains" match on the position name.
          schema:
            type: string
          example: manager
        - name: frequency_type_id
          in: query
          required: false
          description: Pay frequency id, from `GET /v1/pay-frequency`.
          schema:
            type: integer
          example: 1
        - name: department_id
          in: query
          required: false
          description: Department id (`department.id` on a position).
          schema:
            type: integer
          example: 1
        - name: reconciliation
          in: query
          required: false
          description: Override settlement value of any of the position's reconciliation settings, for example `Reconciliation`. Not case-sensitive.
          schema:
            type: string
          example: Reconciliation
        - name: group_id
          in: query
          required: false
          description: Permission group id (`group.id` on a position).
          schema:
            type: integer
          example: 2
        - name: per_page
          in: query
          required: false
          description: Positions per page. No upper limit. Values that are not a positive number become 50.
          schema:
            type: integer
            minimum: 1
            default: 50
          example: 50
        - name: page
          in: query
          required: false
          description: Page number, starting at 1. Send a positive whole number; a negative value returns 500.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
      responses:
        '200':
          description: A page of active positions
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Name of the API credential your token belongs to.
                          current_page:
                            type: integer
                            description: The page returned.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Positions matching the filters, across all pages.
                          last_page:
                            type: integer
                            description: Number of the last page. 0 when nothing matches.
                          positions:
                            type: array
                            description: Positions on this page, oldest first.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Position id. Use it as `position_id` or `sub_position_id` elsewhere.
                                position_name:
                                  type: string
                                  description: Position name.
                                parent_id:
                                  type: integer
                                  nullable: true
                                  description: Id of the position this one sits under, or null.
                                org_parent_id:
                                  type: integer
                                  nullable: true
                                  description: Id of the position above this one in the org chart, or null.
                                is_manager:
                                  type: integer
                                  description: 1 for a manager position.
                                status:
                                  type: integer
                                  description: Always 1 (active).
                                worker_type:
                                  type: string
                                  nullable: true
                                  description: Worker type, such as `1099` or `w2`.
                                is_selfgen:
                                  type: integer
                                  enum: [0, 1, 2, 3]
                                  description: 0 none, 1 self-gen, 2 closer, 3 setter.
                                peoples_count:
                                  type: integer
                                  description: Users assigned to this position, counting every status.
                                group:
                                  type: object
                                  nullable: true
                                  description: Permission group.
                                  properties:
                                    id:
                                      type: integer
                                      description: Group id. Filter with `group_id`.
                                    name:
                                      type: string
                                      description: Group name.
                                department:
                                  type: object
                                  nullable: true
                                  description: Department.
                                  properties:
                                    id:
                                      type: integer
                                      description: Department id. Filter with `department_id`.
                                    name:
                                      type: string
                                      description: Department name.
                                pay_frequency:
                                  type: object
                                  nullable: true
                                  description: How often the position is paid. Use only the two fields below.
                                  properties:
                                    frequency_type_id:
                                      type: integer
                                      description: Pay frequency id, as in `GET /v1/pay-frequency`.
                                    frequency_type_name:
                                      type: string
                                      description: Pay frequency name, for example `Weekly`.
                                deduction_limit:
                                  type: object
                                  nullable: true
                                  description: One deduction limit setting, or null. Not reliable when the position has several.
                                reconciliation:
                                  type: object
                                  nullable: true
                                  description: One reconciliation setting, or null. Not reliable when the position has several.
                                child_positions:
                                  type: array
                                  description: Active positions whose `parent_id` is this position.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Child position id.
                                      parent_id:
                                        type: integer
                                        description: This position's id.
                                      position_name:
                                        type: string
                                        description: Child position name.
                                      is_manager:
                                        type: integer
                                        description: 1 for a manager position.
                                      setup_status:
                                        type: integer
                                        description: Always 1 (active).
                                      group_id:
                                        type: integer
                                        nullable: true
                                        description: Permission group id.
              examples:
                positions:
                  summary: Active positions
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: "acme"
                      current_page: 1
                      per_page: 50
                      total: 12
                      last_page: 1
                      positions:
                        - id: 4
                          parent_id: null
                          org_parent_id: null
                          position_name: "Sales Manager"
                          is_manager: 1
                          status: 1
                          worker_type: "1099"
                          is_selfgen: 0
                          peoples_count: 5
                          group:
                            id: 2
                            name: "Sales"
                            position_id: 4
                          pay_frequency:
                            frequency_type_id: 1
                            frequency_type_name: "Weekly"
                            position_id: 4
                          department:
                            id: 1
                            name: "Sales"
                            parent_id: null
                            position_id: 4
                          deduction_limit: null
                          reconciliation: null
                          child_positions:
                            - id: 10
                              parent_id: 4
                              position_name: "Sales Rep"
                              is_manager: 0
                              setup_status: 1
                              group_id: 2
                no_positions:
                  summary: Nothing matches the filters
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: "acme"
                      current_page: 1
                      per_page: 50
                      total: 0
                      last_page: 0
                      positions: []
        '400':
          description: Unknown query parameter
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Invalid query parameter(s)"
                data:
                  invalid_params: ["search"]
                  allowed_params: ["position_name", "frequency_type_id", "department_id", "reconciliation", "group_id", "page", "per_page"]
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error, including a negative `page`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/positions/{id}:
    get:
      operationId: getPosition
      tags:
        - Positions
      summary: Get a position
      description: |
        Returns one active position by id, with the same fields as `GET /v1/positions`. The position is at `data.positions[0]`: the response uses the list wrapper. Inactive and built-in system positions return `404`, even when a user still holds them.

        **Before you call:**

        - Take the id from `GET /v1/positions`, or from `position_id` / `sub_position_id` on a user.
        - Do not add query parameters. Any query parameter returns `400`.

        **Formats:**

        - Same as `GET /v1/positions`: `status` is always `1`; use only `frequency_type_id` and `frequency_type_name` from `pay_frequency`; do not rely on `deduction_limit` or `reconciliation`.
        - `current_page`, `per_page`, `total` and `last_page` are always `1`, `50`, `1` and `1`. Ignore them.
        - The metadata key is `requested_by` (snake_case).

        **Errors:**

        - `400` `Invalid position id` when `id` does not start with a positive number. Trailing characters are ignored, so `4abc` reads as `4`.
        - `400` `Cannot use query parameters when fetching a single position by id`.
        - `404` `Position not found` for an unknown, inactive or system position. A `404` does not mean the id never existed.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/positions` lists active positions.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Position id.
          schema:
            type: integer
            minimum: 1
          example: 4
      responses:
        '200':
          description: The position, as the only item of `data.positions`
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Name of the API credential your token belongs to.
                          current_page:
                            type: integer
                            description: Always 1.
                          per_page:
                            type: integer
                            description: Always 50. Ignore it.
                          total:
                            type: integer
                            description: Always 1.
                          last_page:
                            type: integer
                            description: Always 1.
                          positions:
                            type: array
                            description: Exactly one position.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Position id. Use it as `position_id` or `sub_position_id` elsewhere.
                                position_name:
                                  type: string
                                  description: Position name.
                                parent_id:
                                  type: integer
                                  nullable: true
                                  description: Id of the position this one sits under, or null.
                                org_parent_id:
                                  type: integer
                                  nullable: true
                                  description: Id of the position above this one in the org chart, or null.
                                is_manager:
                                  type: integer
                                  description: 1 for a manager position.
                                status:
                                  type: integer
                                  description: Always 1 (active).
                                worker_type:
                                  type: string
                                  nullable: true
                                  description: Worker type, such as `1099` or `w2`.
                                is_selfgen:
                                  type: integer
                                  enum: [0, 1, 2, 3]
                                  description: 0 none, 1 self-gen, 2 closer, 3 setter.
                                peoples_count:
                                  type: integer
                                  description: Users assigned to this position, counting every status.
                                group:
                                  type: object
                                  nullable: true
                                  description: Permission group.
                                  properties:
                                    id:
                                      type: integer
                                      description: Group id. Filter with `group_id`.
                                    name:
                                      type: string
                                      description: Group name.
                                department:
                                  type: object
                                  nullable: true
                                  description: Department.
                                  properties:
                                    id:
                                      type: integer
                                      description: Department id. Filter with `department_id`.
                                    name:
                                      type: string
                                      description: Department name.
                                pay_frequency:
                                  type: object
                                  nullable: true
                                  description: How often the position is paid. Use only the two fields below.
                                  properties:
                                    frequency_type_id:
                                      type: integer
                                      description: Pay frequency id, as in `GET /v1/pay-frequency`.
                                    frequency_type_name:
                                      type: string
                                      description: Pay frequency name, for example `Weekly`.
                                deduction_limit:
                                  type: object
                                  nullable: true
                                  description: One deduction limit setting, or null. Not reliable when the position has several.
                                reconciliation:
                                  type: object
                                  nullable: true
                                  description: One reconciliation setting, or null. Not reliable when the position has several.
                                child_positions:
                                  type: array
                                  description: Active positions whose `parent_id` is this position.
                                  items:
                                    type: object
                                    properties:
                                      id:
                                        type: integer
                                        description: Child position id.
                                      parent_id:
                                        type: integer
                                        description: This position's id.
                                      position_name:
                                        type: string
                                        description: Child position name.
                                      is_manager:
                                        type: integer
                                        description: 1 for a manager position.
                                      setup_status:
                                        type: integer
                                        description: Always 1 (active).
                                      group_id:
                                        type: integer
                                        nullable: true
                                        description: Permission group id.
              example:
                status: 200
                message: success
                data:
                  requested_by: "acme"
                  current_page: 1
                  per_page: 50
                  total: 1
                  last_page: 1
                  positions:
                    - id: 4
                      parent_id: null
                      org_parent_id: null
                      position_name: "Sales Manager"
                      is_manager: 1
                      status: 1
                      worker_type: "1099"
                      is_selfgen: 0
                      peoples_count: 5
                      group:
                        id: 2
                        name: "Sales"
                        position_id: 4
                      pay_frequency:
                        frequency_type_id: 1
                        frequency_type_name: "Weekly"
                        position_id: 4
                      department:
                        id: 1
                        name: "Sales"
                        parent_id: null
                        position_id: 4
                      deduction_limit: null
                      reconciliation: null
                      child_positions: []
        '400':
          description: Invalid id, or query parameters sent with an id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive number
                  value:
                    status: 400
                    message: "Invalid position id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with an id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single position by id"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: Unknown, inactive or system position
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Position not found"
                data: {}
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/teams:
    get:
      operationId: listTeams
      tags:
        - Teams
      summary: List teams
      description: |
        Lists teams, as on the Teams page in Sequifi, each with its Team Manager and Team Members. Teams and memberships are dated, and by default you get only those in effect today in UTC, which in US time zones is already tomorrow from late afternoon or evening. Always pass `effective_date`.

        **What happens:**

        - Read-only.
        - A team or membership is in effect on a date when its `start_date` is on or before that date and its `end_date` is empty or on or after it.
        - `effective_date` filters both the teams and each team's members, so a rep who left mid-period disappears from that date on. Pass `effective_date=all` to get every team and every membership.
        - Members are not filtered by employment status. Each person has `status_id` (`1` = active), so a past roster still shows reps who were later terminated.
        - Deleted teams and deleted memberships are left out.

        **Filtering and paging:**

        - Filters combine with AND.
        - `team_name` is a partial, case-insensitive match. Every other filter is exact.
        - `team_manager_id` matches the Team Manager. `team_member_id` returns the teams that user belongs to on `effective_date` (the answer to "which team is this rep on").
        - `start_date_from`, `start_date_to`, `end_date_from` and `end_date_to` are inclusive ranges on the team's own dates.
        - `updated_since` (`YYYY-MM-DD`) returns teams whose own details changed on or after that day. Adding or removing a member probably does not count as a change to the team, so for a roster sync re-read each period by `effective_date`.
        - `per_page` defaults to 50, maximum 200. `last_page` is `0` when nothing matches.
        - Sorted by team `start_date`, newest first, then by `id`.
        - Unknown query parameters are rejected with `400`. Empty values are ignored.

        **Formats:**

        - Team `start_date` and `end_date`, and each member's `start_date` and `end_date`, are `YYYY-MM-DD`. `end_date` is null when open-ended. A member's dates are their own membership on this team and can differ from the team's dates.
        - `created_at` and `updated_at` are UTC timestamps, for example `"2026-09-07T15:05:14.000Z"`.
        - `manager_gets_override` is a boolean in the response. The filter takes `0` or `1`.
        - `type` is always `lead`.
        - `team_manager` is null when the team has no manager.
        - A member whose user record no longer exists comes back with only `start_date` and `end_date`, with no `id`.
        - `filters` always includes `effective_date`: the date used, or `"all"`.
        - There is no `requestedBy` field on this endpoint.

        **Errors:**

        - `400 Invalid query parameter(s)`, with `data.invalid_params` and `data.allowed_params`.
        - `400 effective_date must be a YYYY-MM-DD date or 'all'`
        - `400 <name> must be a YYYY-MM-DD date` for `start_date_from`, `start_date_to`, `end_date_from`, `end_date_to` and `updated_since`.
        - `400 <name> must be a positive integer` for `team_manager_id`, `team_member_id`, `location_id` and `office_id`.
        - `400 manager_gets_override must be 0 or 1`
        - `400 per_page must be an integer between 1 and 200`, `400 page must be a positive integer`

        **Related:**

        - `GET /v1/teams/{id}` returns one team with its full membership history.
        - `POST /v1/teams` creates a team.
        - `GET /v1/users/{id}` for full details of a manager or member.
      security:
        - bearerAuth: []
      parameters:
        - name: effective_date
          in: query
          required: false
          description: 'Return teams and memberships in effect on this date: `YYYY-MM-DD`, or `all` for no date filter. Defaults to today''s date in UTC. Always send it.'
          schema:
            type: string
          example: "2026-09-06"
        - name: start_date_from
          in: query
          required: false
          description: Teams whose `start_date` is on or after this date (`YYYY-MM-DD`).
          schema:
            type: string
            format: date
          example: "2026-09-01"
        - name: start_date_to
          in: query
          required: false
          description: Teams whose `start_date` is on or before this date (`YYYY-MM-DD`).
          schema:
            type: string
            format: date
          example: "2026-09-30"
        - name: end_date_from
          in: query
          required: false
          description: Teams whose `end_date` is on or after this date (`YYYY-MM-DD`).
          schema:
            type: string
            format: date
          example: "2026-09-01"
        - name: end_date_to
          in: query
          required: false
          description: Teams whose `end_date` is on or before this date (`YYYY-MM-DD`).
          schema:
            type: string
            format: date
          example: "2026-09-30"
        - name: updated_since
          in: query
          required: false
          description: Teams whose own details changed on or after this day (`YYYY-MM-DD`, from 00:00 UTC). Member changes may not count; re-read by `effective_date` for roster sync.
          schema:
            type: string
            format: date
          example: "2026-09-01"
        - name: team_name
          in: query
          required: false
          description: Partial, case-insensitive match on the team name.
          schema:
            type: string
          example: Alpha
        - name: team_manager_id
          in: query
          required: false
          description: Only teams led by this Team Manager (user id).
          schema:
            type: integer
            minimum: 1
          example: 72
        - name: team_member_id
          in: query
          required: false
          description: Only teams this user belongs to on `effective_date`.
          schema:
            type: integer
            minimum: 1
          example: 428
        - name: type
          in: query
          required: false
          description: Team type. Every team is `lead`.
          schema:
            type: string
          example: lead
        - name: location_id
          in: query
          required: false
          description: Exact location id on the team.
          schema:
            type: integer
            minimum: 1
          example: 3
        - name: office_id
          in: query
          required: false
          description: Exact office id on the team.
          schema:
            type: integer
            minimum: 1
          example: 5
        - name: manager_gets_override
          in: query
          required: false
          description: 'The "Team Manager gets Override" setting: `0` or `1`.'
          schema:
            type: integer
            enum: [0, 1]
          example: 1
        - name: per_page
          in: query
          required: false
          description: Records per page. Default 50, maximum 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 50
          example: 50
        - name: page
          in: query
          required: false
          description: Page number, starting at 1.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
      responses:
        '200':
          description: One page of teams. An empty page is still a `200`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      current_page:
                        type: integer
                        description: The page returned.
                      per_page:
                        type: integer
                        description: Page size used.
                      total:
                        type: integer
                        description: Number of teams that match.
                      last_page:
                        type: integer
                        description: Last page number. `0` when nothing matches.
                      filters:
                        type: object
                        description: The filters applied. Always includes `effective_date` (a date or `"all"`).
                      teams:
                        type: array
                        description: Teams on this page.
                        items:
                          type: object
                          properties:
                            id:
                              type: integer
                              description: Team id.
                            team_name:
                              type: string
                              description: Team name.
                            type:
                              type: string
                              description: Always `lead`.
                            start_date:
                              type: string
                              description: First day of the team, `YYYY-MM-DD`.
                            end_date:
                              type: string
                              nullable: true
                              description: Last day of the team, `YYYY-MM-DD`, or null when open-ended.
                            manager_gets_override:
                              type: boolean
                              description: Whether the Team Manager becomes each member's manager for the team's dates.
                            location_id:
                              type: integer
                              nullable: true
                              description: Location id, if set.
                            office_id:
                              type: integer
                              nullable: true
                              description: Office id, if set.
                            created_at:
                              type: string
                              description: UTC timestamp.
                            updated_at:
                              type: string
                              description: UTC timestamp of the last change to the team itself.
                            team_manager:
                              type: object
                              nullable: true
                              description: The Team Manager, or null.
                              properties:
                                id: { type: integer, description: User id. }
                                first_name: { type: string, description: First name. }
                                last_name: { type: string, description: Last name. }
                                email: { type: string, description: Email address. }
                                position_id: { type: integer, nullable: true, description: 'Position id, as on `GET /v1/users`.' }
                                position_name: { type: string, nullable: true, description: Position name. }
                                sub_position_id: { type: integer, nullable: true, description: Sub-position id. }
                                sub_position_name: { type: string, nullable: true, description: Sub-position name. }
                                is_manager: { type: integer, nullable: true, description: '`1` when the user is a manager, else `0`.' }
                                status_id: { type: integer, nullable: true, description: 'Employment status. `1` is active.' }
                            team_members:
                              type: array
                              description: Members in effect on `effective_date` (or all memberships with `all`). Same person fields as `team_manager`, plus this membership's dates.
                              items:
                                type: object
                                properties:
                                  id: { type: integer, description: User id. Missing when the user no longer exists. }
                                  first_name: { type: string, description: First name. }
                                  last_name: { type: string, description: Last name. }
                                  email: { type: string, description: Email address. }
                                  status_id: { type: integer, nullable: true, description: 'Employment status. `1` is active.' }
                                  start_date: { type: string, description: 'First day on this team, `YYYY-MM-DD`.' }
                                  end_date: { type: string, nullable: true, description: 'Last day on this team, `YYYY-MM-DD`, or null.' }
              examples:
                list_response:
                  summary: Teams in effect on a given date
                  value:
                    status: 200
                    message: success
                    data:
                      current_page: 1
                      per_page: 50
                      total: 1
                      last_page: 1
                      filters:
                        effective_date: "2026-09-06"
                      teams:
                        - id: 44
                          team_name: "Team Alpha - Sep 6"
                          type: "lead"
                          start_date: "2026-09-06"
                          end_date: "2026-09-12"
                          manager_gets_override: false
                          location_id: null
                          office_id: null
                          created_at: "2026-09-07T15:05:14.000Z"
                          updated_at: "2026-09-07T15:05:14.000Z"
                          team_manager:
                            id: 72
                            first_name: "Avery"
                            last_name: "Nolan"
                            email: "avery.nolan@example.com"
                            position_id: 2
                            position_name: "Closer"
                            sub_position_id: 7
                            sub_position_name: "Veteran"
                            is_manager: 1
                            status_id: 1
                          team_members:
                            - id: 428
                              first_name: "Alex"
                              last_name: "Morgan"
                              email: "alex.morgan@example.com"
                              position_id: 2
                              position_name: "Closer"
                              sub_position_id: 9
                              sub_position_name: "Sophomore"
                              is_manager: 0
                              status_id: 1
                              start_date: "2026-09-06"
                              end_date: "2026-09-12"
                            - id: 487
                              first_name: "Sam"
                              last_name: "Lee"
                              email: "sam.lee@example.com"
                              position_id: 2
                              position_name: "Closer"
                              sub_position_id: 9
                              sub_position_name: "Sophomore"
                              is_manager: 0
                              status_id: 1
                              start_date: "2026-09-06"
                              end_date: "2026-09-12"
        '400':
          description: An unknown query parameter or an invalid filter value. The message names the parameter.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_effective_date:
                  summary: effective_date is not a date or all
                  value:
                    status: 400
                    message: "effective_date must be a YYYY-MM-DD date or 'all'"
                    data: {}
                invalid_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["active_on"]
                      allowed_params: ["effective_date", "start_date_from", "start_date_to", "end_date_from", "end_date_to", "updated_since", "team_name", "team_manager_id", "team_member_id", "type", "location_id", "office_id", "manager_gets_override", "page", "per_page"]
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

    post:
      operationId: createTeam
      tags:
        - Teams
      summary: Create a team
      description: |
        Creates one dated team with a Team Manager and members, as on the Teams page in Sequifi. There is no API to change or delete a team: later roster changes are made on the Teams page, or by creating the next period's team. A rep can be on only one team at a time, so an overlapping membership is refused until you say how to resolve it.

        **Before you call:**

        - Confirm the manager and every member exist and are active with `GET /v1/users/{id}`. An unknown user id most likely comes back as an unreadable `502`, not a `422`.
        - To check for conflicts first, call `GET /v1/teams?team_member_id=<id>&effective_date=<start_date>` for each member.
        - Always send `end_date`. An open-ended membership overlaps every later period, so the next team for that rep will conflict.

        **What happens:**

        The call waits for the result (up to 25 seconds) and checks, in this order:

        - A team with the same `team_name`, `start_date` and `team_manager_id` already exists: `409 TEAM_ALREADY_EXISTS` with `data.team_id`.
        - The manager or a member is dismissed, terminated or contract-ended: `422 MANAGER_NOT_ACTIVE` or `422 MEMBER_NOT_ACTIVE`.
        - A member is on another team during these dates: `409 MEMBER_CONFLICT`. `data.conflicts` lists every conflict at once. Resend the same body with one `member_conflict_resolutions` entry for each listed member: `move_new_start` ends the old membership the day before this team starts; `custom` moves the member on `custom_date` (inside this team's dates) and ends the old membership the day before; `remove` deletes the old membership as if it never existed. Resolutions change the other team's memberships and overrides, so choose deliberately.

        If every check passes:

        - The team (type `lead`) and its memberships are created. A manager listed in `team_members` is left out of the members. Each member's current team in Sequifi is set to this team.
        - With `manager_gets_override: true`, the Team Manager becomes each member's manager for the team's dates, which affects override pay. For a member who already reports to someone else, `manager_override_resolutions` says `keep` (leave their manager) or `reassign` (move them to the Team Manager).
        - No emails are sent. Changes are recorded as made by the Marketplace API.

        **Idempotency and retries:**

        - Safe to retry with the identical body. You get `201` (the first attempt did not land), `409 TEAM_ALREADY_EXISTS` with `data.team_id` (it did), or `409 CREATE_IN_PROGRESS` (another create is still running: wait 1 to 2 seconds and retry).
        - Changing `team_name`, `start_date` or `team_manager_id` on a retry creates a second team.
        - Creates run one at a time per company. Send a period's teams in sequence, not in parallel.
        - A `504` is ambiguous: re-post the identical body and read the result.

        **Formats:**

        - Dates are `YYYY-MM-DD`. `end_date` must be on or after `start_date`; send null or leave it out for open-ended.
        - `manager_gets_override` must be a JSON boolean (`true` or `false`), not `0`, `1` or a string.
        - `team_members`: up to 200 user ids, no repeats. Numeric strings are accepted.
        - Other fields (for example `type`, `office_id`, `location_id` or manual overrides) are ignored without an error.
        - The `201` response has `message: "Successfully."` and the team as stored. Membership dates can differ from the request after a `custom` resolution.

        **Errors:**

        - `400`: the body failed a check before it was sent. The message names the field, for example `team_name is required`, `start_date is required and must be a YYYY-MM-DD date`, `end_date must be on or after start_date`, `manager_gets_override must be true or false`, `team_members must not repeat the same user` (with `data.duplicates`) or `a custom resolution requires custom_date as a YYYY-MM-DD date`.
        - `409`: `MEMBER_CONFLICT`, `TEAM_ALREADY_EXISTS` or `CREATE_IN_PROGRESS` in `data.code`.
        - `422`: `MANAGER_NOT_ACTIVE` (with `data.team_manager_id`) or `MEMBER_NOT_ACTIVE` (with `data.member_ids`).
        - `500 The team could not be created.` (`data.code` `CREATE_FAILED`) or `500 Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502 Could not reach the tenant` or `502 The tenant returned an unreadable response`. The second most likely also covers unknown user ids, a `custom_date` outside the team's dates, going over about 60 creates a minute for your company, and unexpected errors. No `Retry-After` header is sent. Check the ids, wait, then retry the identical body.
        - `503`: the company is not set up for team creation over the API (`data.code` `NOT_PROVISIONED` in one case). Contact Sequifi support.
        - `504`: the team may still have been created. Re-post the identical body.

        **Common mistakes:**

        - Using `team_id` on `POST /v1/onboarding` to put someone on a team. Only this endpoint writes team memberships.
        - Reading the id in the `TEAM_ALREADY_EXISTS` message as the manager's id. It is the existing team's id; use `data.team_id`.

        **Related:**

        - `GET /v1/teams/{id}` reads the team back.
        - `GET /v1/teams?team_member_id=<user_id>&effective_date=<date>` shows which team a rep is on.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - team_name
                - start_date
              properties:
                team_name:
                  type: string
                  maxLength: 255
                  description: Team name. Leading and trailing spaces are trimmed. Part of the duplicate check, so keep it identical on retries.
                  example: "Team Alpha - Sep 6"
                start_date:
                  type: string
                  format: date
                  description: First day of the team, `YYYY-MM-DD`. Part of the duplicate check.
                  example: "2026-09-06"
                end_date:
                  type: string
                  format: date
                  nullable: true
                  description: Last day of the team, on or after `start_date`. Always send one for a weekly roster.
                  example: "2026-09-12"
                team_manager_id:
                  type: integer
                  nullable: true
                  description: The Team Manager's user id. Must be an active user. Part of the duplicate check.
                  example: 72
                team_members:
                  type: array
                  maxItems: 200
                  description: Active user ids, at most 200, with no repeats.
                  items: { type: integer }
                  example: [428, 487, 489]
                manager_gets_override:
                  type: boolean
                  description: 'The "Team Manager gets Override" setting. When true, the Team Manager becomes the manager of each member for the team''s dates. Must be a JSON boolean.'
                  default: false
                  example: false
                member_conflict_resolutions:
                  type: array
                  description: Send on the retry after `409 MEMBER_CONFLICT`, one entry per member named in `data.conflicts`.
                  items:
                    type: object
                    required: [member_id, type]
                    properties:
                      member_id:
                        type: integer
                        description: The conflicting member's user id.
                        example: 428
                      type:
                        type: string
                        enum: [remove, move_new_start, custom]
                        description: '`move_new_start` ends the old membership the day before this team starts. `custom` moves the member on `custom_date`. `remove` deletes the old membership.'
                        example: move_new_start
                      custom_date:
                        type: string
                        format: date
                        nullable: true
                        description: Required when `type` is `custom`. Must fall inside this team's dates.
                        example: "2026-09-08"
                manager_override_resolutions:
                  type: array
                  description: 'Only used with `manager_gets_override: true`. For a member who already reports to someone else: `keep` leaves their manager, `reassign` moves them to the Team Manager for the team''s dates.'
                  items:
                    type: object
                    required: [member_id, action]
                    properties:
                      member_id:
                        type: integer
                        description: The member's user id.
                        example: 487
                      action:
                        type: string
                        enum: [keep, reassign]
                        description: What to do with the member's current manager.
                        example: reassign
            examples:
              weekly_team:
                summary: A weekly team with three members
                value:
                  team_name: "Team Alpha - Sep 6"
                  start_date: "2026-09-06"
                  end_date: "2026-09-12"
                  team_manager_id: 72
                  team_members: [428, 487, 489]
                  manager_gets_override: false
              retry_with_resolution:
                summary: The same body resent after a MEMBER_CONFLICT
                value:
                  team_name: "Team Alpha - Sep 6"
                  start_date: "2026-09-06"
                  end_date: "2026-09-12"
                  team_manager_id: 72
                  team_members: [428, 487, 489]
                  manager_gets_override: false
                  member_conflict_resolutions:
                    - member_id: 428
                      type: move_new_start
      responses:
        '201':
          description: Created. The team as stored, with each membership's dates.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 201
                  message:
                    type: string
                    example: "Successfully."
                  data:
                    type: object
                    properties:
                      id:
                        type: integer
                        description: New team id. Use it with `GET /v1/teams/{id}`.
                      team_name:
                        type: string
                        description: Team name as stored.
                      type:
                        type: string
                        description: Always `lead`.
                      start_date:
                        type: string
                        description: First day, `YYYY-MM-DD`.
                      end_date:
                        type: string
                        nullable: true
                        description: Last day, `YYYY-MM-DD`, or null.
                      manager_gets_override:
                        type: boolean
                        description: The "Team Manager gets Override" setting.
                      team_manager_id:
                        type: integer
                        nullable: true
                        description: The Team Manager's user id.
                      team_members:
                        type: array
                        description: Memberships as stored.
                        items:
                          type: object
                          properties:
                            id: { type: integer, description: Member's user id. }
                            start_date: { type: string, description: 'First day on the team, `YYYY-MM-DD`.' }
                            end_date: { type: string, nullable: true, description: 'Last day on the team, `YYYY-MM-DD`, or null.' }
              example:
                status: 201
                message: "Successfully."
                data:
                  id: 44
                  team_name: "Team Alpha - Sep 6"
                  type: "lead"
                  start_date: "2026-09-06"
                  end_date: "2026-09-12"
                  manager_gets_override: false
                  team_manager_id: 72
                  team_members:
                    - id: 428
                      start_date: "2026-09-06"
                      end_date: "2026-09-12"
                    - id: 487
                      start_date: "2026-09-06"
                      end_date: "2026-09-12"
                    - id: 489
                      start_date: "2026-09-06"
                      end_date: "2026-09-12"
        '400':
          description: The body failed a check before it was sent. The message names the field.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_start_date:
                  summary: start_date missing or not a real date
                  value:
                    status: 400
                    message: "start_date is required and must be a YYYY-MM-DD date"
                    data: {}
                repeated_member:
                  summary: The same user appears twice in team_members
                  value:
                    status: 400
                    message: "team_members must not repeat the same user"
                    data:
                      duplicates: [487]
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '409':
          description: A member is already on another team for these dates, this team already exists, or another create is running. Branch on `data.code`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                member_conflict:
                  summary: One or more members are already on another team
                  value:
                    status: 409
                    message: "One or more team_members already belong to another team during this period. Resend with a member_conflict_resolutions entry for each member listed in data.conflicts."
                    data:
                      code: MEMBER_CONFLICT
                      conflicts:
                        - member_id: 428
                          team_id: 42
                          team_name: "Team Bravo - Sep 6"
                          membership_start_date: "2026-09-06"
                          membership_end_date: "2026-09-12"
                        - member_id: 487
                          team_id: 42
                          team_name: "Team Bravo - Sep 6"
                          membership_start_date: "2026-09-06"
                          membership_end_date: "2026-09-12"
                team_already_exists:
                  summary: An identical team already exists (a safe retry). The id in the message is the team's id.
                  value:
                    status: 409
                    message: 'A team named "Team Alpha - Sep 6" already starts on 2026-09-06 with the same Team Manager (id 44).'
                    data:
                      code: TEAM_ALREADY_EXISTS
                      team_id: 44
                create_in_progress:
                  summary: Another create for your company is running (retry in a moment)
                  value:
                    status: 409
                    message: "Another team create for this tenant is already running. Retry in a moment; if it was the same team and it succeeded, you will get TEAM_ALREADY_EXISTS with the team id."
                    data:
                      code: CREATE_IN_PROGRESS
        '422':
          description: The Team Manager or a member is not an active user. Unknown user ids most likely return `502` instead.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                member_not_active:
                  summary: One or more members is not an active user
                  value:
                    status: 422
                    message: "These team_members are not active users and cannot be added to a team: 530, 541."
                    data:
                      code: MEMBER_NOT_ACTIVE
                      member_ids: [530, 541]
                manager_not_active:
                  summary: The Team Manager is not an active user
                  value:
                    status: 422
                    message: "team_manager_id 530 is not an active user and cannot manage a team."
                    data:
                      code: MANAGER_NOT_ACTIVE
                      team_manager_id: 530
        '500':
          description: The team could not be created, or the company's Sequifi address could not be resolved.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The team could not be created."
                data:
                  code: CREATE_FAILED
        '502':
          description: Your company's Sequifi app could not be reached, or sent a response the API could not read. The second case most likely also covers unknown user ids, an unusable `custom_date` and rate limits. Check the ids, wait, and retry the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unreadable:
                  summary: Unreadable response (likely a validation or rate-limit error)
                  value:
                    status: 502
                    message: "The tenant returned an unreadable response"
                    data: {}
                unreachable:
                  summary: Could not connect
                  value:
                    status: 502
                    message: "Could not reach the tenant"
                    data: {}
        '503':
          description: Your company is not set up for team creation over the API. Contact Sequifi support.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This tenant is not configured for team creation over the API. Contact Sequifi support."
                    data: {}
                not_provisioned:
                  summary: Not provisioned for API writes
                  value:
                    status: 503
                    message: "This tenant is not provisioned for Marketplace API writes. Contact Sequifi support."
                    data:
                      code: NOT_PROVISIONED
        '504':
          description: No answer in time. The team may still have been created. Re-post the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The team may still have been created — re-post the identical body: you will get 201 if it was not, or 409 TEAM_ALREADY_EXISTS with the existing team id if it was. Do not change team_name or start_date on a retry."
                data: {}

  /v1/teams/{id}:
    get:
      operationId: getTeam
      tags:
        - Teams
      summary: Get a team
      description: |
        Returns one team by id with its Team Manager and every membership it has had, each with its own `start_date` and `end_date`. Unlike `GET /v1/teams`, no date filter is applied, so read the membership dates yourself.

        **Formats:**

        - Same fields as one item of `GET /v1/teams`, under `data.team`. Team and membership dates are `YYYY-MM-DD`; `created_at` and `updated_at` are UTC timestamps.
        - Members include former members; check each membership's dates. Each person has `status_id` (`1` = active).
        - A member whose user record no longer exists comes back with only `start_date` and `end_date`.

        **Errors:**

        - `400 Invalid team id`: the id is not a positive whole number.
        - `400 Cannot use query parameters when fetching a single team by id`
        - `404 Team not found`: no team has this id, or it was deleted.

        **Related:**

        - `POST /v1/teams` returns this id as `data.id`.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Team id, from `GET /v1/teams` or `POST /v1/teams`.
          schema:
            type: integer
            minimum: 1
          example: 44
      responses:
        '200':
          description: The team with all of its memberships.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      team:
                        type: object
                        description: The team.
                        properties:
                          id: { type: integer, description: Team id. }
                          team_name: { type: string, description: Team name. }
                          type: { type: string, description: Always `lead`. }
                          start_date: { type: string, description: 'First day, `YYYY-MM-DD`.' }
                          end_date: { type: string, nullable: true, description: 'Last day, `YYYY-MM-DD`, or null.' }
                          manager_gets_override: { type: boolean, description: The "Team Manager gets Override" setting. }
                          location_id: { type: integer, nullable: true, description: 'Location id, if set.' }
                          office_id: { type: integer, nullable: true, description: 'Office id, if set.' }
                          created_at: { type: string, description: UTC timestamp. }
                          updated_at: { type: string, description: UTC timestamp of the last change to the team itself. }
                          team_manager: { type: object, nullable: true, description: 'The Team Manager (same person fields as `GET /v1/teams`), or null.' }
                          team_members:
                            type: array
                            description: Every membership, past, current and future, each with its own dates.
                            items:
                              type: object
                              properties:
                                id: { type: integer, description: User id. Missing when the user no longer exists. }
                                first_name: { type: string, description: First name. }
                                last_name: { type: string, description: Last name. }
                                status_id: { type: integer, nullable: true, description: 'Employment status. `1` is active.' }
                                start_date: { type: string, description: 'First day on this team, `YYYY-MM-DD`.' }
                                end_date: { type: string, nullable: true, description: 'Last day on this team, `YYYY-MM-DD`, or null.' }
              example:
                status: 200
                message: success
                data:
                  team:
                    id: 44
                    team_name: "Team Alpha - Sep 6"
                    type: "lead"
                    start_date: "2026-09-06"
                    end_date: "2026-09-12"
                    manager_gets_override: false
                    location_id: null
                    office_id: null
                    created_at: "2026-09-07T15:05:14.000Z"
                    updated_at: "2026-09-07T15:05:14.000Z"
                    team_manager:
                      id: 72
                      first_name: "Avery"
                      last_name: "Nolan"
                      email: "avery.nolan@example.com"
                      position_id: 2
                      position_name: "Closer"
                      sub_position_id: 7
                      sub_position_name: "Veteran"
                      is_manager: 1
                      status_id: 1
                    team_members:
                      - id: 428
                        first_name: "Alex"
                        last_name: "Morgan"
                        email: "alex.morgan@example.com"
                        position_id: 2
                        position_name: "Closer"
                        sub_position_id: 9
                        sub_position_name: "Sophomore"
                        is_manager: 0
                        status_id: 1
                        start_date: "2026-09-06"
                        end_date: "2026-09-12"
        '400':
          description: The id is invalid, or query parameters were sent with it.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid team id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single team by id"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: No team has this id, or it was deleted.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Team not found"
                data: {}
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/onboarding:
    get:
      operationId: listOnboardingEmployees
      tags:
        - Onboarding
      summary: List onboarding records
      description: |
        Lists people who are being onboarded and are not hired yet, newest first, 20 per page by default. A record leaves this list when it is hired with `PUT /v1/onboarding/hire`, so a poller never sees the hire here: follow hired people with `GET /v1/users`. Branch on `status_id`, because your company can rename statuses.

        **Filtering and paging:**

        - Filters combine with AND.
        - `first_name`, `last_name`, `full_name`, `email` and `employee_id` are partial, case-insensitive matches. `_` and `%` in a value act as wildcards, so `email=jo_n@example.com` also matches `join@example.com`. Compare the exact value on your side before you treat a result as a duplicate.
        - `status` is a partial match on the status name, so `status=Offer` matches Offer Sent, Offer Review, Offer Expired and more. There is no `status_id` filter.
        - `updated_after`, `updated_before`, `created_after` and `created_before` take `YYYY-MM-DD` or an ISO 8601 timestamp such as `2026-05-06T13:43:14Z` (a `+hh:mm` offset or a space instead of `T` also work). No zone means UTC. Bounds are inclusive. A bare date means 00:00:00 UTC for `_after` and 23:59:59 UTC for `_before`.
        - To poll for changes, pass the newest `updated_at` you have seen as `updated_after`. The record at that exact time comes back again, so de-duplicate on `id`.
        - `per_page` defaults to 20, maximum 200. `last_page` is `0` when nothing matches. Sorted by `id`, newest first.
        - Unknown query parameters are rejected with `400`.
        - A record deleted in the app disappears without a trace.

        **Formats:**

        - `id` is the onboarding id used by `GET /v1/onboarding/{id}`, send-offer and hire. `employee_id` is the onboarding id string, such as `ONB0012`; the user gets a different one on hire.
        - `start_date` (the agreement start date) and `end_date` are calendar days returned as midnight UTC, for example `"2026-11-02T00:00:00.000Z"`. Use the first 10 characters. Converting them to a US time zone shows the previous day.
        - `created_at` and `updated_at` are UTC timestamps, for example `"2026-10-01T15:22:08.000Z"`.
        - `custom_fields` is a JSON-encoded string such as `"{\"Employment Type\":\"Full Time\"}"`, or null. Parse it yourself.
        - `worker_type` comes from the position: `"1099"` or `"w2"` (sometimes `"W2"`).
        - `sub_position_id` equals `position_id` when no sub-position was sent at create. `position_name` is the name of `position_id`.
        - `user_id` is always null in this list.
        - `status_id` and its default `status_name`:
          - `8` Draft: created by `POST /v1/onboarding`. Nothing sent yet.
          - `17` Offer Review: the offer is waiting for internal approval.
          - `4` Offer Sent, Unread; `21` Offer Sent, Read; `12` Offer Resent, Unread; `24` Offer Resent, Read.
          - `13` Offer Letter Accepted; `22` Offer Accepted, Docs Pending; `23` Offer Pending, Docs Completed; `16` Document Review.
          - `6` Requested Change; `2` Declined; `5` Offer Expired.
          - `11` Rejected; `15` Admin Reject; `19` Manager Rejected; `20` Conditions Rejected.
          - `7` Onboarding: set by the hire call. The record then leaves this list.

        **Errors:**

        - `400 Invalid query parameter(s)`, with `data.invalid_params` and `data.allowed_params`.
        - `400 Bad Request: page must be a positive integer`
        - `400 Bad Request: per_page must be a positive integer between 1 and 200`
        - `400 <name> must be a date (YYYY-MM-DD) or ISO 8601 timestamp` for the four date filters, including impossible dates such as `2026-02-30`.

        **Related:**

        - `GET /v1/onboarding/{id}` returns one record.
        - `POST /v1/onboarding/{id}/send-offer` sends the offer letter for a Draft record.
        - `PUT /v1/onboarding/hire` creates the user.
        - `GET /v1/users?email=` finds people who were already hired.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          description: Page number, starting at 1.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Records per page. Default 20, maximum 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 20
          example: 20
        - name: first_name
          in: query
          required: false
          description: Partial, case-insensitive match on first name.
          schema:
            type: string
          example: Alex
        - name: last_name
          in: query
          required: false
          description: Partial, case-insensitive match on last name.
          schema:
            type: string
          example: Morgan
        - name: full_name
          in: query
          required: false
          description: Partial, case-insensitive match on first name, a space, then last name.
          schema:
            type: string
          example: "Alex Morgan"
        - name: email
          in: query
          required: false
          description: Partial, case-insensitive match on the personal email. `_` and `%` act as wildcards; compare the exact address on your side.
          schema:
            type: string
          example: alex.morgan@example.com
        - name: employee_id
          in: query
          required: false
          description: Partial, case-insensitive match on the onboarding id string, such as `ONB0012`.
          schema:
            type: string
          example: ONB0012
        - name: status
          in: query
          required: false
          description: Partial, case-insensitive match on the status name, for example `Draft` or `Offer Sent`. `Offer` matches several statuses. There is no filter by `status_id`.
          schema:
            type: string
          example: Draft
        - name: updated_after
          in: query
          required: false
          description: Records with `updated_at` on or after this value. `YYYY-MM-DD` (from 00:00:00 UTC) or an ISO 8601 timestamp; no zone means UTC. Pass the newest `updated_at` you have seen to poll for changes.
          schema:
            type: string
          example: "2026-10-01T15:22:08Z"
        - name: updated_before
          in: query
          required: false
          description: Records with `updated_at` on or before this value. A bare date runs to 23:59:59 UTC that day.
          schema:
            type: string
          example: "2026-10-31"
        - name: created_after
          in: query
          required: false
          description: Records with `created_at` on or after this value. `YYYY-MM-DD` or an ISO 8601 timestamp.
          schema:
            type: string
          example: "2026-10-01"
        - name: created_before
          in: query
          required: false
          description: Records with `created_at` on or before this value. A bare date runs to 23:59:59 UTC that day.
          schema:
            type: string
          example: "2026-10-31"
      responses:
        '200':
          description: One page of onboarding records. An empty page is still a `200`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      current_page:
                        type: integer
                        description: The page returned.
                      per_page:
                        type: integer
                        description: Page size used.
                      total:
                        type: integer
                        description: Number of records that match.
                      last_page:
                        type: integer
                        description: Last page number. `0` when nothing matches.
                      filters:
                        type: object
                        nullable: true
                        description: The filters you applied, as sent. Null when none.
                      onboarding_employees:
                        type: array
                        description: Records on this page, newest first.
                        items:
                          type: object
                          properties:
                            id:
                              type: integer
                              description: Onboarding id. Use it for send-offer, hire and `GET /v1/onboarding/{id}`.
                            employee_id:
                              type: string
                              description: Onboarding id string, for example `ONB0012`.
                            first_name:
                              type: string
                              description: First name.
                            last_name:
                              type: string
                              description: Last name.
                            email:
                              type: string
                              description: Personal email. The offer letter goes here.
                            mobile_no:
                              type: string
                              description: Mobile number.
                            worker_type:
                              type: string
                              nullable: true
                              description: '`1099` or `w2` (sometimes `W2`), from the position.'
                            status_id:
                              type: integer
                              description: Onboarding status id. See the list above. Branch on this, not on the name.
                            status_name:
                              type: string
                              nullable: true
                              description: Status name. Your company can rename statuses.
                            position_id:
                              type: integer
                              description: Position id.
                            position_name:
                              type: string
                              nullable: true
                              description: Name of `position_id`.
                            sub_position_id:
                              type: integer
                              nullable: true
                              description: Sub-position id. Equals `position_id` when none was sent at create.
                            department_id:
                              type: integer
                              nullable: true
                              description: Department id.
                            office_id:
                              type: integer
                              description: Office id.
                            office_name:
                              type: string
                              nullable: true
                              description: Office name.
                            manager_id:
                              type: integer
                              nullable: true
                              description: Manager's user id.
                            recruiter_id:
                              type: integer
                              nullable: true
                              description: Recruiter's user id. The offer letter is sent as this user.
                            lead_id:
                              type: integer
                              nullable: true
                              description: Candidate id from `GET /v1/candidates`, if one was linked.
                            team_id:
                              type: integer
                              nullable: true
                              description: Team id stored as a label. It does not place the person on a team.
                            start_date:
                              type: string
                              nullable: true
                              description: Agreement start day as midnight UTC, for example `2026-11-02T00:00:00.000Z`. Use the date part.
                            end_date:
                              type: string
                              nullable: true
                              description: Agreement end day as midnight UTC, or null. Use the date part.
                            custom_fields:
                              type: string
                              nullable: true
                              description: Onboarding custom fields as a JSON-encoded string, or null.
                            user_id:
                              type: integer
                              nullable: true
                              description: Always null here (hired records are not listed).
                            created_at:
                              type: string
                              description: UTC timestamp.
                            updated_at:
                              type: string
                              description: UTC timestamp. Use it with `updated_after` to poll.
              examples:
                list_response:
                  summary: One page of onboarding records
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 20
                      total: 1
                      last_page: 1
                      filters: null
                      onboarding_employees:
                        - id: 4821
                          employee_id: "ONB0012"
                          first_name: "Alex"
                          last_name: "Morgan"
                          email: "alex.morgan@example.com"
                          mobile_no: "5125550148"
                          worker_type: "1099"
                          status_id: 4
                          position_id: 14
                          sub_position_id: 22
                          department_id: 3
                          office_id: 7
                          manager_id: 312
                          recruiter_id: 57
                          lead_id: 1093
                          team_id: null
                          start_date: "2026-11-02T00:00:00.000Z"
                          end_date: null
                          custom_fields: "{\"Employment Type\":\"Full Time\"}"
                          user_id: null
                          created_at: "2026-10-01T15:22:08.000Z"
                          updated_at: "2026-10-02T09:41:30.000Z"
                          position_name: "Setter"
                          office_name: "Austin"
                          status_name: "Offer Sent, Unread"
                filtered_response:
                  summary: Records still in Draft
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 20
                      total: 1
                      last_page: 1
                      filters:
                        status: "Draft"
                      onboarding_employees:
                        - id: 4830
                          employee_id: "ONB0013"
                          first_name: "Jordan"
                          last_name: "Reyes"
                          email: "jordan.reyes@example.com"
                          mobile_no: "5125550199"
                          worker_type: "w2"
                          status_id: 8
                          position_id: 14
                          sub_position_id: 14
                          department_id: 3
                          office_id: 7
                          manager_id: null
                          recruiter_id: null
                          lead_id: null
                          team_id: null
                          start_date: "2026-11-09T00:00:00.000Z"
                          end_date: null
                          custom_fields: null
                          user_id: null
                          created_at: "2026-10-03T18:05:51.000Z"
                          updated_at: "2026-10-03T18:05:51.000Z"
                          position_name: "Setter"
                          office_name: "Austin"
                          status_name: "Draft"
        '400':
          description: An unknown query parameter, or an invalid paging or date value.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["status_id"]
                      allowed_params: ["first_name", "last_name", "full_name", "email", "employee_id", "status", "page", "per_page", "updated_after", "updated_before", "created_after", "created_before"]
                invalid_page:
                  summary: page is not a positive whole number
                  value:
                    status: 400
                    message: "Bad Request: page must be a positive integer"
                    data: {}
                invalid_date:
                  summary: A date filter is not a valid date or timestamp
                  value:
                    status: 400
                    message: "updated_after must be a date (YYYY-MM-DD) or ISO 8601 timestamp"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

    post:
      operationId: createOnboardingEmployee
      tags:
        - Onboarding
      summary: Create or replace an onboarding record
      description: |
        Creates an onboarding record in Draft for a person you plan to hire, and copies the position's default pay onto it. Nothing is sent to the person: send the offer with `POST /v1/onboarding/{id}/send-offer`. Sending `onboarding_id` turns the call into a full replace of that record, which overwrites every field, including the ones you leave out.

        **Before you call:**

        - Pick `position_id` and `sub_position_id` from `GET /v1/positions`. The sub-position decides the pay that is copied and the offer letter template used later. If you leave it out, `position_id` is used for both.
        - Pick `office_id` from `GET /v1/locations`. Archived offices are refused on create.
        - Get allowed custom field names and options from `GET /v1/custom-fields?type=onboarding`.
        - Get `recruiter_id` and `manager_id` from `GET /v1/users`. The offer letter is sent as the recruiter (or, without one, the manager), and that name is printed on it. These ids are stored without being checked, so make sure they exist.
        - Check that the person is not already in Sequifi: `GET /v1/onboarding?email=` and `GET /v1/users?email=`, comparing the email exactly. An existing match on email or mobile number blocks the create.
        - Validate the email address and dates yourself. The API does not check the email format, and a malformed date is most likely rejected with `500`.

        **What happens:**

        Create (no `onboarding_id`) returns `201`:

        - The record is created with `status_id` 8 (Draft) and a new onboarding id string such as `ONB0012` (prefix set by your company, `ONB` by default).
        - The position's pay is copied onto the record: wages, commissions, upfronts (effective today in UTC), overrides, withholding and deductions. The counts come back in the response.
        - `department_id` comes from the position when you leave it out. State and city come from the office.
        - Nothing else happens: no email, no candidate update, no team membership.

        Replace (with `onboarding_id`) returns `200`:

        - Every field is overwritten from the body. Leaving out `manager_id`, `recruiter_id`, `team_id`, `lead_id` or `end_date` sets it to null. Leaving out `sub_position_id` sets it to `position_id`.
        - The record's pay is deleted and copied again from the position. Any pay an admin set on this record in the app is lost.
        - `custom_fields`, `work_email` and `additional_locations` are replaced only when the key is in the body. Send `[]` to clear one.
        - It works on any record: one whose offer was already sent (the sent letter does not change) and one already hired (the user does not change).
        - Safe practice: read the record with `GET /v1/onboarding/{id}`, change what you need, and send the complete record back, including every optional field you want to keep. Do not use it on records that already have an offer out or are hired.

        **Idempotency and retries:**

        - A create is not idempotent. Repeating a create that already succeeded returns `400 Email or mobile number already exists.` without the id. Find the record with `GET /v1/onboarding?email=` (or `GET /v1/users?email=` if it was already hired) and compare the email exactly.
        - After a timeout or network error, check for the record before you retry.
        - `503 Server is busy, please retry.` means nothing was created. Retry after a short wait.
        - Two creates for the same person sent at the same moment can both succeed. Send one person at a time.
        - A replace with the same complete body can be repeated safely.

        **Formats:**

        - `mobile_no`: exactly 10 digits, no spaces or symbols. A JSON number also works.
        - `start_date` and `end_date`: `YYYY-MM-DD`.
        - `custom_fields`: an array of single-key objects, for example `[{"Employment Type": "Full Time"}]`. Each name must be an onboarding custom field, and a field with options needs one of its option labels. All entries are merged into one object, which `GET /v1/onboarding` returns as a JSON string.
        - `work_email`: `[{"email": "alex@work.example.com"}]`. `additional_locations`: `[{"state_id": 5, "office_id": 12}]`.
        - `employee_id` in the response is the onboarding id string, not the user's employee id.
        - The response key is `requested_by` here, but `requestedBy` on the GET routes.

        **Errors:**

        - `400 first_name, last_name, email, mobile_no are required.` and `400 position_id, office_id, start_date are required.`
        - `400 mobile_no must be exactly 10 digits and must not contain characters.`
        - `400 Invalid custom field(s)` (with `data.invalid_fields`, `data.allowed_fields`) and `400 Invalid value for custom field '<name>'` (with `data.provided_value`, `data.allowed_values`).
        - `400 Email or mobile number already exists.`: a user or another onboarding record (hired or not) has this email or mobile number.
        - `400 Additional email <email> already exists.`
        - `400 Position with id <n> not found.`: missing, or not fully set up (create only). The id named is the sub-position when you sent one.
        - `400 Department with id <n> not found.`, `400 Office with id <n> not found.`, `400 Additional location office_id <n> not found.`, `400 additional_locations[n].office_id is required.`
        - `400 <position name> has no milestone_schema configured; cannot seed default upfronts.` and `400 A required field is missing. Please ensure the position is fully configured.`: the position's setup is incomplete. Ask your company admin to finish it.
        - `400 Invalid onboarding_id. Must be a positive integer.` and `404 Onboarding record with id <n> not found.` (replace only).
        - `400 Invalid or missing JSON body`
        - `503 Server is busy, please retry.`

        **Common mistakes:**

        - Leaving out `sub_position_id`. The record then uses `position_id`, which may have no offer letter template, so send-offer fails with `TEMPLATE_NOT_MAPPED`.
        - Sending only the changed fields with `onboarding_id`. The others are cleared and pay is reset.
        - Using `team_id` to put someone on a team. It is stored as a label only. Use `POST /v1/teams` after hire.
        - Re-onboarding someone who was onboarded before. Any earlier onboarding record or user with the same email or mobile number blocks the create.

        **Related:**

        - `POST /v1/onboarding/{id}/send-offer` sends the offer letter.
        - `GET /v1/onboarding/{id}` reads the record back.
        - `PUT /v1/onboarding/hire` creates the user once the offer is accepted.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - first_name
                - last_name
                - email
                - mobile_no
                - position_id
                - office_id
                - start_date
              properties:
                onboarding_id:
                  type: integer
                  nullable: true
                  description: Leave out (or send null) to create. Set it to replace that whole record; send every field you want to keep.
                  example: 4821
                first_name:
                  type: string
                  description: First name. Not trimmed.
                  example: "Alex"
                last_name:
                  type: string
                  description: Last name. Not trimmed.
                  example: "Morgan"
                email:
                  type: string
                  description: Personal email. The offer letter goes here. Must not match an existing user or onboarding record. The format is not checked.
                  example: "alex.morgan@example.com"
                mobile_no:
                  type: string
                  description: Exactly 10 digits. Must not match an existing user or onboarding record.
                  example: "5125550148"
                position_id:
                  type: integer
                  description: Position id from `GET /v1/positions`.
                  example: 14
                sub_position_id:
                  type: integer
                  nullable: true
                  description: Sub-position id. Decides the pay copied and the offer letter template. Defaults to `position_id`. Not checked against `position_id`.
                  example: 22
                office_id:
                  type: integer
                  description: Office id from `GET /v1/locations`. Archived offices are refused on create.
                  example: 7
                start_date:
                  type: string
                  format: date
                  description: Agreement start date, `YYYY-MM-DD`. Validate it before sending.
                  example: "2026-11-02"
                end_date:
                  type: string
                  format: date
                  nullable: true
                  description: Agreement end date, `YYYY-MM-DD`. Set to null on replace when left out.
                  example: null
                department_id:
                  type: integer
                  nullable: true
                  description: Taken from the position when left out. Send it only to use a different department; it must exist.
                  example: 3
                manager_id:
                  type: integer
                  nullable: true
                  description: Manager's user id. Not checked. Set to null on replace when left out.
                  example: 312
                recruiter_id:
                  type: integer
                  nullable: true
                  description: Recruiter's user id. The offer letter is sent as this user. Not checked. Set to null on replace when left out.
                  example: 57
                lead_id:
                  type: integer
                  nullable: true
                  description: Candidate id from `GET /v1/candidates`, kept as a link. The candidate is not changed. Not checked.
                  example: 1093
                team_id:
                  type: integer
                  nullable: true
                  description: Stored as a label only. It does not place the person on a team. Not checked.
                  example: null
                additional_locations:
                  type: array
                  description: Extra offices. On replace, sent only when present; `[]` clears them.
                  items:
                    type: object
                    required: [office_id]
                    properties:
                      state_id: { type: integer, description: State id. Not checked., example: 5 }
                      office_id: { type: integer, description: Office id. Must exist., example: 12 }
                work_email:
                  type: array
                  description: Work emails. Each must not already belong to a user or onboarding record. On replace, sent only when present.
                  items:
                    type: object
                    properties:
                      email: { type: string, description: Work email address., example: "alex@work.example.com" }
                custom_fields:
                  type: array
                  description: 'Onboarding custom fields as single-key objects, for example `[{"Employment Type": "Full Time"}]`. Names come from `GET /v1/custom-fields?type=onboarding`. On replace, sent only when present.'
                  items:
                    type: object
                    additionalProperties: true
                  example:
                    - Employment Type: "Full Time"
            examples:
              create:
                summary: Create a Draft record
                value:
                  first_name: "Alex"
                  last_name: "Morgan"
                  email: "alex.morgan@example.com"
                  mobile_no: "5125550148"
                  position_id: 14
                  sub_position_id: 22
                  office_id: 7
                  start_date: "2026-11-02"
                  recruiter_id: 57
                  manager_id: 312
                  lead_id: 1093
              replace:
                summary: Replace a record, sending every field to keep
                value:
                  onboarding_id: 4821
                  first_name: "Alex"
                  last_name: "Morgan"
                  email: "alex.morgan@example.com"
                  mobile_no: "5125550148"
                  position_id: 14
                  sub_position_id: 22
                  office_id: 7
                  start_date: "2026-11-09"
                  end_date: null
                  recruiter_id: 57
                  manager_id: 312
                  lead_id: 1093
                  team_id: null
      responses:
        '201':
          description: Created in Draft. Nothing was sent to the person.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 201
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requested_by:
                        type: string
                        description: Label of the API credentials that made the call.
                      onboarding_id:
                        type: integer
                        description: The new record's id. Use it for send-offer and hire.
                      employee_id:
                        type: string
                        description: Onboarding id string, for example `ONB0012`.
                      products_linked:
                        type: integer
                        description: Products on the position.
                      commissions_added:
                        type: integer
                        description: Commission settings copied from the position.
                      upfronts_added:
                        type: integer
                        description: Upfront settings copied.
                      overrides_added:
                        type: integer
                        description: Override settings copied.
                      withheld_added:
                        type: integer
                        description: Withholding settings copied.
                      deductions_added:
                        type: integer
                        description: Deductions copied.
              example:
                status: 201
                message: success
                data:
                  requested_by: "acme"
                  onboarding_id: 4821
                  employee_id: "ONB0012"
                  products_linked: 2
                  commissions_added: 3
                  upfronts_added: 1
                  overrides_added: 2
                  withheld_added: 0
                  deductions_added: 1
        '200':
          description: Replaced (the body had `onboarding_id`). Pay was reset to the position's defaults.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requested_by:
                        type: string
                        description: Label of the API credentials that made the call.
                      onboarding_id:
                        type: integer
                        description: The record that was replaced.
                      employee_id:
                        type: string
                        description: The record's onboarding id string (unchanged).
                      commissions_added:
                        type: integer
                        description: Commission settings copied again from the position. The other counts work the same way as on create.
              example:
                status: 200
                message: success
                data:
                  requested_by: "acme"
                  onboarding_id: 4821
                  employee_id: "ONB0012"
                  products_linked: 2
                  commissions_added: 3
                  upfronts_added: 1
                  overrides_added: 2
                  withheld_added: 0
                  deductions_added: 1
        '400':
          description: A field failed a check, the person already exists, or the position is not fully set up. The message says which.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_fields:
                  summary: A required name or contact field is missing
                  value:
                    status: 400
                    message: "first_name, last_name, email, mobile_no are required."
                    data: {}
                bad_mobile:
                  summary: mobile_no is not exactly 10 digits
                  value:
                    status: 400
                    message: "mobile_no must be exactly 10 digits and must not contain characters."
                    data: {}
                already_exists:
                  summary: A user or onboarding record has this email or mobile (also a repeated create)
                  value:
                    status: 400
                    message: "Email or mobile number already exists."
                    data: {}
                work_email_exists:
                  summary: A work email is already in use
                  value:
                    status: 400
                    message: "Additional email alex@work.example.com already exists."
                    data: {}
                invalid_custom_fields:
                  summary: Unknown custom field name
                  value:
                    status: 400
                    message: "Invalid custom field(s)"
                    data:
                      invalid_fields: ["Shirt Size"]
                      allowed_fields: ["Employment Type", "Additional Notes"]
                invalid_custom_field_value:
                  summary: Value is not one of the field's options
                  value:
                    status: 400
                    message: "Invalid value for custom field 'Employment Type'"
                    data:
                      provided_value: "Freelance"
                      allowed_values: ["Full Time", "Part Time", "Contract"]
                position_not_found:
                  summary: Position missing or not fully set up
                  value:
                    status: 400
                    message: "Position with id 22 not found."
                    data: {}
                office_not_found:
                  summary: Office missing or archived
                  value:
                    status: 400
                    message: "Office with id 7 not found."
                    data: {}
                position_incomplete:
                  summary: The position's pay setup is incomplete
                  value:
                    status: 400
                    message: "A required field is missing. Please ensure the position is fully configured."
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: Replace only. No onboarding record has this `onboarding_id`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Onboarding record with id 4821 not found."
                data: {}
        '500':
          description: Unexpected server error, including a malformed `start_date` or `end_date`. Check for the record before retrying a create.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
        '503':
          description: Busy assigning the next onboarding id. Nothing was created. Retry after a short wait.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 503
                message: "Server is busy, please retry."
                data: {}

  /v1/onboarding/{id}:
    get:
      operationId: getOnboardingEmployee
      tags:
        - Onboarding
      summary: Get an onboarding record
      description: |
        Returns one onboarding record that is not hired yet, as a single object in `data.onboarding_employee`. After `PUT /v1/onboarding/hire` the same id returns `404`, which is expected: follow the person at `GET /v1/users/{user_id}` from then on.

        **Formats:**

        - Same fields and formats as one item of `GET /v1/onboarding`, including the `status_id` list there.
        - `start_date` and `end_date` are calendar days returned as midnight UTC (`"2026-11-02T00:00:00.000Z"`). Use the first 10 characters.
        - `custom_fields` is a JSON-encoded string or null.

        **Errors:**

        - `400 Invalid onboarding id`: the id is not a positive whole number.
        - `400 Cannot use query parameters when fetching a single onboarding employee by id`
        - `404 Onboarding employee not found`: no record has this id, or the record was hired.

        **Related:**

        - `POST /v1/onboarding/{id}/send-offer` while the record is Draft (`status_id` 8).
        - `PUT /v1/onboarding/hire` once the candidate has accepted.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: Onboarding id, the `onboarding_id` returned by `POST /v1/onboarding`.
          schema:
            type: integer
            minimum: 1
          example: 4821
      responses:
        '200':
          description: The onboarding record.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      onboarding_employee:
                        type: object
                        description: The record, with the same fields as `GET /v1/onboarding`.
                        properties:
                          id: { type: integer, description: Onboarding id. }
                          employee_id: { type: string, description: 'Onboarding id string, for example `ONB0012`.' }
                          first_name: { type: string, description: First name. }
                          last_name: { type: string, description: Last name. }
                          email: { type: string, description: Personal email. }
                          status_id: { type: integer, description: 'Onboarding status id, for example `8` Draft or `4` Offer Sent, Unread.' }
                          status_name: { type: string, nullable: true, description: Status name. Can be renamed by your company. }
                          position_id: { type: integer, description: Position id. }
                          sub_position_id: { type: integer, nullable: true, description: 'Sub-position id. Equals `position_id` when none was sent.' }
                          office_id: { type: integer, description: Office id. }
                          manager_id: { type: integer, nullable: true, description: Manager's user id. }
                          recruiter_id: { type: integer, nullable: true, description: Recruiter's user id. }
                          start_date: { type: string, nullable: true, description: Agreement start day as midnight UTC. Use the date part. }
                          custom_fields: { type: string, nullable: true, description: Custom fields as a JSON-encoded string. }
                          updated_at: { type: string, description: UTC timestamp. }
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  onboarding_employee:
                    id: 4821
                    employee_id: "ONB0012"
                    first_name: "Alex"
                    last_name: "Morgan"
                    email: "alex.morgan@example.com"
                    mobile_no: "5125550148"
                    worker_type: "1099"
                    status_id: 4
                    position_id: 14
                    sub_position_id: 22
                    department_id: 3
                    office_id: 7
                    manager_id: 312
                    recruiter_id: 57
                    lead_id: 1093
                    team_id: null
                    start_date: "2026-11-02T00:00:00.000Z"
                    end_date: null
                    custom_fields: "{\"Employment Type\":\"Full Time\"}"
                    user_id: null
                    created_at: "2026-10-01T15:22:08.000Z"
                    updated_at: "2026-10-02T09:41:30.000Z"
                    position_name: "Setter"
                    office_name: "Austin"
                    status_name: "Offer Sent, Unread"
        '400':
          description: The id is invalid, or query parameters were sent with it.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid onboarding id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single onboarding employee by id"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: No record has this id, or the record was hired (expected after `PUT /v1/onboarding/hire`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Onboarding employee not found"
                data: {}
        '500':
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/onboarding/hire:
    put:
      operationId: hireOnboardingEmployee
      tags:
        - Onboarding
      summary: Create a user from onboarding
      description: |
        Creates an active user (a rep) from an onboarding record and marks the record as hired. This is not the same as **Hire** in the Sequifi app: it only copies the record's data into a new user. Nothing is set up with your company's payroll provider and the person's documents are not moved. No welcome email goes out unless you send `send_welcome_email: true`; without it the rep cannot log in until someone sends one from the app.

        **Before you call:**

        - Check the record's `status_id` with `GET /v1/onboarding/{id}`. This call does not check it: a Draft record that never got an offer, or a declined or expired one, is hired the same way. Gate on acceptance yourself (for example `status_id` 13, 22 or 23).
        - Make sure no user already has the same email or mobile number. The call is refused if one does.
        - Plan who will finish the hire in the app (see "Not done" below).

        **What happens:**

        Done, in one step:

        - A new active user is created from the record: name, email, mobile, position, sub-position, office, department, manager, recruiter, team and agreement dates. `worker_type` comes from the sub-position (`1099` when not set). If the record has no recruiter, the recruiter is set to the Marketplace API system user.
        - The user gets a new employee id, for example `EMP000245`. It is its own sequence, not derived from `user_id`.
        - The record's pay (wages, commissions, upfronts, overrides, withholding, deductions), work emails, extra offices, and manager, office and department history are copied to the user, effective on the record's start date.
        - The onboarding record moves to `status_id` 7. Its default name is **Onboarding**, not Hired. It then drops out of `GET /v1/onboarding`.

        Not done (an admin has to do these in the Sequifi app):

        - No welcome email unless you send `send_welcome_email: true`. Without it the user's password is random and nobody is told it; an admin can send the email from the rep's profile with **Resend Welcome Email**.
        - No setup with your company's payroll provider. Payroll onboarding has to be finished in the app.
        - The offer letter and onboarding documents stay on the onboarding record, and post-hire documents are not sent.
        - No in-app notification, no updates to connected integrations, and no payroll recalculation.
        - The person is not added to a team. `team_id` is copied as a label only; use `POST /v1/teams`.
        - No background-check email.

        **Welcome email (`send_welcome_email: true`):**

        - Sends the same welcome email as **Resend Welcome Email** in the app: your company's welcome template with a single-use link to set a password. It sends no offer letter or documents. To send the offer letter and its documents, use `POST /v1/onboarding/{id}/send-offer` before hiring.
        - The result is in `data.welcome_email`: `{ "status": "sent" }`, or `{ "status": "not_sent", "code", "message" }`.
        - `not_sent` codes: `PASSWORD_ALREADY_SET` (the rep already set a password), `NOT_CONFIGURED` (contact Sequifi support), `NOT_SENT` (the email could not be sent or confirmed; the message says why).

        **Idempotency and retries:**

        - Not idempotent. A second call for the same record returns `400 Email or mobile number already exists.`
        - A slow call can time out at the gateway (about 29 seconds) after the user was created. Before you retry, look for the user with `GET /v1/users?email=<email>` and compare the email exactly.
        - `503 Server is busy, please retry.` means nothing was created. Retry after a short wait.
        - Hire one record at a time. Two hires at the same moment can be given the same `employee_id`.
        - The welcome email is sent after the user is created. If it fails, the call still returns `200` with `data.welcome_email.status` `not_sent`. Do not retry the hire: an admin can send the email with **Resend Welcome Email**.

        **Formats:**

        - `user_id` is an integer. `employee_id` is a string.
        - `onboarding_id` is echoed exactly as you sent it (a string if you sent a string).
        - `products` limits which products' commissions, upfronts, overrides and withholding are copied. Deductions are always copied in full. Leave it out to copy everything.
        - The response key is `requested_by` here, but `requestedBy` on the GET routes.

        **Errors:**

        - `400 onboarding_id is required.` and `400 Invalid onboarding_id. Must be a positive integer.`
        - `400 Invalid product id(s): <ids>`: a product does not exist, is inactive or was deleted.
        - `400 send_welcome_email must be true or false.`
        - `400 Email or mobile number already exists.`: a user already has this email or mobile number. Usually the record was already hired, by an earlier call or in the app.
        - `400 A required field is missing. Please ensure the position is fully configured.`: the position's setup is incomplete. Ask your company admin to finish it.
        - `404 Onboarding employee not found.`
        - `503 Server is busy, please retry.`

        **Common mistakes:**

        - Treating a `200` as "the rep can start". They are not set up for payroll, and they cannot log in unless `data.welcome_email.status` is `sent`.
        - Calling `GET /v1/onboarding/{id}` afterwards and treating the `404` as a failure. Hired records leave onboarding; follow the person at `GET /v1/users/{user_id}`.
        - Expecting the person to be on a team. Create the membership with `POST /v1/teams`.

        **Related:**

        - `GET /v1/users/{user_id}` shows the new user with `hiring_status_id` 7 and `onboarding_complete` 0 or false.
        - `POST /v1/teams` puts the rep on a team.
        - `GET /v1/documents?user_id=<user_id>` finds the person's documents, including those still on the onboarding record.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - onboarding_id
              properties:
                onboarding_id:
                  type: integer
                  description: The onboarding id to hire, from `POST /v1/onboarding` or `GET /v1/onboarding`.
                  example: 4821
                products:
                  type: array
                  description: Product ids. When set, only these products' commissions, upfronts, overrides and withholding are copied. Deductions are always copied. Each must be an active product.
                  items:
                    type: integer
                  example: [1, 2]
                send_welcome_email:
                  type: boolean
                  description: When true, sends the rep the welcome email with a link to set their password after the hire. The result is in `data.welcome_email`. Default false.
                  example: true
            examples:
              hire:
                summary: Hire with all products
                value:
                  onboarding_id: 4821
              hire_and_welcome:
                summary: Hire and send the welcome email
                value:
                  onboarding_id: 4821
                  send_welcome_email: true
              hire_some_products:
                summary: Hire and copy pay for two products only
                value:
                  onboarding_id: 4821
                  products: [1, 2]
      responses:
        '200':
          description: The user was created. They cannot log in yet and are not set up with the payroll provider.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requested_by:
                        type: string
                        description: Label of the API credentials that made the call.
                      user_id:
                        type: integer
                        description: The new user's id. Use it with `GET /v1/users/{id}` and `POST /v1/teams`.
                      employee_id:
                        type: string
                        description: The new user's employee id, for example `EMP000245`.
                      onboarding_id:
                        description: The onboarding id, echoed exactly as sent (number or string).
                      welcome_email:
                        type: object
                        description: Only when `send_welcome_email` was true.
                        properties:
                          status:
                            type: string
                            enum: [sent, not_sent]
                          code:
                            type: string
                            description: Only when `not_sent`. `PASSWORD_ALREADY_SET`, `NOT_CONFIGURED` or `NOT_SENT`.
                          message:
                            type: string
                            description: Only when `not_sent`. Why it was not sent.
              example:
                status: 200
                message: success
                data:
                  requested_by: "acme"
                  user_id: 6150
                  employee_id: "EMP000245"
                  onboarding_id: 4821
                  welcome_email:
                    status: sent
        '400':
          description: Invalid input, an inactive product, or a user with this email or mobile number already exists.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_onboarding_id:
                  summary: onboarding_id not sent
                  value:
                    status: 400
                    message: "onboarding_id is required."
                    data: {}
                invalid_onboarding_id:
                  summary: onboarding_id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid onboarding_id. Must be a positive integer."
                    data: {}
                already_exists:
                  summary: A user has this email or mobile (often already hired)
                  value:
                    status: 400
                    message: "Email or mobile number already exists."
                    data: {}
                invalid_product_ids:
                  summary: A product is missing, inactive or deleted
                  value:
                    status: 400
                    message: "Invalid product id(s): 9"
                    data: {}
                position_incomplete:
                  summary: The position's setup is incomplete
                  value:
                    status: 400
                    message: "A required field is missing. Please ensure the position is fully configured."
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: No onboarding record has this id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Onboarding employee not found."
                data: {}
        '500':
          description: Unexpected server error. Check `GET /v1/users?email=` before retrying.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
        '503':
          description: Busy assigning the next employee id. Nothing was created. Retry after a short wait.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 503
                message: "Server is busy, please retry."
                data: {}

  /v1/onboarding/{id}/send-offer:
    post:
      operationId: sendOfferLetter
      tags:
        - Onboarding
      summary: Send an offer letter
      description: |
        Emails the candidate their offer letter for a Draft onboarding record, the same way **Send offer letter** works in the Sequifi app. The letter template comes from the record's sub-position, which equals `position_id` when none was sent at create, so that position needs an offer letter template. A `200` means the send ran, not that the email arrived: read `data.outcome`, and validate email addresses before you create the record.

        **Before you call:**

        - The record must be in Draft (`status_id` 8), which is how `POST /v1/onboarding` creates it.
        - Your company must have SequiDocs turned on.
        - An offer letter template must be assigned to the record's sub-position and marked ready. API-created records always have a sub-position: when you did not send `sub_position_id`, it equals `position_id`, which is often a parent position with no template. Send the real `sub_position_id` at create time.
        - The candidate's email domain must be allowed by your company's email settings.
        - The offer is sent as the record's recruiter, else its manager, else the first active company admin, and that name is printed on the letter. Set `recruiter_id` at create time if the signature matters.

        **What happens:**

        The call waits for the send to finish (up to 25 seconds).

        - If your company requires approval of offers, the record moves to `status_id` 17 (Offer Review) and nothing is emailed. `outcome` is `queued_for_review`. An admin approves it in the app.
        - Otherwise the offer letter is generated as an e-sign document, with any documents attached to the template, and emailed to the candidate's personal `email` (not a work email) with a signing link. The record moves to `status_id` 4 (Offer Sent, Unread). `outcome` is `sent`.
        - If the record is flagged for a background check and your company has S-Clearance, a background-check email is sent too.
        - After that, the status changes as the candidate acts: 21 opened, 13, 22 or 23 accepted, 16 document review, 6 change requested, 2 declined, 5 expired. Poll `GET /v1/onboarding/{id}`.

        **Idempotency and retries:**

        - Safe to retry. Only a Draft record can be sent, so a repeat returns `409 NOT_SENDABLE` with the current `status_id`. Treat that as "already sent or waiting for review". It also fires when someone sent the offer in the app.
        - A failed send leaves the record in Draft, so you can fix the cause and call again.
        - On `502` or `504`, wait, retry once, and read the code. `409 NOT_SENDABLE` means the first call worked.
        - Sends are limited to about 120 a minute for your company, and repeats count too.

        **Formats:**

        - The body is optional. Send `{}` or `{"template_id": 87}`. Other keys are ignored.
        - `data.outcome` is `sent` or `queued_for_review`. `data.status_id` is 4 or 17.
        - `data.template_id` is the template used. `data.sent_by_user_id` is the user the offer was sent as.
        - Errors from the send carry `data.code` and `data.requestedBy`, and `409`/`422` errors also carry `data.onboarding_id`, `data.status_id` and `data.status_name`. Branch on `data.code`, not on `message`.

        **Errors:**

        - `400 Invalid onboarding id`, `400 Invalid JSON body`, `400 template_id must be a positive integer`
        - `404 No onboarding record with id <n>.` (`NOT_FOUND`)
        - `409` `ADDON_DISABLED`: SequiDocs is off for your company. `409` `NOT_SENDABLE`: the record is not in Draft.
        - `422` `TEMPLATE_NOT_MAPPED`: no offer letter template is assigned to the sub-position (or `template_id` is not one of them). `TEMPLATE_NOT_READY`: the template is not marked ready. `NO_SENDER`: no recruiter, manager or active admin to send as. Your company admin fixes these in the app.
        - `422` `SEND_FAILED`: the send stopped with a reason in `message`, for example `Domain setting isn't allowed to send email on this domain!!` (the candidate's email domain is not allowed) or `Offer Expiry Date should be in the future`. The record stays in Draft.
        - `500 The offer letter could not be sent.` (`SEND_FAILED`), or `500 Could not resolve the tenant host`. The record stays in Draft.
        - `502 Could not reach the tenant` or `502 The tenant returned an unreadable response`. The second most likely also covers going over about 120 sends a minute and unexpected errors. No `Retry-After` header is sent. Wait, then retry once.
        - `503`: your company is not set up for offer sending over the API. Contact Sequifi support.
        - `504`: no answer in time. The offer may have been sent. Retry once and read the code.

        **Common mistakes:**

        - Reading `200` as "the candidate has the offer". A mistyped email address is still reported as `sent`.
        - Leaving out `sub_position_id` on create, then getting `TEMPLATE_NOT_MAPPED` here.
        - Expecting the candidate to get login access from this email. It carries a signing link only.
        - Hiring before the candidate accepts. `PUT /v1/onboarding/hire` does not check.

        **Related:**

        - `POST /v1/onboarding` creates the Draft record.
        - `GET /v1/onboarding/{id}` to follow the status.
        - `PUT /v1/onboarding/hire` once the offer is accepted.
      security:
        - bearerAuth: []
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: integer
            minimum: 1
          description: The `onboarding_id` returned by `POST /v1/onboarding`. Not a user id; no user exists until hire.
          example: 4821
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                template_id:
                  type: integer
                  description: Optional. Which offer letter template to use when the sub-position has more than one. Must be a template assigned to the record's sub-position as an offer letter. Leave it out to use the assigned template.
                  example: 87
            examples:
              default_template:
                summary: Use the template assigned to the sub-position
                value: {}
              chosen_template:
                summary: Choose one of the sub-position's templates
                value:
                  template_id: 87
      responses:
        '200':
          description: The send ran. Read `data.outcome`; `sent` does not prove the email was delivered.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    description: '`Offer letter sent.` or `Offer letter queued for internal review.`'
                    example: "Offer letter sent."
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      onboarding_id:
                        type: integer
                        description: The onboarding id.
                      employee_id:
                        type: string
                        description: Onboarding id string, for example `ONB0012`.
                      outcome:
                        type: string
                        enum: [sent, queued_for_review]
                        description: '`sent`: emailed to the candidate (delivery not confirmed). `queued_for_review`: waiting for an admin; nothing emailed yet.'
                      status_id:
                        type: integer
                        description: '`4` (Offer Sent, Unread) or `17` (Offer Review).'
                      status_name:
                        type: string
                        description: Current status name.
                      template_id:
                        type: integer
                        nullable: true
                        description: The offer letter template used.
                      sent_by_user_id:
                        type: integer
                        description: The user the offer was sent as (recruiter, manager or company admin).
              examples:
                sent:
                  summary: Offer emailed to the candidate
                  value:
                    status: 200
                    message: "Offer letter sent."
                    data:
                      requestedBy: "acme"
                      onboarding_id: 4821
                      employee_id: "ONB0012"
                      outcome: "sent"
                      status_id: 4
                      status_name: "Offer Sent, Unread"
                      template_id: 87
                      sent_by_user_id: 57
                queued_for_review:
                  summary: Your company requires approval; nothing emailed yet
                  value:
                    status: 200
                    message: "Offer letter queued for internal review."
                    data:
                      requestedBy: "acme"
                      onboarding_id: 4821
                      employee_id: "ONB0012"
                      outcome: "queued_for_review"
                      status_id: 17
                      status_name: "Offer Review"
                      template_id: 87
                      sent_by_user_id: 57
        '400':
          description: The path id or the body is invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Path id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid onboarding id"
                    data: {}
                invalid_template_id:
                  summary: template_id is not a positive whole number
                  value:
                    status: 400
                    message: "template_id must be a positive integer"
                    data: {}
                invalid_json:
                  summary: The body is not valid JSON
                  value:
                    status: 400
                    message: "Invalid JSON body"
                    data: {}
        '401':
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        '404':
          description: No onboarding record has this id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "No onboarding record with id 4821."
                data:
                  requestedBy: "acme"
                  code: "NOT_FOUND"
        '409':
          description: The record is not in Draft (`NOT_SENDABLE`, also the answer to a retry of a call that worked), or SequiDocs is off for your company (`ADDON_DISABLED`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_sendable:
                  summary: Already sent or waiting for review
                  value:
                    status: 409
                    message: "This record is no longer in Draft, so an offer has already been sent or is awaiting review. Current status: Offer Sent, Unread."
                    data:
                      requestedBy: "acme"
                      code: "NOT_SENDABLE"
                      onboarding_id: 4821
                      status_id: 4
                      status_name: "Offer Sent, Unread"
                addon_disabled:
                  summary: SequiDocs is not enabled for the company
                  value:
                    status: 409
                    message: "SequiDocs is not enabled for this company, so offer letters cannot be sent."
                    data:
                      requestedBy: "acme"
                      code: "ADDON_DISABLED"
                      onboarding_id: 4821
                      status_id: 8
                      status_name: "Draft"
        '422':
          description: A setup requirement is not met, or the send stopped. Branch on `data.code`. The record stays in Draft.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                template_not_mapped:
                  summary: No offer letter template assigned to the sub-position
                  value:
                    status: 422
                    message: "No offer letter template is mapped to sub-position \"Setter\" (id 14). An administrator must assign an offer letter template to that position before an offer can be sent."
                    data:
                      requestedBy: "acme"
                      code: "TEMPLATE_NOT_MAPPED"
                      onboarding_id: 4821
                      status_id: 8
                      status_name: "Draft"
                template_not_ready:
                  summary: The assigned template is not finished
                  value:
                    status: 422
                    message: "Offer letter template \"Setter Offer\" (id 87) is not marked ready. An administrator must finish configuring it before an offer can be sent."
                    data:
                      requestedBy: "acme"
                      code: "TEMPLATE_NOT_READY"
                      onboarding_id: 4821
                      status_id: 8
                      status_name: "Draft"
                no_sender:
                  summary: No user to send the offer as
                  value:
                    status: 422
                    message: "Could not determine a user to send this offer letter on behalf of. The record has no recruiter or manager, and no active company admin was found."
                    data:
                      requestedBy: "acme"
                      code: "NO_SENDER"
                      onboarding_id: 4821
                      status_id: 8
                      status_name: "Draft"
                send_failed:
                  summary: The candidate's email domain is not allowed
                  value:
                    status: 422
                    message: "Domain setting isn't allowed to send email on this domain!!"
                    data:
                      requestedBy: "acme"
                      code: "SEND_FAILED"
                      onboarding_id: 4821
                      status_id: 8
                      status_name: "Draft"
        '429':
          description: 'Rate limited at the gateway. The body is `{"message":"Too Many Requests"}`. Going over your company''s limit of about 120 sends a minute most likely shows up as `502` instead. Wait and retry.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Too Many Requests }
              example:
                message: Too Many Requests
        '500':
          description: The send failed unexpectedly (`SEND_FAILED`), or the company's Sequifi address could not be resolved. The record stays in Draft.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The offer letter could not be sent."
                data:
                  requestedBy: "acme"
                  code: "SEND_FAILED"
                  onboarding_id: 4821
                  status_id: 8
                  status_name: "Draft"
        '502':
          description: Your company's Sequifi app could not be reached, or sent a response the API could not read. The second case most likely also covers its rate limit and unexpected errors. Wait, retry once, and read the code.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unreachable:
                  summary: Could not connect
                  value:
                    status: 502
                    message: "Could not reach the tenant"
                    data:
                      onboarding_id: 4821
                unreadable:
                  summary: Unreadable response (likely a rate limit or unexpected error)
                  value:
                    status: 502
                    message: "The tenant returned an unreadable response"
                    data: {}
        '503':
          description: Your company is not set up for offer sending over the API. Contact Sequifi support.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 503
                message: "This tenant is not configured for offer letter sending. Contact Sequifi support."
                data: {}
        '504':
          description: No answer in time. The offer may still have been sent. Retry once; `409 NOT_SENDABLE` means it was.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The offer may still have been sent — retry this call: it returns 409 NOT_SENDABLE if the offer already went out."
                data:
                  onboarding_id: 4821

  /v1/users/termination:
    post:
      operationId: toggleUserDismissal
      tags:
        - Users
      summary: Dismiss a worker or undo a dismissal
      description: |
        Dismisses a worker, or undoes the dismissal if they already have one on file. There is no parameter to choose: each call flips the state, so a retried call undoes the first one. Check the worker's `status_id` with `GET /v1/users/{id}` before you call, and never retry this call automatically.

        Dismissal does not block login. A dismissed worker can still sign in to the app. Login is controlled only by Suspend access in the web app, which this API does not change.

        **Before you call:**

        - Take `user_id` from `GET /v1/users`.
        - Read `GET /v1/users/{id}` and decide from `status_id` whether the call should dismiss or undo a dismissal. A dismissal made through this endpoint sets `status_id` to `2`.

        **What happens:**

        - No dismissal on file: a dismissal dated today (UTC) is recorded and `status_id` becomes `2`. Sign-in is not changed. `message` is `Employee dismissed successfully`.
        - A dismissal on file (made here or in the app): every dismissal record for the worker is deleted and `status_id` becomes `1` (active). Sign-in is not changed, so a worker whose access was suspended stays suspended until someone uses Restore access in the web app. `message` is `Employee enabled successfully`. This happens whatever the reason the worker was inactive.
        - Any existing worker is accepted, whatever their status.
        - Both outcomes return `201`. Only `message` tells you which one happened.
        - This endpoint records no last working day. To record an effective-dated dismissal, including a past date, use `POST /v1/users/{id}/terminate`.

        **Idempotency and retries:**

        - Not safe to retry. If a call times out or the response is lost, read `GET /v1/users/{id}` and check `status_id` before deciding whether to call again.

        **Formats:**

        - `user_id` is an integer. A numeric string also works.
        - The dismissal date is today's date in UTC. In US time zones that is already tomorrow from 5 pm Pacific (8 pm Eastern) during daylight saving time, an hour earlier in winter.

        **Errors:**

        - `400` `user_id is required` (missing, `0` or empty) or `Invalid JSON body`.
        - `404` `User not found`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/users/{id}` to check the state before and after.
        - `POST /v1/users/{id}/terminate` to record an effective-dated dismissal.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - user_id
              properties:
                user_id:
                  type: integer
                  minimum: 1
                  description: Id of the worker to dismiss or whose dismissal to undo, from `GET /v1/users`.
                  example: 4821
            example:
              user_id: 4821
      responses:
        '201':
          description: Worker dismissed or dismissal undone. Read `message` to see which.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      status:
                        type: integer
                        description: Always 201.
                      message:
                        type: string
                        enum: ["Employee dismissed successfully", "Employee enabled successfully"]
                        description: The only indication of which way the toggle went.
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
              examples:
                dismissed:
                  summary: Worker dismissed
                  value:
                    status: 201
                    message: "Employee dismissed successfully"
                    data:
                      requestedBy: "acme"
                enabled:
                  summary: Dismissal undone
                  value:
                    status: 201
                    message: "Employee enabled successfully"
                    data:
                      requestedBy: "acme"
        '400':
          description: Missing user_id or malformed JSON
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_user_id:
                  summary: user_id missing, 0 or empty
                  value:
                    status: 400
                    message: "user_id is required"
                    data: {}
                invalid_json:
                  summary: Body is not valid JSON
                  value:
                    status: 400
                    message: "Invalid JSON body"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: No user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/terminate:
    post:
      operationId: terminateUser
      tags:
        - Users
      summary: Dismiss a worker with an effective date
      description: |
        Records an effective-dated dismissal for a worker, using the last working day you supply, which may be in the past. The same date twice is a safe retry; a different date for a worker already dismissed this way returns `409`.

        **Before you call:**

        - `id` is the user id from `GET /v1/users`, not an onboarding id.
        - Decide the last working day. `effective_date` is required and has no default.

        **What happens:**

        - The dismissal is added to the worker's employment history with your `effective_date`. App sign-in is turned off and the rest of Sequifi updates as it does for the same change made in the app.
        - `effective_date` is the last day worked, not the first day gone. A worker dismissed effective the 15th is still paid for a pay period that starts on the 15th, and is left out of every period that starts after it.
        - Commissions already earned are not affected. Amounts already owed keep paying out through normal payroll, and a later milestone on a sale the rep already owns still earns commission. Holding back a departed rep's pending pay is a separate admin action that this API does not offer.
        - This API cannot reverse the record. A worker is brought back with Rehire in the web app, which starts a new contract. A call sent in error needs Sequifi support.
        - `POST /v1/users/termination` is different: it toggles a dismissal dated today and records no last working day.

        **Idempotency and retries:**

        - Sending the same `effective_date` again returns `200` with `already_terminated: true` and changes nothing, so a timed-out call is safe to retry with the same date.
        - A different `effective_date` for a worker already dismissed this way returns `409` with the date on file.

        **Formats:**

        - `effective_date` is `YYYY-MM-DD` and must be a real calendar day. Other body fields are ignored.
        - The success response `status` is the number `200`.

        **Errors:**

        - `400` `Invalid user id`, `Invalid JSON body`, or one of the two `effective_date` messages in the examples.
        - `404` with `data.code` `NOT_FOUND`: no user with that id.
        - `409` with `data.code` `ALREADY_TERMINATED`: terminated on another date (`data.effective_date`).
        - `500` with `data.code` `TERMINATION_FAILED`, or `Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502` `The tenant returned an unreadable response` or `Could not reach the tenant`: retry later with the same date.
        - `503`: your company is not set up for this endpoint yet. Contact Sequifi support.
        - `504`: no answer in time. The dismissal may still have been applied, so retry with the same date and read `already_terminated`.
        - Errors passed back from Sequifi carry `data.code` and `data.requestedBy`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/users/{id}` to confirm the change.
        - `POST /v1/users/termination` to dismiss a worker without a last working day, or undo that dismissal.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            minimum: 1
          description: User id from `GET /v1/users`.
          example: 4821
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - effective_date
              properties:
                effective_date:
                  type: string
                  format: date
                  description: The worker's last working day, YYYY-MM-DD. May be in the past.
                  example: "2026-09-15"
            example:
              effective_date: "2026-09-15"
      responses:
        '200':
          description: Dismissal applied, or already on file for this date
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          user_id:
                            type: integer
                            description: The dismissed worker.
                          effective_date:
                            type: string
                            format: date
                            description: Last working day on file, YYYY-MM-DD.
                          already_terminated:
                            type: boolean
                            description: True when this date was already on file and nothing changed.
              examples:
                applied:
                  summary: Dismissal applied
                  value:
                    status: 200
                    message: "Termination applied."
                    data:
                      requestedBy: "acme"
                      user_id: 4821
                      effective_date: "2026-09-15"
                      already_terminated: false
                repeated:
                  summary: Same date sent again (safe retry)
                  value:
                    status: 200
                    message: "User is already terminated effective this date."
                    data:
                      requestedBy: "acme"
                      user_id: 4821
                      effective_date: "2026-09-15"
                      already_terminated: true
        '400':
          description: Invalid id, body or date
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_effective_date:
                  summary: effective_date not sent
                  value:
                    status: 400
                    message: "effective_date is required. It is the employee's last working day, in YYYY-MM-DD format."
                    data: {}
                bad_effective_date:
                  summary: effective_date is not a real YYYY-MM-DD date
                  value:
                    status: 400
                    message: "effective_date must be a date in YYYY-MM-DD format."
                    data: {}
                invalid_id:
                  summary: Path id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid user id"
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '404':
          description: No user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "No user with id 4821."
                data:
                  requestedBy: "acme"
                  code: "NOT_FOUND"
        '409':
          description: Already dismissed with a different effective date
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 409
                message: "User 4821 is already terminated effective 2026-09-15."
                data:
                  requestedBy: "acme"
                  code: "ALREADY_TERMINATED"
                  user_id: 4821
                  effective_date: "2026-09-15"
        '500':
          description: The dismissal could not be applied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The termination could not be applied."
                data:
                  requestedBy: "acme"
                  code: "TERMINATION_FAILED"
        '502':
          description: Sequifi could not complete the request. Retry later with the same date.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 502
                message: "Could not reach the tenant"
                data:
                  user_id: 4821
        '503':
          description: Your company is not set up for effective-dated dismissals over the API. Contact Sequifi support; this is not a problem with your token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This tenant is not configured for termination over the API. Contact Sequifi support."
                    data: {}
                not_provisioned:
                  summary: Not provisioned
                  value:
                    status: 503
                    message: "This tenant is not provisioned for Marketplace API writes. Contact Sequifi support."
                    data:
                      requestedBy: "acme"
                      code: "NOT_PROVISIONED"
        '504':
          description: No answer in time. The dismissal may still have been applied; retry with the same `effective_date` and read `already_terminated`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The termination may still have been applied — retry this call with the same effective_date: it returns already_terminated=true if the first attempt landed."
                data:
                  user_id: 4821

  /v1/milestones:
    get:
      operationId: listMilestoneSchemas
      tags:
        - Milestones
      summary: List milestone schemas
      description: |
        Lists your company's milestone schemas (payment plans), each with its milestones in order and the products linked to it. Use it to look up the milestone ids that `POST /v1/sales` expects in `milestone_dates[].milestone_id`. Send the ids from the inner `milestones[]` array, not the schema `id`.

        **What happens:**

        - Read-only. Each schema returns its milestones in `milestones[]`, numbered by `order` (1 is the first milestone), and its linked products in `products[]`.
        - `milestones[].id` is the milestone id to send on `POST /v1/sales`. `code` is the schema `prefix` plus the order number (for example `M1`).
        - `products[]` lists every product linked to the schema with an effective date of today (UTC) or earlier, including past links. A product that moved to another schema is listed under both, and nothing marks which link is current. Deleted products are left out.

        **Filtering and paging:**

        - Filters combine with AND. An unknown parameter returns `400` with `invalid_params` and `allowed_params`.
        - `page` defaults to 1 and `per_page` to 10, with no maximum. A `per_page` that is not a positive whole number falls back to 10. A `page` of `0` or text falls back to 1.
        - Newest schema first (`id` descending). `last_page` is `0` when nothing matches.

        **Formats:**

        - `status` is a string (`"1"` or `"0"`), not a number.

        **Errors:**

        - `400 Invalid query parameter(s)`: an unknown query parameter.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`, without `status` or `data`.
        - `500 Internal Server Error`: a server error. A negative `page` is not rejected and also returns `500`.

        **Common mistakes:**

        - Sending the schema `id`, or the `order` number, as `milestone_id`. Send `milestones[].id`.
        - Assuming the first schema that lists a product is the current one. If a product appears under more than one schema, ask your Sequifi admin which one is current.

        **Related:**

        - `GET /v1/milestones/{id}`: one schema by its `id`.
        - `GET /v1/products`: the product `id` for the `product` filter.
        - `POST /v1/sales`: send milestone dates in `milestone_dates[]`.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          description: Page number, starting at 1. `0` or text falls back to 1. A negative number returns `500`.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Schemas per page. Default 10, no maximum. A value that is not a positive whole number falls back to 10.
          schema:
            type: integer
            minimum: 1
            default: 10
          example: 10
        - name: status
          in: query
          required: false
          description: Exact match on the schema `status` (`1` active, `0` inactive).
          schema:
            type: string
          example: "1"
        - name: schema_name
          in: query
          required: false
          description: Partial match on the schema name. `%` and `_` act as wildcards.
          schema:
            type: string
          example: Solar
        - name: schema_description
          in: query
          required: false
          description: Partial match on the schema description. `%` and `_` act as wildcards.
          schema:
            type: string
          example: install
        - name: product
          in: query
          required: false
          description: Integer product `id` from `GET /v1/products` (not the product code). Returns schemas linked to that product with an effective date of today (UTC) or earlier, including past links.
          schema:
            type: integer
          example: 12
        - name: noofpayment
          in: query
          required: false
          description: Exact number of milestones in the schema.
          schema:
            type: integer
          example: 2
      responses:
        '200':
          description: One page of milestone schemas.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Number of schemas that match the filters.
                          last_page:
                            type: integer
                            description: Last page number. `0` when nothing matches.
                          schemas:
                            type: array
                            description: Matching schemas, newest first.
                            items:
                              $ref: '#/components/schemas/MilestoneSchema'
              examples:
                with_schemas:
                  summary: Schemas found
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 1
                      last_page: 1
                      schemas:
                        - id: 3
                          prefix: "M"
                          schema_name: "Solar Standard"
                          schema_description: "Paid at site survey and at install"
                          status: "1"
                          milestone_trigger_count: 2
                          products:
                            - id: 12
                              name: "Solar Rooftop"
                          milestones:
                            - id: 41
                              code: "M1"
                              name: "Site Survey"
                              trigger_date_label: "Site Survey Date"
                              order: 1
                            - id: 42
                              code: "M2"
                              name: "Install"
                              trigger_date_label: "Install Date"
                              order: 2
                no_match:
                  summary: Nothing matches the filters
                  value:
                    status: 200
                    message: success
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 0
                      last_page: 0
                      schemas: []
        '400':
          description: Unknown query parameter.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Invalid query parameter(s)"
                data:
                  invalid_params: ["shema"]
                  allowed_params: ["page", "per_page", "status", "schema_name", "schema_description", "product", "noofpayment"]
        '401':
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        '500':
          description: Server error, including a negative `page`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/milestones/{id}:
    get:
      operationId: getMilestoneSchema
      tags:
        - Milestones
      summary: Get a milestone schema
      description: |
        Returns one milestone schema by its schema `id`, with its milestones in order and its linked products. The path takes the schema id. The ids inside `data.schema.milestones[]` are the milestone ids that `POST /v1/sales` expects as `milestone_id`.

        **What happens:**

        - Read-only. Returns the same fields as one item of `GET /v1/milestones`, under `data.schema`, with no paging fields.
        - `products[]` includes past product links with an effective date of today (UTC) or earlier, so a product can appear under more than one schema.

        **Errors:**

        - `400 Invalid milestone id`: the id is not a positive number. The id is read up to the first non-digit, so `12abc` is read as `12`.
        - `400 Cannot use query parameters when fetching a single milestone by id`: any query parameter was sent.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `404 Milestone not found`: no schema has this id.

        **Common mistakes:**

        - Sending this schema `id` as `milestone_dates[].milestone_id`. Send `data.schema.milestones[].id`.

        **Related:**

        - `GET /v1/milestones?product=<id>`: find the schema for a product.
        - `POST /v1/sales`: send milestone dates.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The schema `id` from `GET /v1/milestones`. Not a milestone id.
          schema:
            type: integer
            minimum: 1
          example: 3
      responses:
        '200':
          description: The schema.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential that made the call.
                          schema:
                            $ref: '#/components/schemas/MilestoneSchema'
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  schema:
                    id: 3
                    prefix: "M"
                    schema_name: "Solar Standard"
                    schema_description: "Paid at site survey and at install"
                    status: "1"
                    milestone_trigger_count: 2
                    products:
                      - id: 12
                        name: "Solar Rooftop"
                    milestones:
                      - id: 41
                        code: "M1"
                        name: "Site Survey"
                        trigger_date_label: "Site Survey Date"
                        order: 1
                      - id: 42
                        code: "M2"
                        name: "Install"
                        trigger_date_label: "Install Date"
                        order: 2
        '400':
          description: Invalid id, or query parameters sent with the id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: The id is not a positive number
                  value:
                    status: 400
                    message: "Invalid milestone id"
                    data: {}
                query_params_with_id:
                  summary: A query parameter was sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single milestone by id"
                    data: {}
        '401':
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        '404':
          description: No schema has this id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Milestone not found"
                data: {}
        '500':
          description: Server error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/payroll-history/{id}:
    get:
      operationId: getPaidPayroll
      tags:
        - Payroll
      summary: Get a paid pay stub
      description: |
        Returns one paid or marked-paid pay stub, looked up by its payroll id. Use the id the stub had while it was open (`payroll_id` in GET /v1/payroll-history, `id` in GET /v1/payroll, or `payroll_id` in GET /v1/users/{id}/earnings/items). The paid record's own `id` returns 404.

        **What happens:**

        - The stub comes back in `data.payrolls` as a one-item array, with the same fields as GET /v1/payroll-history.
        - Only stubs that count as paid are returned: paid through your payroll provider, or marked as paid by an admin. A stub whose payment is still in flight or has failed returns 404.
        - If a payroll was processed more than once, Sequifi holds more than one paid record for it. This endpoint returns one of them and does not guarantee which. GET /v1/payroll-history/{id}/line-items always reads the newest one.

        **Formats:**

        - `pay_period_from`, `pay_period_to` and `pay_date` are timestamps at midnight UTC, for example `"2026-03-01T00:00:00.000Z"`. Use the date part.
        - Most money fields are JSON numbers. `employee_tax`, `employer_tax` and `total_earning` are decimal strings such as `"152.40"`, or null.
        - Custom field values are strings.

        **Errors:**

        - `400 Invalid payroll id`: the id is not a positive number.
        - `400 Cannot use query parameters when fetching a single payroll history record by id`: remove the query string.
        - `404 Payroll history record not found`: the stub is still open (try GET /v1/payroll/{id}), its payment is in flight or failed, or you passed the paid record's `id` instead of `payroll_id`.

        **Related:**

        - GET /v1/payroll-history lists paid stubs.
        - GET /v1/payroll-history/{id}/line-items itemizes this stub.
        - GET /v1/payroll/{id} reads a stub that is not paid yet.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The pay stub id (`payroll_id` in GET /v1/payroll-history). Not the paid record's `id`.
          schema:
            type: integer
            minimum: 1
          example: 5521
      responses:
        "200":
          description: The paid pay stub
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Always `1`.
                          per_page:
                            type: integer
                            description: Always `1`.
                          total:
                            type: integer
                            description: Always `1`.
                          last_page:
                            type: integer
                            description: Always `1`.
                          payrolls:
                            type: array
                            description: One paid pay stub. Rows also carry other stored fields not listed here; ignore them, they can change without notice.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Id of the paid record. Not the stub id; other endpoints do not accept it.
                                payroll_id:
                                  type: integer
                                  description: The pay stub id. Use it with this endpoint, its line items, and PATCH /v1/payroll-history.
                                user_id:
                                  type: integer
                                  description: The user who was paid.
                                first_name:
                                  type: string
                                  description: The user's first name.
                                last_name:
                                  type: string
                                  description: The user's last name.
                                pay_frequency:
                                  type: integer
                                  description: Pay frequency id. `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily.
                                worker_type:
                                  type: string
                                  description: "`1099` or `w2`."
                                pay_period_from:
                                  type: string
                                  description: Start of the pay period, midnight UTC timestamp.
                                pay_period_to:
                                  type: string
                                  description: End of the pay period, midnight UTC timestamp.
                                pay_date:
                                  type: string
                                  nullable: true
                                  description: Pay date when recorded, midnight UTC timestamp.
                                status:
                                  type: integer
                                  description: Always `3` (paid).
                                is_mark_paid:
                                  type: integer
                                  description: "`1` when an admin marked the stub as paid outside Sequifi (for example by check), so no money moved through your payroll provider. `0` otherwise."
                                is_onetime_payment:
                                  type: integer
                                  description: "`1` for a one-time payment, which is a separate stub from the regular one for the same period."
                                commission:
                                  type: number
                                  description: Commission total.
                                override:
                                  type: number
                                  description: Override total.
                                adjustment:
                                  type: number
                                  description: Adjustment total.
                                reimbursement:
                                  type: number
                                  description: Reimbursement total.
                                reimbursement_amount:
                                  type: number
                                  description: Same value as `reimbursement`.
                                deduction:
                                  type: number
                                  description: Deduction total.
                                clawback:
                                  type: number
                                  description: Clawback total.
                                reconciliation:
                                  type: number
                                  description: Reconciliation payout total.
                                hourly_salary:
                                  type: number
                                  description: Hourly and salary wages.
                                overtime:
                                  type: number
                                  description: Overtime wages.
                                custom_payment:
                                  type: number
                                  description: Custom payment amount.
                                manual_paid_amount:
                                  type: number
                                  description: Same value as `custom_payment`.
                                gross_pay:
                                  type: number
                                  description: Gross pay.
                                net_pay:
                                  type: number
                                  description: Net pay.
                                employee_tax:
                                  type: string
                                  nullable: true
                                  description: Employee taxes as a decimal string.
                                employer_tax:
                                  type: string
                                  nullable: true
                                  description: Employer taxes as a decimal string.
                                total_earning:
                                  type: string
                                  nullable: true
                                  description: Total earnings as a decimal string.
                                state_income_tax:
                                  type: number
                                  description: State income tax withheld (W-2 only). `0` when none.
                                federal_income_tax:
                                  type: number
                                  description: Federal income tax withheld (W-2 only). `0` when none.
                                quickbooks_journal_entry_id:
                                  type: string
                                  nullable: true
                                  description: QuickBooks journal entry id saved with PATCH /v1/payroll-history, or null.
                                custom_field:
                                  type: array
                                  description: Present only when the stub has custom payroll field values. A one-item array holding an object that maps each field name to its value (a string). A field whose definition was removed is keyed by its numeric id.
                                  items:
                                    type: object
                                    additionalProperties:
                                      type: string
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 1
                  total: 1
                  last_page: 1
                  payrolls:
                    - id: 9014
                      payroll_id: 5521
                      user_id: 4821
                      first_name: "Alex"
                      last_name: "Morgan"
                      pay_frequency: 2
                      worker_type: "w2"
                      pay_period_from: "2026-03-01T00:00:00.000Z"
                      pay_period_to: "2026-03-07T00:00:00.000Z"
                      pay_date: "2026-03-13T00:00:00.000Z"
                      status: 3
                      is_mark_paid: 0
                      is_onetime_payment: 0
                      commission: 1250
                      override: 150
                      adjustment: 0
                      reimbursement: 40
                      reimbursement_amount: 40
                      deduction: 0
                      clawback: 0
                      reconciliation: 0
                      hourly_salary: 560
                      overtime: 0
                      custom_payment: 0
                      manual_paid_amount: 0
                      gross_pay: 2000
                      net_pay: 1712.5
                      employee_tax: "152.40"
                      employer_tax: "152.40"
                      total_earning: null
                      state_income_tax: 45
                      federal_income_tax: 90.1
                      quickbooks_journal_entry_id: "JE-1042"
                      custom_field:
                        - Sales Bonus: "100"
                          Fuel: "20"
        "400":
          description: Invalid id, or query parameters sent with the id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Id is not a positive number
                  value:
                    status: 400
                    message: "Invalid payroll id"
                    data: {}
                query_params_with_id:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single payroll history record by id"
                    data: {}
        "404":
          description: No paid stub with this payroll id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Payroll history record not found"
                data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/payroll-history/{id}/line-items:
    get:
      operationId: listPaidPayrollLineItems
      tags:
        - Payroll
      summary: List a paid stub's line items
      description: |
        Returns the rows that a paid pay stub's section totals were built from (which deal, which milestone, how much), so you can reconcile a paycheck line by line. Some rows are shown on the stub but not paid on it: sum only rows with `counts_toward_pay: true` to match the stub.

        **What happens:**

        - Reads the copy of each row that Sequifi saved when the payroll was processed, so figures do not change when live commissions are later recalculated. They will not match today's earning lines, by design.
        - If the payroll was processed more than once, the newest paid record is used.
        - Each row has a `category` matching a section of the stub: `commission`, `override`, `adjustment`, `reimbursement`, `additional_value` (custom payroll fields) or `deduction`.
        - A row with `counts_toward_pay: false` is on the stub but excluded from its totals. `excluded_reason` says why: `paid_externally`, `do_not_pay`, `marked_paid`, `next_payroll`, `one_time_payment` or `moved_to_reconciliation`. These rows are summed into `totals.excluded_total`, not into their category.
        - Wages, overtime, reconciliation and taxes are not itemized. They are totals on GET /v1/payroll-history.
        - Money held in the user's reserve never reaches a stub, so it is not here. See GET /v1/users/{id}/reserve.

        **Filtering and paging:**

        - `category` returns one section. `totals` respect `category` but always cover the whole stub, never only the current page.
        - `page` defaults to 1. `per_page` defaults to 50, maximum 500.
        - Rows are sorted by category, then sale id, then `source` and `id`.

        **Formats:**

        - Amounts are JSON numbers in dollars, rounded to cents, signed as they affect the check: clawbacks and deductions are negative.
        - `date` is the date the row was last updated (`YYYY-MM-DD`), not the date it was earned.
        - `customer_name` is the sale's customer on deal rows and the user's own name on other rows.
        - `product_code`, `milestone` and `customer_signoff` appear only on commission and override rows.
        - `(source, id)` is the unique row key; `id` alone repeats across sources. Treat `source` as an opaque label.
        - `pay_frequency` is the pay frequency id (`2` Weekly to `6` Daily).

        **Errors:**

        - `400 Invalid payroll id`, `400 Invalid category` (with `data.allowed_categories`), `400 page must be a positive integer`, `400 per_page must be an integer between 1 and 500`, and `400 Invalid query parameter(s)` for any other query key.
        - `404 Payroll history record not found`: the stub is not paid, its payment is in flight or failed, or the id is the paid record's `id` rather than `payroll_id`.

        **Related:**

        - GET /v1/payroll-history/{id} returns the stub's totals.
        - GET /v1/payroll/{id}/line-items is the same view for a stub that is not paid yet.
        - GET /v1/users/{id}/earnings/items lists a user's earning lines with their `payroll_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The pay stub id (`payroll_id` in GET /v1/payroll-history).
          schema:
            type: integer
            minimum: 1
          example: 5521
        - name: category
          in: query
          required: false
          description: Return only one section of the stub. Omit for every row.
          schema:
            type: string
            enum: [commission, override, adjustment, reimbursement, additional_value, deduction]
          example: commission
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page.
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 50
      responses:
        "200":
          description: Line items for the paid pay stub
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          payroll_id:
                            type: integer
                            description: The pay stub id.
                          user:
                            type: object
                            description: The user on the stub.
                            properties:
                              id:
                                type: integer
                                description: User id.
                              employee_id:
                                type: string
                                nullable: true
                                description: Employee id shown in Sequifi.
                              first_name:
                                type: string
                                description: First name.
                              last_name:
                                type: string
                                description: Last name.
                              position_id:
                                type: integer
                                nullable: true
                                description: The user's current position id.
                              position_name:
                                type: string
                                nullable: true
                                description: The user's current position name.
                              worker_type:
                                type: string
                                description: "Worker type on the stub: `1099` or `w2`."
                          pay_period_from:
                            type: string
                            format: date
                            description: Start of the pay period, `YYYY-MM-DD`.
                          pay_period_to:
                            type: string
                            format: date
                            description: End of the pay period, `YYYY-MM-DD`.
                          pay_frequency:
                            type: integer
                            description: Pay frequency id.
                          is_history:
                            type: boolean
                            description: Always `true` on this endpoint.
                          totals:
                            type: object
                            description: Sums over the whole stub (after any `category` filter), never only this page.
                            properties:
                              commission:
                                type: number
                                description: Counted commission rows.
                              override:
                                type: number
                                description: Counted override rows.
                              adjustment:
                                type: number
                                description: Counted adjustment rows.
                              reimbursement:
                                type: number
                                description: Counted reimbursement rows.
                              additional_value:
                                type: number
                                description: Counted custom payroll field rows.
                              deduction:
                                type: number
                                description: Counted deduction rows (negative).
                              line_items_total:
                                type: number
                                description: Sum of every row with `counts_toward_pay` true.
                              excluded_total:
                                type: number
                                description: Sum of every row with `counts_toward_pay` false.
                          filters:
                            type: object
                            nullable: true
                            description: "`{category}` when filtered, otherwise null."
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page.
                          total:
                            type: integer
                            description: Rows across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          line_items:
                            type: array
                            description: The rows on this page.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Row id. Unique only together with `source`.
                                source:
                                  type: string
                                  description: Opaque label for the kind of record. Use with `id` as the row key.
                                category:
                                  type: string
                                  enum: [commission, override, adjustment, reimbursement, additional_value, deduction]
                                  description: Section of the stub.
                                type:
                                  type: string
                                  description: Label shown on the stub, for example `Commission`, `Clawback`, an override kind, an adjustment type or a deduction name.
                                pid:
                                  type: string
                                  nullable: true
                                  description: Sale id on deal rows, otherwise null.
                                customer_name:
                                  type: string
                                  nullable: true
                                  description: Sale customer on deal rows, the user's name on other rows.
                                product_code:
                                  type: string
                                  nullable: true
                                  description: Product code. Commission and override rows only.
                                milestone:
                                  type: string
                                  nullable: true
                                  description: Milestone name. Commission and override rows only.
                                customer_signoff:
                                  type: string
                                  nullable: true
                                  description: Sale date, `YYYY-MM-DD`. Commission and override rows only.
                                amount:
                                  type: number
                                  description: Dollars as they affect the check. Clawbacks and deductions are negative.
                                date:
                                  type: string
                                  nullable: true
                                  description: Date the row was last updated, `YYYY-MM-DD`.
                                description:
                                  type: string
                                  nullable: true
                                  description: Free text from the row, if any.
                                counts_toward_pay:
                                  type: boolean
                                  description: "`false` when the row is shown on the stub but not paid on it."
                                excluded_reason:
                                  type: string
                                  nullable: true
                                  enum: [paid_externally, do_not_pay, marked_paid, next_payroll, one_time_payment, moved_to_reconciliation, null]
                                  description: Why the row does not count, or null when it does.
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  payroll_id: 5521
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 14
                    position_name: "Sales Rep"
                    worker_type: "1099"
                  pay_period_from: "2026-07-26"
                  pay_period_to: "2026-08-01"
                  pay_frequency: 2
                  is_history: true
                  totals:
                    commission: 1250.00
                    override: 0.00
                    adjustment: 0.00
                    reimbursement: 0.00
                    additional_value: 0.00
                    deduction: 0.00
                    line_items_total: 1250.00
                    excluded_total: -300.00
                  filters: null
                  current_page: 1
                  per_page: 50
                  total: 2
                  last_page: 1
                  line_items:
                    - id: 70114
                      source: "user_commission_lock"
                      category: "commission"
                      type: "Commission"
                      pid: "SALE-10482"
                      customer_name: "Riley Chen"
                      product_code: "SOLAR"
                      milestone: "Install Complete"
                      customer_signoff: "2026-06-29"
                      amount: 1250.00
                      date: "2026-08-01"
                      description: null
                      counts_toward_pay: true
                      excluded_reason: null
                    - id: 3307
                      source: "approvals_and_requests_lock"
                      category: "adjustment"
                      type: "Advance"
                      pid: null
                      customer_name: "Alex Morgan"
                      amount: -300.00
                      date: "2026-07-30"
                      description: "Advance repayment"
                      counts_toward_pay: false
                      excluded_reason: "paid_externally"
        "400":
          description: Invalid payroll id, category, paging value or query parameter
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["pay_period_from"]
                      allowed_params: ["category", "page", "per_page"]
                invalid_category:
                  summary: Unknown category
                  value:
                    status: 400
                    message: "Invalid category"
                    data:
                      allowed_categories: ["commission", "override", "adjustment", "reimbursement", "additional_value", "deduction"]
                bad_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "per_page must be an integer between 1 and 500"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: No paid stub with this payroll id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Payroll history record not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/payroll/{id}:
    get:
      operationId: getPayroll
      tags:
        - Payroll
      summary: Get an open pay stub
      description: |
        Returns one pay stub that has not been paid yet, by its id. When a stub is paid it moves to payroll history and this endpoint returns 404 for it; read it with GET /v1/payroll-history/{id} using the same id.

        **What happens:**

        - The stub comes back in `data.payrolls` as a one-item array, with the same fields as GET /v1/payroll. There is no `filters` key.
        - Figures can still change until the payroll is paid.

        **Formats:**

        - `pay_period_from` and `pay_period_to` are timestamps at midnight UTC, for example `"2026-03-01T00:00:00.000Z"`. Use the date part.
        - Most money fields are JSON numbers. `employee_tax`, `employer_tax` and `total_earning` are decimal strings such as `"152.40"`, or null.

        **Errors:**

        - `400 Invalid payroll id`: the id is not a positive number. Trailing characters are ignored, so `12abc` is read as `12`; send digits only.
        - `400 Cannot use query parameters when fetching a single payroll by id`: remove the query string.
        - `404 Payroll not found`: usually the stub was paid. Retry with GET /v1/payroll-history/{id}.

        **Related:**

        - GET /v1/payroll lists open stubs.
        - GET /v1/payroll/{id}/line-items itemizes this stub.
        - GET /v1/payroll-history/{id} reads the stub after it is paid.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The pay stub id (`id` in GET /v1/payroll).
          schema:
            type: integer
            minimum: 1
          example: 5521
      responses:
        '200':
          description: The open pay stub
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Always `1`.
                          per_page:
                            type: integer
                            description: Always `1`.
                          total:
                            type: integer
                            description: Always `1`.
                          last_page:
                            type: integer
                            description: Always `1`.
                          payrolls:
                            type: array
                            description: One open pay stub. Rows also carry other stored fields not listed here; ignore them, they can change without notice.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: The pay stub id. It stays the same after the stub is paid.
                                user_id:
                                  type: integer
                                  description: The user being paid.
                                position_id:
                                  type: integer
                                  nullable: true
                                  description: The user's position for this pay run.
                                pay_frequency:
                                  type: integer
                                  description: Pay frequency id. `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily.
                                worker_type:
                                  type: string
                                  description: "`1099` or `w2`."
                                pay_period_from:
                                  type: string
                                  description: Start of the pay period, midnight UTC timestamp.
                                pay_period_to:
                                  type: string
                                  description: End of the pay period, midnight UTC timestamp.
                                status:
                                  type: integer
                                  enum: [1, 2, 3]
                                  description: "`1` open (editable), `2` finalized (ready to pay), `3` payment in progress."
                                is_mark_paid:
                                  type: integer
                                  description: "`1` when an admin marked the stub as paid outside Sequifi, otherwise `0`."
                                is_onetime_payment:
                                  type: integer
                                  description: "`1` for a one-time payment, which is a separate stub from the regular one for the same period."
                                commission:
                                  type: number
                                  description: Commission total.
                                override:
                                  type: number
                                  description: Override total.
                                adjustment:
                                  type: number
                                  description: Adjustment total.
                                reimbursement:
                                  type: number
                                  description: Reimbursement total.
                                deduction:
                                  type: number
                                  description: Deduction total.
                                clawback:
                                  type: number
                                  description: Clawback total.
                                reconciliation:
                                  type: number
                                  description: Reconciliation payout total.
                                hourly_salary:
                                  type: number
                                  description: Hourly and salary wages.
                                overtime:
                                  type: number
                                  description: Overtime wages.
                                custom_payment:
                                  type: number
                                  description: Custom payment amount.
                                gross_pay:
                                  type: number
                                  description: Gross pay.
                                net_pay:
                                  type: number
                                  description: Net pay. Not final until the payroll is finalized.
                                employee_tax:
                                  type: string
                                  nullable: true
                                  description: Employee taxes as a decimal string.
                                employer_tax:
                                  type: string
                                  nullable: true
                                  description: Employer taxes as a decimal string.
                                total_earning:
                                  type: string
                                  nullable: true
                                  description: Total earnings as a decimal string.
                                created_at:
                                  type: string
                                  description: When the stub was created, ISO 8601 UTC.
                                updated_at:
                                  type: string
                                  description: When the stub last changed, ISO 8601 UTC.
                                custom_field:
                                  type: array
                                  description: Present only when the stub has custom payroll field values. A one-item array holding an object that maps each field name to its value (a string). A field whose definition was removed is keyed by its numeric id.
                                  items:
                                    type: object
                                    additionalProperties:
                                      type: string
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 1
                  total: 1
                  last_page: 1
                  payrolls:
                    - id: 5521
                      user_id: 4821
                      position_id: 14
                      pay_frequency: 2
                      worker_type: "w2"
                      pay_period_from: "2026-03-01T00:00:00.000Z"
                      pay_period_to: "2026-03-07T00:00:00.000Z"
                      status: 1
                      is_mark_paid: 0
                      is_onetime_payment: 0
                      commission: 1250
                      override: 150
                      adjustment: 0
                      reimbursement: 40
                      deduction: 0
                      clawback: 0
                      reconciliation: 0
                      hourly_salary: 560
                      overtime: 0
                      custom_payment: 0
                      gross_pay: 2000
                      net_pay: 1712.5
                      employee_tax: "152.40"
                      employer_tax: "152.40"
                      total_earning: null
                      created_at: "2026-03-08T14:02:11.000Z"
                      updated_at: "2026-03-08T14:02:11.000Z"
                      custom_field:
                        - Sales Bonus: "100"
        '400':
          description: Invalid id, or query parameters sent with the id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                query_params_with_id:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single payroll by id"
                    data: {}
                invalid_id:
                  summary: Id is not a positive number
                  value:
                    status: 400
                    message: "Invalid payroll id"
                    data: {}
        '404':
          description: No open stub with this id. It may have been paid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Payroll not found"
                data: {}
        '401':
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/payroll/{id}/line-items:
    get:
      operationId: listPayrollLineItems
      tags:
        - Payroll
      summary: List an open stub's line items
      description: |
        Returns the rows that an open pay stub's section totals are built from (which deal, which milestone, how much). Some rows are shown on the stub but not paid on it: sum only rows with `counts_toward_pay: true` to match the stub.

        **What happens:**

        - Reads the live earning records, so figures move while the payroll is being built. A stub that is finalized but not yet paid is still read live and can drift from what was finalized.
        - Each row has a `category` matching a section of the stub: `commission`, `override`, `adjustment`, `reimbursement`, `additional_value` (custom payroll fields) or `deduction`.
        - A row with `counts_toward_pay: false` is on the stub but excluded from its totals. `excluded_reason` says why: `paid_externally`, `do_not_pay`, `marked_paid`, `next_payroll`, `one_time_payment` or `moved_to_reconciliation`. These rows are summed into `totals.excluded_total`, not into their category.
        - Wages, overtime, reconciliation and taxes are not itemized. They are totals on GET /v1/payroll.
        - Money diverted into the user's reserve never reaches a stub, so it is not here. See GET /v1/users/{id}/reserve.

        **Filtering and paging:**

        - `category` returns one section. `totals` respect `category` but always cover the whole stub, never only the current page.
        - `page` defaults to 1. `per_page` defaults to 50, maximum 500.
        - Rows are sorted by category, then sale id, then `source` and `id`.

        **Formats:**

        - Amounts are JSON numbers in dollars, rounded to cents, signed as they affect the check: clawbacks and deductions are negative.
        - `date` is the date the row was last updated (`YYYY-MM-DD`), not the date it was earned.
        - `customer_name` is the sale's customer on deal rows and the user's own name on other rows.
        - `product_code`, `milestone` and `customer_signoff` appear only on commission and override rows.
        - `(source, id)` is the unique row key; `id` alone repeats across sources. Treat `source` as an opaque label.
        - `pay_frequency` is the pay frequency id (`2` Weekly to `6` Daily).

        **Errors:**

        - `400 Invalid payroll id`, `400 Invalid category` (with `data.allowed_categories`), `400 page must be a positive integer`, `400 per_page must be an integer between 1 and 500`, and `400 Invalid query parameter(s)` for any other query key.
        - `404 Payroll record not found`: usually the stub was paid. Use GET /v1/payroll-history/{id}/line-items with the same id.

        **Related:**

        - GET /v1/payroll/{id} returns the stub's totals.
        - GET /v1/payroll-history/{id}/line-items is the same view after the stub is paid.
        - GET /v1/users/{id}/earnings/items lists a user's earning lines with their `payroll_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The open pay stub id (`id` in GET /v1/payroll).
          schema:
            type: integer
            minimum: 1
          example: 5521
        - name: category
          in: query
          required: false
          description: Return only one section of the stub. Omit for every row.
          schema:
            type: string
            enum: [commission, override, adjustment, reimbursement, additional_value, deduction]
          example: commission
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page.
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 50
      responses:
        "200":
          description: Line items for the open pay stub
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          payroll_id:
                            type: integer
                            description: The pay stub id.
                          user:
                            type: object
                            description: The user on the stub.
                            properties:
                              id:
                                type: integer
                                description: User id.
                              employee_id:
                                type: string
                                nullable: true
                                description: Employee id shown in Sequifi.
                              first_name:
                                type: string
                                description: First name.
                              last_name:
                                type: string
                                description: Last name.
                              position_id:
                                type: integer
                                nullable: true
                                description: The user's current position id.
                              position_name:
                                type: string
                                nullable: true
                                description: The user's current position name.
                              worker_type:
                                type: string
                                description: "Worker type on the stub: `1099` or `w2`."
                          pay_period_from:
                            type: string
                            format: date
                            description: Start of the pay period, `YYYY-MM-DD`.
                          pay_period_to:
                            type: string
                            format: date
                            description: End of the pay period, `YYYY-MM-DD`.
                          pay_frequency:
                            type: integer
                            description: Pay frequency id.
                          is_history:
                            type: boolean
                            description: Always `false` on this endpoint.
                          totals:
                            type: object
                            description: Sums over the whole stub (after any `category` filter), never only this page.
                            properties:
                              commission:
                                type: number
                                description: Counted commission rows.
                              override:
                                type: number
                                description: Counted override rows.
                              adjustment:
                                type: number
                                description: Counted adjustment rows.
                              reimbursement:
                                type: number
                                description: Counted reimbursement rows.
                              additional_value:
                                type: number
                                description: Counted custom payroll field rows.
                              deduction:
                                type: number
                                description: Counted deduction rows (negative).
                              line_items_total:
                                type: number
                                description: Sum of every row with `counts_toward_pay` true.
                              excluded_total:
                                type: number
                                description: Sum of every row with `counts_toward_pay` false.
                          filters:
                            type: object
                            nullable: true
                            description: "`{category}` when filtered, otherwise null."
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page.
                          total:
                            type: integer
                            description: Rows across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          line_items:
                            type: array
                            description: The rows on this page.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Row id. Unique only together with `source`.
                                source:
                                  type: string
                                  description: Opaque label for the kind of record. Use with `id` as the row key.
                                category:
                                  type: string
                                  enum: [commission, override, adjustment, reimbursement, additional_value, deduction]
                                  description: Section of the stub.
                                type:
                                  type: string
                                  description: Label shown on the stub, for example `Commission`, `Clawback`, an override kind, an adjustment type or a deduction name.
                                pid:
                                  type: string
                                  nullable: true
                                  description: Sale id on deal rows, otherwise null.
                                customer_name:
                                  type: string
                                  nullable: true
                                  description: Sale customer on deal rows, the user's name on other rows.
                                product_code:
                                  type: string
                                  nullable: true
                                  description: Product code. Commission and override rows only.
                                milestone:
                                  type: string
                                  nullable: true
                                  description: Milestone name. Commission and override rows only.
                                customer_signoff:
                                  type: string
                                  nullable: true
                                  description: Sale date, `YYYY-MM-DD`. Commission and override rows only.
                                amount:
                                  type: number
                                  description: Dollars as they affect the check. Clawbacks and deductions are negative.
                                date:
                                  type: string
                                  nullable: true
                                  description: Date the row was last updated, `YYYY-MM-DD`.
                                description:
                                  type: string
                                  nullable: true
                                  description: Free text from the row, if any.
                                counts_toward_pay:
                                  type: boolean
                                  description: "`false` when the row is shown on the stub but not paid on it."
                                excluded_reason:
                                  type: string
                                  nullable: true
                                  enum: [paid_externally, do_not_pay, marked_paid, next_payroll, one_time_payment, moved_to_reconciliation, null]
                                  description: Why the row does not count, or null when it does.
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  payroll_id: 5521
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 14
                    position_name: "Sales Rep"
                    worker_type: "1099"
                  pay_period_from: "2026-07-26"
                  pay_period_to: "2026-08-01"
                  pay_frequency: 2
                  is_history: false
                  totals:
                    commission: 1250.00
                    override: 0.00
                    adjustment: 0.00
                    reimbursement: 0.00
                    additional_value: 0.00
                    deduction: 0.00
                    line_items_total: 1250.00
                    excluded_total: -300.00
                  filters: null
                  current_page: 1
                  per_page: 50
                  total: 2
                  last_page: 1
                  line_items:
                    - id: 70114
                      source: "user_commission"
                      category: "commission"
                      type: "Commission"
                      pid: "SALE-10482"
                      customer_name: "Riley Chen"
                      product_code: "SOLAR"
                      milestone: "Install Complete"
                      customer_signoff: "2026-06-29"
                      amount: 1250.00
                      date: "2026-08-01"
                      description: null
                      counts_toward_pay: true
                      excluded_reason: null
                    - id: 3307
                      source: "approvals_and_requests"
                      category: "adjustment"
                      type: "Advance"
                      pid: null
                      customer_name: "Alex Morgan"
                      amount: -300.00
                      date: "2026-07-30"
                      description: "Advance repayment"
                      counts_toward_pay: false
                      excluded_reason: "paid_externally"
        "400":
          description: Invalid payroll id, category, paging value or query parameter
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["pay_period_from"]
                      allowed_params: ["category", "page", "per_page"]
                invalid_category:
                  summary: Unknown category
                  value:
                    status: 400
                    message: "Invalid category"
                    data:
                      allowed_categories: ["commission", "override", "adjustment", "reimbursement", "additional_value", "deduction"]
                bad_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "per_page must be an integer between 1 and 500"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: No open stub with this id. It may have been paid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Payroll record not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/payroll:
    post:
      operationId: upsertPayroll
      tags:
        - Payroll
      summary: Set payroll amounts
      description: >-
        Writes commission, override and salary amounts onto each user's open pay stub for one pay period,
        creating the stub if the user does not have one yet. Up to 10 users per request. Only for
        companies on SequiPay payroll. It stores the amounts you send; it does not calculate pay, taxes or
        net pay, and it does not run, finalize or pay the payroll.
      
      
        **Before you call:**
      
      
        - Your company must run payroll in SequiPay. Otherwise every call returns `400 Sequipay payroll is
        not enabled for this company`.
      
        - Get the exact pay frequency name from GET /v1/pay-frequency (for example `Weekly`). Ids are not
        accepted.
      
        - Get user ids and each user's worker type (`1099` or `w2`) from GET /v1/users. One request covers
        one worker type, and every user in it must have that worker type.
      
        - Each user needs a position on or before `pay_period_to` (set by onboarding or a position
        change). Users without one are skipped.
      
        - Custom field names must match your company's payroll custom fields exactly: GET
        /v1/custom-fields?type=payroll.
      
      
        **What happens:**
      
      
        - The whole request is checked first. A problem here rejects everything with `400`: missing or
        badly formatted fields, more than 10 users, a repeated `user_id`, an unknown pay frequency, a
        worker type your company does not use, a period that is already finalized, or a period that starts
        on or before the end of the last finalized period for that worker type and pay frequency.
      
        - Then each user is handled on their own, in their own transaction. A user who fails is listed in
        `data.results[]` with `status: false` and a message; the others still go through.
      
        - If the user already has a stub for exactly this period, pay frequency and worker type, its
        `commission`, `override` and salary (`hourly_salary`) are replaced with the values you send.
      
        - If not, a new open stub is created with your amounts, the user's position as of `pay_period_to`,
        and every other amount (net pay, taxes, deductions, reimbursements, adjustments) at `0`.
      
        - Custom fields you send are created or replaced on the stub. Custom fields you leave out are not
        changed.
      
        - Nothing checks that the period matches your company's pay calendar; you choose the dates.
      
      
        **Idempotency and retries:**
      
      
        - Amounts are absolute, not added: sending the same request twice leaves the same values, so a
        retry never doubles pay.
      
        - A retry after a timeout is safe. Users that already went through are updated with the same
        values.
      
      
        **Formats:**
      
      
        - Dates are `YYYY-MM-DD`, and `pay_period_to` must be after `pay_period_from`. Send real calendar
        dates: the format check accepts an impossible date such as `2026-02-30`, which then fails for that
        user or misbehaves.
      
        - Amounts are dollars. `commission_amount` and `override_amount` are required and must be 0 or
        more. `salary` is optional; a missing, negative or non-numeric `salary` is stored as `0` without
        an error.
      
        - `worker_type` is case-insensitive (`W2` works). `user_id` may be a number or a string of digits.
      
      
        **Errors:**
      
      
        - `400` for the request-level problems above, with details in `data` (see the examples). The
        "after the last finalized payroll period" message prints that date in a long format, for example
        `Sat Feb 14 2026 00:00:00 GMT+0000 (Coordinated Universal Time)`.
      
        - `200` with `status: false` per user for: user not found, a different worker type, no position on
        or before `pay_period_to`, a missing or negative amount, an unknown custom field name, or a
        database error ("Failed to process payroll."). A `200` can mean every user failed: check every
        result.
      
        - `401` `{"message":"Unauthorized"}` for a missing or invalid token.
      
      
        **Common mistakes:**
      
      
        - Sending a pay frequency id (`2`) instead of its name (`Weekly`).
      
        - Mixing 1099 and W-2 users in one request. Send one request per worker type.
      
        - Expecting net pay: this endpoint writes gross commission, override and salary amounts only.
      
      
        **Related:**
      
      
        - GET /v1/payroll lists open stubs for a period, so you can confirm what was written; GET
        /v1/payroll/{id}/line-items itemises one.
      
        - GET /v1/pay-frequency, GET /v1/users and GET /v1/custom-fields?type=payroll give the values this
        endpoint needs.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - pay_period_from
                - pay_period_to
                - pay_frequency
                - worker_type
                - users
              properties:
                pay_period_from:
                  type: string
                  format: date
                  description: Start of the pay period. Format `YYYY-MM-DD`. Send a real calendar date, because impossible dates such as 2026-02-30 still pass the format check.
                  example: "2026-02-20"
                pay_period_to:
                  type: string
                  format: date
                  description: End of the pay period. Format `YYYY-MM-DD`. Must be after `pay_period_from`.
                  example: "2026-02-28"
                pay_frequency:
                  type: string
                  description: >-
                    Pay frequency name as listed by GET /v1/pay-frequency, case-insensitive, for example
                    `Weekly` or `Bi-Weekly`.
                  example: WEEKLY
                worker_type:
                  type: string
                  enum:
                    - "1099"
                    - w2
                  description: >-
                    `1099` or `w2`, case-insensitive. Must be a worker type your company's positions use,
                    and every user in the request must have it.
                  example: "1099"
                users:
                  type: array
                  minItems: 1
                  maxItems: 10
                  description: Users to process. Maximum 10 per request.
                  items:
                    type: object
                    required:
                      - user_id
                      - commission_amount
                      - override_amount
                    properties:
                      user_id:
                        type: integer
                        description: User id from GET /v1/users. A number or a string of digits.
                        example: 778
                      commission_amount:
                        type: number
                        minimum: 0
                        description: Commission amount for this user. Must be non-negative.
                        example: 200
                      override_amount:
                        type: number
                        minimum: 0
                        description: Override amount for this user. Must be non-negative.
                        example: 200
                      salary:
                        type: number
                        minimum: 0
                        description: >-
                          Optional salary or wage amount, stored as `hourly_salary` on the stub. A
                          missing, negative or non-numeric value is stored as `0` without an error.
                        example: 100
                      custom_fields:
                        type: object
                        description: >-
                          Optional map of payroll custom field names (exactly as GET
                          /v1/custom-fields?type=payroll lists them) to values. Only the fields you send
                          are written.
                        additionalProperties:
                          type: string
                        example:
                          Sales Bonus: "100"
                          Expenses: "20"
            examples:
              two_users:
                summary: Two users with salary and custom fields
                value:
                  pay_period_from: "2026-02-20"
                  pay_period_to: "2026-02-28"
                  pay_frequency: WEEKLY
                  worker_type: "1099"
                  users:
                    - user_id: 778
                      salary: 100
                      commission_amount: 200
                      override_amount: 200
                      custom_fields:
                        Sales Bonus: "100"
                        Expenses: "20"
                    - user_id: 779
                      commission_amount: 200
                      override_amount: 300
                      custom_fields:
                        Sales Bonus: "200"
                        Expenses: "40"
      responses:
        "200":
          description: >-
            The request was accepted. Each user has its own result in `data.results[]`; check every one,
            because all of them can fail.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ApiResponse"
              examples:
                success:
                  summary: Both users processed successfully
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: acme
                      results:
                        - user_id: 778
                          status: true
                          message: Payroll created successfully.
                        - user_id: 779
                          status: true
                          message: Payroll updated successfully.
                partial_failure:
                  summary: One user failed (per-user error)
                  value:
                    status: 200
                    message: success
                    data:
                      requested_by: acme
                      results:
                        - user_id: 778
                          status: true
                          message: Payroll created successfully.
                        - user_id: 779
                          status: false
                          message: User 779 not found.
                        - user_id: 780
                          status: false
                          message: User 780 does not belong to worker_type "1099". User's worker_type is "w2".
                        - user_id: 781
                          status: false
                          message: >-
                            No organization history found for user_id 781 with effective_date <=
                            2026-02-28
        "400":
          description: Validation error (request-level)
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ApiResponse"
              examples:
                missing_fields:
                  summary: Required fields missing
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      pay_period_from: "Required. Format: YYYY-MM-DD"
                      pay_frequency: Required.
                invalid_date:
                  summary: Invalid calendar date
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      pay_period_to: "Required. Format: YYYY-MM-DD"
                invalid_worker_type:
                  summary: Invalid worker_type
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      worker_type: "Required. Allowed values: 1099, w2"
                too_many_users:
                  summary: Exceeds 10-user limit
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      users: Too many users. Maximum allowed is 10 per request.
                duplicate_user_ids:
                  summary: Duplicate user_id in request
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      message: Duplicate user_id(s) found in users array. Each user_id must be unique.
                      duplicate_ids:
                        - 778
                finalized:
                  summary: Pay period already finalized
                  value:
                    status: 400
                    message: Payroll has been finalized. No changes can be made after finalization.
                    data: {}
                period_before_last_finalized:
                  summary: New period before last finalized
                  value:
                    status: 400
                    message: >-
                      New payroll period must be after the last finalized payroll period (pay_period_to:
                      Sat Feb 14 2026 00:00:00 GMT+0000 (Coordinated Universal Time)).
                    data: {}
                sequipay_not_enabled:
                  summary: SequiPay not enabled
                  value:
                    status: 400
                    message: Sequipay payroll is not enabled for this company
                    data: {}
                invalid_pay_frequency:
                  summary: Pay frequency name not found (ids are not accepted)
                  value:
                    status: 400
                    message: Invalid pay_frequency
                    data:
                      provided: "2"
                      allowed_values:
                        - WEEKLY
                        - BI-WEEKLY
                        - SEMI-MONTHLY
                        - MONTHLY
                worker_type_not_used:
                  summary: Worker type not used by any of the company's positions
                  value:
                    status: 400
                    message: Validation Failed
                    data:
                      worker_type: "worker_type \"w2\" is not supported for this company. Allowed worker types: 1099"
        "401":
          description: >-
            Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so
            the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: Unauthorized
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ApiResponse"
              example:
                status: 500
                message: Internal Server Error
                data: {}
    get:
      operationId: listPayroll
      tags:
        - Payroll
      summary: List open pay stubs
      description: |
        Lists pay stubs that have not been paid yet, one row per user per pay run, newest first. Paid stubs move to GET /v1/payroll-history and drop out of this list. There is no `user_id` filter.

        **What happens:**

        - Read-only.
        - A one-time payment is a separate row (`is_onetime_payment: 1`) next to the user's regular stub for the same period.
        - Each row can carry `custom_field`, the stub's custom payroll field values.

        **Filtering and paging:**

        - Filters are optional and combine with AND.
        - `pay_period_from` and `pay_period_to` return stubs whose whole period falls inside the range: the period starts on or after `pay_period_from` and ends on or before `pay_period_to`. A period that crosses either boundary is left out.
        - `pay_frequency` takes a pay frequency id: `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily.
        - `status`: `1` open, `2` finalized, `3` payment in progress. Paid stubs are not in this list, so `status=3` returns few or no rows.
        - `is_mark_paid`: `true` for stubs an admin marked as paid outside Sequifi, `false` for the rest.
        - `worker_type` is an exact match (`1099` or `w2`). Other values are not rejected; they match nothing.
        - `page` defaults to 1 and `per_page` to 10. No maximum is enforced on `per_page`; keep it at 200 or less.
        - Sorted by stub `id`, newest first. `last_page` is `0` when nothing matches.
        - To find one user's stub, filter by pay period and match `user_id` yourself, or take `payroll_id` from GET /v1/users/{id}/earnings/items.

        **Formats:**

        - `pay_period_from` and `pay_period_to` are timestamps at midnight UTC, for example `"2026-03-01T00:00:00.000Z"`. Use the date part.
        - Most money fields are JSON numbers. `employee_tax`, `employer_tax` and `total_earning` are decimal strings such as `"152.40"`, or null.
        - `filters` echoes the query values as strings.

        **Errors:**

        - `400 Invalid query parameter(s)` for an unknown query key, with `data.invalid_params` and `data.allowed_params`.
        - `400 is_mark_paid must be 'true' or 'false'`.
        - `400 pay_period_from must be in YYYY-MM-DD format` (or `pay_period_to`): the value must be a real calendar date.
        - A non-numeric `page`, `per_page`, `status` or `pay_frequency` returns `500`, not `400`. Validate these before sending and do not retry a `500` with the same values.

        **Related:**

        - GET /v1/payroll/{id} and GET /v1/payroll/{id}/line-items read one stub.
        - GET /v1/payroll-history lists paid stubs.
        - GET /v1/pay-frequency maps frequency ids to names.
      security:
        - bearerAuth: []
      parameters:
        - name: pay_frequency
          in: query
          required: false
          description: "Pay frequency id: `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily."
          schema:
            type: integer
            enum: [2, 3, 4, 5, 6]
          example: 2
        - name: status
          in: query
          required: false
          description: "`1` open (editable), `2` finalized (ready to pay), `3` payment in progress. Paid stubs are not in this list."
          schema:
            type: integer
            enum: [1, 2, 3]
          example: 1
        - name: is_mark_paid
          in: query
          required: false
          description: "`true` returns stubs an admin marked as paid outside Sequifi; `false` returns the rest. Omit for both."
          schema:
            type: string
            enum: ["false", "true"]
          example: "false"
        - name: worker_type
          in: query
          required: false
          description: "Exact match on worker type: `1099` or `w2`. Other values return no rows."
          schema:
            type: string
          example: "w2"
        - name: pay_period_from
          in: query
          required: false
          description: "Only stubs whose period starts on or after this date. Format `YYYY-MM-DD`."
          schema:
            type: string
            format: date
          example: "2026-03-01"
        - name: pay_period_to
          in: query
          required: false
          description: "Only stubs whose period ends on or before this date. Format `YYYY-MM-DD`."
          schema:
            type: string
            format: date
          example: "2026-03-07"
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page. No maximum is enforced; keep it at 200 or less.
          schema:
            type: integer
            minimum: 1
            default: 10
          example: 10
      responses:
        "200":
          description: A page of open pay stubs
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page.
                          total:
                            type: integer
                            description: Rows across all pages.
                          last_page:
                            type: integer
                            description: Last page number. `0` when nothing matches.
                          filters:
                            type: object
                            nullable: true
                            description: The filters you sent, as strings, or null when none.
                          payrolls:
                            type: array
                            description: Open pay stubs. Rows also carry other stored fields not listed here; ignore them, they can change without notice.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: The pay stub id. It stays the same after the stub is paid.
                                user_id:
                                  type: integer
                                  description: The user being paid.
                                position_id:
                                  type: integer
                                  nullable: true
                                  description: The user's position for this pay run.
                                pay_frequency:
                                  type: integer
                                  description: Pay frequency id.
                                worker_type:
                                  type: string
                                  description: "`1099` or `w2`."
                                pay_period_from:
                                  type: string
                                  description: Start of the pay period, midnight UTC timestamp.
                                pay_period_to:
                                  type: string
                                  description: End of the pay period, midnight UTC timestamp.
                                status:
                                  type: integer
                                  enum: [1, 2, 3]
                                  description: "`1` open, `2` finalized, `3` payment in progress."
                                is_mark_paid:
                                  type: integer
                                  description: "`1` when an admin marked the stub as paid outside Sequifi, otherwise `0`."
                                is_onetime_payment:
                                  type: integer
                                  description: "`1` for a one-time payment stub."
                                commission:
                                  type: number
                                  description: Commission total.
                                override:
                                  type: number
                                  description: Override total.
                                adjustment:
                                  type: number
                                  description: Adjustment total.
                                reimbursement:
                                  type: number
                                  description: Reimbursement total.
                                deduction:
                                  type: number
                                  description: Deduction total.
                                clawback:
                                  type: number
                                  description: Clawback total.
                                reconciliation:
                                  type: number
                                  description: Reconciliation payout total.
                                hourly_salary:
                                  type: number
                                  description: Hourly and salary wages.
                                overtime:
                                  type: number
                                  description: Overtime wages.
                                custom_payment:
                                  type: number
                                  description: Custom payment amount.
                                gross_pay:
                                  type: number
                                  description: Gross pay.
                                net_pay:
                                  type: number
                                  description: Net pay. Not final until the payroll is finalized.
                                employee_tax:
                                  type: string
                                  nullable: true
                                  description: Employee taxes as a decimal string.
                                employer_tax:
                                  type: string
                                  nullable: true
                                  description: Employer taxes as a decimal string.
                                total_earning:
                                  type: string
                                  nullable: true
                                  description: Total earnings as a decimal string.
                                created_at:
                                  type: string
                                  description: When the stub was created, ISO 8601 UTC.
                                updated_at:
                                  type: string
                                  description: When the stub last changed, ISO 8601 UTC.
                                custom_field:
                                  type: array
                                  description: Present only when the stub has custom payroll field values. A one-item array holding an object that maps each field name to its value (a string).
                                  items:
                                    type: object
                                    additionalProperties:
                                      type: string
              examples:
                with_filters:
                  summary: Filtered list with custom fields
                  value:
                    status: 200
                    message: "success"
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 2
                      last_page: 1
                      filters:
                        pay_frequency: "2"
                        worker_type: "w2"
                      payrolls:
                        - id: 5521
                          user_id: 4821
                          position_id: 14
                          pay_frequency: 2
                          worker_type: "w2"
                          pay_period_from: "2026-03-01T00:00:00.000Z"
                          pay_period_to: "2026-03-07T00:00:00.000Z"
                          status: 1
                          is_mark_paid: 0
                          is_onetime_payment: 0
                          commission: 1250
                          override: 150
                          adjustment: 0
                          reimbursement: 40
                          deduction: 0
                          clawback: 0
                          reconciliation: 0
                          hourly_salary: 560
                          overtime: 0
                          custom_payment: 0
                          gross_pay: 2000
                          net_pay: 1712.5
                          employee_tax: "152.40"
                          employer_tax: "152.40"
                          total_earning: null
                          created_at: "2026-03-08T14:02:11.000Z"
                          updated_at: "2026-03-08T14:02:11.000Z"
                          custom_field:
                            - Sales Bonus: "100"
                              Expenses: "20"
                        - id: 5520
                          user_id: 4822
                          position_id: 14
                          pay_frequency: 2
                          worker_type: "w2"
                          pay_period_from: "2026-03-01T00:00:00.000Z"
                          pay_period_to: "2026-03-07T00:00:00.000Z"
                          status: 1
                          is_mark_paid: 0
                          is_onetime_payment: 0
                          commission: 900
                          override: 0
                          adjustment: 0
                          reimbursement: 0
                          deduction: 0
                          clawback: 0
                          reconciliation: 0
                          hourly_salary: 600
                          overtime: 0
                          custom_payment: 0
                          gross_pay: 1500
                          net_pay: 1285.25
                          employee_tax: "114.75"
                          employer_tax: "114.75"
                          total_earning: null
                          created_at: "2026-03-08T14:02:11.000Z"
                          updated_at: "2026-03-08T14:02:11.000Z"
                no_filters:
                  summary: Unfiltered list (filters is null)
                  value:
                    status: 200
                    message: "success"
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 50
                      last_page: 5
                      filters: null
                      payrolls:
                        - id: 5530
                          user_id: 4830
                          position_id: 9
                          pay_frequency: 3
                          worker_type: "1099"
                          pay_period_from: "2026-03-01T00:00:00.000Z"
                          pay_period_to: "2026-03-14T00:00:00.000Z"
                          status: 1
                          is_mark_paid: 0
                          is_onetime_payment: 0
                          commission: 0
                          override: 0
                          adjustment: 0
                          reimbursement: 0
                          deduction: 0
                          clawback: 0
                          reconciliation: 0
                          hourly_salary: 0
                          overtime: 0
                          custom_payment: 0
                          gross_pay: 0
                          net_pay: 0
                          employee_tax: null
                          employer_tax: null
                          total_earning: null
                          created_at: "2026-03-15T09:30:00.000Z"
                          updated_at: "2026-03-15T09:30:00.000Z"
        "400":
          description: Unknown query parameter, bad is_mark_paid value, or bad date
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["user_id"]
                      allowed_params: ["pay_frequency", "status", "is_mark_paid", "worker_type", "pay_period_from", "pay_period_to", "page", "per_page"]
                bad_is_mark_paid:
                  summary: is_mark_paid is not true or false
                  value:
                    status: 400
                    message: "is_mark_paid must be 'true' or 'false'"
                    data: {}
                bad_date:
                  summary: Invalid date
                  value:
                    status: 400
                    message: "pay_period_from must be in YYYY-MM-DD format"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error, including a non-numeric page, per_page, status or pay_frequency
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/payroll-history:
    get:
      operationId: listPaidPayroll
      tags:
        - Payroll
      summary: List paid pay stubs
      description: |
        Lists paid and marked-paid pay stubs, mainly so an accounting sync can post them to the books. Results are not deduplicated: if a payroll was processed more than once, every paid record for it is returned, so key your sync on `payroll_id` and skip ids you have already posted.

        **What happens:**

        - A stub appears here once it is paid through your payroll provider or marked as paid by an admin. A stub whose payment is in flight or has failed is left out until it settles.
        - One-time payments, such as an approved bonus paid right away, are not listed here. Read them from GET /v1/one-time-payments. The exception is a one-time payment that paid a whole open payroll, which is listed here with `is_onetime_payment: 1`.
        - For some payroll providers a stub is listed as soon as payment is sent, before the provider confirms it.
        - `is_mark_paid` tells you how the stub was settled: `1` means an admin marked it paid outside Sequifi (for example by check) and no money moved through your payroll provider. Filter on `is_mark_paid` rather than inferring it from other fields.

        **Filtering and paging:**

        - `quickbooks_synced=false` returns stubs with no QuickBooks journal entry id and net pay above zero, oldest first. `quickbooks_synced=true` returns stubs that have one.
        - `is_mark_paid=true` or `false` splits marked-paid stubs from the rest. The two values together cover every stub.
        - `worker_type` is an exact match (`1099` or `w2`).
        - There is no date, user or pay frequency filter.
        - `page` defaults to 1. `per_page` defaults to 10; values above 200 are treated as 200.
        - Sorted by `payroll_id`, newest first, except `quickbooks_synced=false`, which sorts oldest first. `last_page` is at least `1`.
        - Saving journal ids while you page through `quickbooks_synced=false` shifts the pages. Start again from page 1 after each PATCH /v1/payroll-history.

        **Idempotency and retries:**

        - Use `payroll_id` (not `id`) as the key for each stub. Before creating a journal entry, check that `quickbooks_journal_entry_id` is null and that you have not already posted that `payroll_id`.

        **Formats:**

        - `id` is the paid record's own id. `payroll_id` is the stub id used everywhere else.
        - `pay_period_from`, `pay_period_to` and `pay_date` are timestamps at midnight UTC, for example `"2026-03-01T00:00:00.000Z"`. Use the date part.
        - Most money fields are JSON numbers. `employee_tax`, `employer_tax` and `total_earning` are decimal strings such as `"152.40"`, or null.
        - `reimbursement_amount` repeats `reimbursement`, and `manual_paid_amount` repeats `custom_payment`.

        **Errors:**

        - `400 Invalid query parameter(s)` for an unknown query key.
        - `400 quickbooks_synced must be 'true' or 'false'` and `400 is_mark_paid must be 'true' or 'false'`.
        - A non-numeric `page` or `per_page` returns `500`, not `400`.

        **Related:**

        - PATCH /v1/payroll-history saves journal entry ids.
        - GET /v1/payroll-history/{id} and its line items read one stub by `payroll_id`.
        - GET /v1/payroll lists stubs that are not paid yet.
        - GET /v1/one-time-payments lists paid one-time payments, which are not listed here.
      security:
        - bearerAuth: []
      parameters:
        - name: quickbooks_synced
          in: query
          required: false
          description: "`false` returns stubs with no QuickBooks journal entry id and net pay above zero, oldest first. `true` returns stubs that have one. Omit for all."
          schema:
            type: string
            enum: ["false", "true"]
          example: "false"
        - name: is_mark_paid
          in: query
          required: false
          description: "`true` returns stubs an admin marked as paid outside Sequifi; `false` returns stubs paid through your payroll provider. Omit for both."
          schema:
            type: string
            enum: ["false", "true"]
          example: "false"
        - name: worker_type
          in: query
          required: false
          description: "Exact match on worker type: `1099` or `w2`. Other values return no rows."
          schema:
            type: string
          example: "w2"
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page. Values above 200 are treated as 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 10
          example: 10
      responses:
        "200":
          description: A page of paid pay stubs
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page after the 200 cap.
                          total:
                            type: integer
                            description: Rows across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          filters:
                            type: object
                            nullable: true
                            description: The filters you sent, as strings, or null when none.
                          payrolls:
                            type: array
                            description: Paid pay stubs. Rows also carry other stored fields not listed here; ignore them, they can change without notice.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Id of the paid record. Not the stub id; other endpoints do not accept it.
                                payroll_id:
                                  type: integer
                                  description: The pay stub id. Use it as your sync key, with GET /v1/payroll-history/{id}, and in PATCH /v1/payroll-history.
                                user_id:
                                  type: integer
                                  description: The user who was paid.
                                first_name:
                                  type: string
                                  description: The user's first name.
                                last_name:
                                  type: string
                                  description: The user's last name.
                                pay_frequency:
                                  type: integer
                                  description: Pay frequency id. `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily.
                                worker_type:
                                  type: string
                                  description: "`1099` or `w2`."
                                pay_period_from:
                                  type: string
                                  description: Start of the pay period, midnight UTC timestamp.
                                pay_period_to:
                                  type: string
                                  description: End of the pay period, midnight UTC timestamp.
                                pay_date:
                                  type: string
                                  nullable: true
                                  description: Pay date when recorded, midnight UTC timestamp.
                                status:
                                  type: integer
                                  description: Always `3` (paid).
                                is_mark_paid:
                                  type: integer
                                  description: "`1` when an admin marked the stub as paid outside Sequifi, so no money moved through your payroll provider. `0` otherwise."
                                is_onetime_payment:
                                  type: integer
                                  description: "`1` for a one-time payment stub."
                                commission:
                                  type: number
                                  description: Commission total.
                                override:
                                  type: number
                                  description: Override total.
                                adjustment:
                                  type: number
                                  description: Adjustment total.
                                reimbursement:
                                  type: number
                                  description: Reimbursement total.
                                reimbursement_amount:
                                  type: number
                                  description: Same value as `reimbursement`.
                                deduction:
                                  type: number
                                  description: Deduction total.
                                clawback:
                                  type: number
                                  description: Clawback total.
                                reconciliation:
                                  type: number
                                  description: Reconciliation payout total.
                                hourly_salary:
                                  type: number
                                  description: Hourly and salary wages.
                                overtime:
                                  type: number
                                  description: Overtime wages.
                                custom_payment:
                                  type: number
                                  description: Custom payment amount.
                                manual_paid_amount:
                                  type: number
                                  description: Same value as `custom_payment`.
                                gross_pay:
                                  type: number
                                  description: Gross pay.
                                net_pay:
                                  type: number
                                  description: Net pay.
                                employee_tax:
                                  type: string
                                  nullable: true
                                  description: Employee taxes as a decimal string.
                                employer_tax:
                                  type: string
                                  nullable: true
                                  description: Employer taxes as a decimal string.
                                total_earning:
                                  type: string
                                  nullable: true
                                  description: Total earnings as a decimal string.
                                state_income_tax:
                                  type: number
                                  description: State income tax withheld (W-2 only). `0` when none.
                                federal_income_tax:
                                  type: number
                                  description: Federal income tax withheld (W-2 only). `0` when none.
                                quickbooks_journal_entry_id:
                                  type: string
                                  nullable: true
                                  description: QuickBooks journal entry id saved with PATCH /v1/payroll-history, or null.
                                custom_field:
                                  type: array
                                  description: Present only when the stub has custom payroll field values. A one-item array holding an object that maps each field name to its value (a string).
                                  items:
                                    type: object
                                    additionalProperties:
                                      type: string
              examples:
                unsynced:
                  summary: "quickbooks_synced=false: paid, not yet in QuickBooks (oldest first)"
                  value:
                    status: 200
                    message: "success"
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 1
                      last_page: 1
                      filters:
                        quickbooks_synced: "false"
                      payrolls:
                        - id: 9014
                          payroll_id: 5521
                          user_id: 4821
                          first_name: "Alex"
                          last_name: "Morgan"
                          pay_frequency: 2
                          worker_type: "w2"
                          pay_period_from: "2026-03-01T00:00:00.000Z"
                          pay_period_to: "2026-03-07T00:00:00.000Z"
                          pay_date: "2026-03-13T00:00:00.000Z"
                          status: 3
                          is_mark_paid: 0
                          is_onetime_payment: 0
                          commission: 1250
                          override: 150
                          adjustment: 0
                          reimbursement: 40
                          reimbursement_amount: 40
                          deduction: 0
                          clawback: 0
                          reconciliation: 0
                          hourly_salary: 560
                          overtime: 0
                          custom_payment: 0
                          manual_paid_amount: 0
                          gross_pay: 2000
                          net_pay: 1712.5
                          employee_tax: "152.40"
                          employer_tax: "152.40"
                          total_earning: null
                          state_income_tax: 45
                          federal_income_tax: 90.1
                          quickbooks_journal_entry_id: null
                          custom_field:
                            - Sales Bonus: "100"
                              Fuel: "20"
                marked_paid:
                  summary: "is_mark_paid=true: settled outside Sequifi"
                  value:
                    status: 200
                    message: "success"
                    data:
                      requestedBy: "acme"
                      current_page: 1
                      per_page: 10
                      total: 1
                      last_page: 1
                      filters:
                        is_mark_paid: "true"
                      payrolls:
                        - id: 9022
                          payroll_id: 5560
                          user_id: 4835
                          first_name: "Jordan"
                          last_name: "Lee"
                          pay_frequency: 2
                          worker_type: "1099"
                          pay_period_from: "2026-03-15T00:00:00.000Z"
                          pay_period_to: "2026-03-21T00:00:00.000Z"
                          pay_date: null
                          status: 3
                          is_mark_paid: 1
                          is_onetime_payment: 0
                          commission: 950
                          override: 0
                          adjustment: 0
                          reimbursement: 0
                          reimbursement_amount: 0
                          deduction: 0
                          clawback: 0
                          reconciliation: 0
                          hourly_salary: 0
                          overtime: 0
                          custom_payment: 0
                          manual_paid_amount: 0
                          gross_pay: 950
                          net_pay: 950
                          employee_tax: null
                          employer_tax: null
                          total_earning: null
                          state_income_tax: 0
                          federal_income_tax: 0
                          quickbooks_journal_entry_id: null
        "400":
          description: Unknown query parameter or bad filter value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["pay_period_from"]
                      allowed_params: ["quickbooks_synced", "is_mark_paid", "worker_type", "page", "per_page"]
                bad_quickbooks_synced:
                  summary: quickbooks_synced is not true or false
                  value:
                    status: 400
                    message: "quickbooks_synced must be 'true' or 'false'"
                    data: {}
                bad_is_mark_paid:
                  summary: is_mark_paid is not true or false
                  value:
                    status: 400
                    message: "is_mark_paid must be 'true' or 'false'"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error, including a non-numeric page or per_page
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
    patch:
      operationId: updatePaidPayrollJournalIds
      tags:
        - Payroll
      summary: Save QuickBooks journal entry IDs
      description: |
        Saves a QuickBooks journal entry id on paid pay stubs, so they drop out of GET /v1/payroll-history?quickbooks_synced=false. Send a JSON array of 1 to 500 items keyed by `payroll_id`. A different id sent for a stub that already has one replaces it without warning.

        **Before you call:**

        - Take stubs from GET /v1/payroll-history?quickbooks_synced=false and create their journal entries in QuickBooks first.
        - Use `payroll_id` from that list, not `id`.

        **What happens:**

        - All items are saved in one transaction: either every item is applied or none is.
        - The id is saved on every paid record with that `payroll_id`, including records the GET list hides because their payment is in flight or failed.
        - Any existing journal entry id is overwritten.
        - A `payroll_id` with no paid record is listed in `data.not_found`. This is not an error.
        - `data.updated` counts items, not records. An item sent twice counts twice.

        **Idempotency and retries:**

        - Sending the same id again is safe and changes nothing.
        - Sending a new id replaces the old one, which leaves the earlier journal entry orphaned in QuickBooks. Check that `quickbooks_journal_entry_id` is null before you create an entry.
        - After a batch, query GET /v1/payroll-history?quickbooks_synced=false again from page 1.

        **Formats:**

        - `payroll_id` must be a JSON integer. A string such as `"42"` is rejected.
        - `quickbooks_journal_entry_id` must be a non-blank string. Leading and trailing spaces are trimmed.

        **Errors:**

        - `400 Request body must be a non-empty array of { payroll_id, quickbooks_journal_entry_id }`: the body is not a JSON array, is empty, or is not valid JSON.
        - `400 Batch size exceeds 500 items — split into multiple requests`.
        - `400 Validation failed`: `data.errors` lists each bad item by index, for example `"[0]: payroll_id must be a positive integer"`. Nothing is saved.

        **Related:**

        - GET /v1/payroll-history lists paid stubs and their `quickbooks_journal_entry_id`.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              minItems: 1
              maxItems: 500
              items:
                type: object
                required:
                  - payroll_id
                  - quickbooks_journal_entry_id
                properties:
                  payroll_id:
                    type: integer
                    minimum: 1
                    description: The stub's `payroll_id` from GET /v1/payroll-history. Must be a JSON integer.
                    example: 5521
                  quickbooks_journal_entry_id:
                    type: string
                    description: Journal entry id returned by QuickBooks.
                    example: "JE-1042"
            example:
              - payroll_id: 5521
                quickbooks_journal_entry_id: "JE-1042"
              - payroll_id: 5522
                quickbooks_journal_entry_id: "JE-1043"
      responses:
        "200":
          description: Batch saved. Check `not_found` for ids with no paid record.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          updated:
                            type: integer
                            description: Number of items that matched a paid record.
                          not_found:
                            type: array
                            description: "`payroll_id` values with no paid record."
                            items:
                              type: integer
              example:
                status: 200
                message: "quickbooks_journal_entry_id saved"
                data:
                  requestedBy: "acme"
                  updated: 2
                  not_found: []
        "400":
          description: Invalid request body
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_array:
                  summary: Body is not a non-empty array
                  value:
                    status: 400
                    message: "Request body must be a non-empty array of { payroll_id, quickbooks_journal_entry_id }"
                    data: {}
                too_many:
                  summary: More than 500 items
                  value:
                    status: 400
                    message: "Batch size exceeds 500 items — split into multiple requests"
                    data: {}
                validation_errors:
                  summary: One or more items fail validation
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        - "[0]: payroll_id must be a positive integer"
                        - "[1]: quickbooks_journal_entry_id must be a non-empty string"
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error. Nothing in the batch was saved.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/one-time-payments:
    get:
      operationId: listOneTimePayments
      tags:
        - Payroll
      summary: List paid one-time payments
      description: |
        Lists paid one-time payments, each with the same totals as its pay stub, so an accounting sync can post them the same way it posts GET /v1/payroll-history. One-time payments are not listed in GET /v1/payroll-history, so a sync that posts all pay reads both endpoints.

        **What happens:**

        - A payment appears here once it is paid. For some payroll providers it is listed as soon as it is sent, with `settlement_status: "pending"` until the provider confirms it. A failed payment is left out.
        - A one-time payment that paid a whole open payroll from the Payroll screen is listed in GET /v1/payroll-history instead, with `is_onetime_payment: 1`. No payment is in both lists, so posting both lists never posts a payment twice.
        - Figures match the pay stub the worker sees. `gross_pay` is the sum of `commission`, `override`, `reconciliation`, `custom_payment`, `hourly_salary`, `overtime`, `adjustment`, `reimbursement` and `deduction`.
        - `net_pay` is your payroll provider's own figure when it sent one (`net_pay_source: "provider"`). Otherwise it is `amount` minus taxes (`"computed"`). A provider figure can differ from `gross_pay` minus `employee_tax`.

        **Filtering and paging:**

        - `quickbooks_synced=false` returns payments with no journal entry id and an amount above zero, oldest first. `quickbooks_synced=true` returns payments that have one.
        - `worker_type` is an exact match (`1099` or `w2`).
        - There is no date or user filter.
        - `page` defaults to 1. `per_page` defaults to 10; values above 200 are treated as 200.
        - Sorted by `one_time_payment_id`, newest first, except `quickbooks_synced=false`, which sorts oldest first. `last_page` is at least `1`.
        - Saving journal ids while you page through `quickbooks_synced=false` shifts the pages. Start again from page 1 after each PATCH /v1/one-time-payments.

        **Idempotency and retries:**

        - Key your sync on `one_time_payment_id`. It is its own number series: one-time payment 14 and payroll 14 are different records.
        - Before creating a journal entry, check that `quickbooks_journal_entry_id` is null and that you have not already posted that `one_time_payment_id`.

        **Formats:**

        - `pay_period_from`, `pay_period_to` and `pay_date` are dates (`YYYY-MM-DD`).
        - Money fields are JSON numbers rounded to cents. Taxes and benefits are positive amounts. `deduction` is signed: negative lowers pay, as on payroll history.
        - `from_payroll` is `true` when the payment paid lines from an open payroll, and `false` for a standalone payment such as an approved bonus or reimbursement. A standalone payment's own amount is counted in `adjustment`, or in `reimbursement` for a reimbursement.
        - `request_number` is the request number shown in the app, such as `R000014`, or null.

        **Errors:**

        - `400 Invalid query parameter(s)` for an unknown query key.
        - `400 quickbooks_synced must be 'true' or 'false'`.

        **Related:**

        - PATCH /v1/one-time-payments saves journal entry ids.
        - GET /v1/one-time-payments/{id} and its line items read one payment.
        - GET /v1/payroll-history lists paid pay runs.
      security:
        - bearerAuth: []
      parameters:
        - name: quickbooks_synced
          in: query
          required: false
          description: "`false` returns payments with no journal entry id and an amount above zero, oldest first. `true` returns payments that have one. Omit for all."
          schema:
            type: string
            enum: ["false", "true"]
          example: "false"
        - name: worker_type
          in: query
          required: false
          description: "Exact match on worker type: `1099` or `w2`. Other values return no rows."
          schema:
            type: string
          example: "w2"
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
          example: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page. Values above 200 are treated as 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 10
          example: 10
      responses:
        "200":
          description: A page of paid one-time payments
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page after the 200 cap.
                          total:
                            type: integer
                            description: Rows across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          filters:
                            type: object
                            nullable: true
                            description: The filters applied, or null when none were sent.
                          one_time_payments:
                            type: array
                            items:
                              $ref: '#/components/schemas/OneTimePayment'
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 10
                  total: 1
                  last_page: 1
                  filters:
                    quickbooks_synced: "false"
                  one_time_payments:
                    - one_time_payment_id: 14
                      is_onetime_payment: 1
                      user_id: 501
                      first_name: "Jordan"
                      last_name: "Lee"
                      employee_id: "AC-0042"
                      worker_type: "w2"
                      pay_frequency: 1
                      pay_period_from: "2026-10-26"
                      pay_period_to: "2026-11-01"
                      pay_date: "2026-10-30"
                      request_number: "R000014"
                      description: "Signing bonus"
                      adjustment_type_id: 1
                      adjustment_type: "Bonus"
                      from_payroll: false
                      commission: 0
                      override: 0
                      reconciliation: 0
                      custom_payment: 0
                      hourly_salary: 0
                      overtime: 0
                      adjustment: 1000
                      reimbursement: 0
                      deduction: 0
                      gross_pay: 1000
                      employee_tax: 218.8
                      state_income_tax: 0
                      federal_income_tax: 0
                      employer_tax: 76.5
                      employee_benefit_deduction: 0
                      employer_benefit_deduction: 0
                      net_pay: 781.2
                      net_pay_source: "provider"
                      amount: 1000
                      settlement_status: "paid"
                      is_deposit_returned: false
                      quickbooks_journal_entry_id: null
                      created_at: "2026-10-30T15:00:00.000Z"
                      updated_at: "2026-10-30T15:05:00.000Z"
        "400":
          description: Unknown query parameter or bad filter value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["is_mark_paid"]
                      allowed_params: ["quickbooks_synced", "worker_type", "page", "per_page"]
                bad_quickbooks_synced:
                  summary: quickbooks_synced is not true or false
                  value:
                    status: 400
                    message: "quickbooks_synced must be 'true' or 'false'"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
    patch:
      operationId: updateOneTimePaymentJournalIds
      tags:
        - Payroll
      summary: Save journal entry IDs for one-time payments
      description: |
        Saves a journal entry id on paid one-time payments, so they drop out of GET /v1/one-time-payments?quickbooks_synced=false. Send a JSON array of 1 to 500 items keyed by `one_time_payment_id`. A different id sent for a payment that already has one replaces it without warning.

        **Before you call:**

        - Take payments from GET /v1/one-time-payments?quickbooks_synced=false and create their journal entries first.
        - Use `one_time_payment_id`. Never send a `payroll_id` here: the two are different number series. Pay runs are saved with PATCH /v1/payroll-history.

        **What happens:**

        - All items are saved in one transaction: either every item is applied or none is.
        - Any existing journal entry id is overwritten.
        - A `one_time_payment_id` with no one-time payment is listed in `data.not_found`. This is not an error.
        - `data.updated` counts items, not records. An item sent twice counts twice.

        **Idempotency and retries:**

        - Sending the same id again is safe and changes nothing.
        - Sending a new id replaces the old one, which leaves the earlier journal entry orphaned in your books. Check that `quickbooks_journal_entry_id` is null before you create an entry.
        - After a batch, query GET /v1/one-time-payments?quickbooks_synced=false again from page 1.

        **Formats:**

        - `one_time_payment_id` must be a JSON integer. A string such as `"14"` is rejected.
        - `quickbooks_journal_entry_id` must be a non-blank string, from any accounting system. Leading and trailing spaces are trimmed.

        **Errors:**

        - `400 Request body must be a non-empty array of { one_time_payment_id, quickbooks_journal_entry_id }`: the body is not a JSON array, is empty, or is not valid JSON.
        - `400 Batch size exceeds 500 items — split into multiple requests`.
        - `400 Validation failed`: `data.errors` lists each bad item by index, for example `"[0]: one_time_payment_id must be a positive integer"`. Nothing is saved.

        **Related:**

        - GET /v1/one-time-payments lists paid one-time payments and their `quickbooks_journal_entry_id`.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: array
              minItems: 1
              maxItems: 500
              items:
                type: object
                required:
                  - one_time_payment_id
                  - quickbooks_journal_entry_id
                properties:
                  one_time_payment_id:
                    type: integer
                    minimum: 1
                    description: The payment's `one_time_payment_id` from GET /v1/one-time-payments. Must be a JSON integer.
                    example: 14
                  quickbooks_journal_entry_id:
                    type: string
                    description: Journal entry id from your accounting system.
                    example: "JE-1042"
            example:
              - one_time_payment_id: 14
                quickbooks_journal_entry_id: "JE-1042"
              - one_time_payment_id: 32
                quickbooks_journal_entry_id: "JE-1043"
      responses:
        "200":
          description: Batch saved. Check `not_found` for ids with no one-time payment.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          updated:
                            type: integer
                            description: Number of items that matched a one-time payment.
                          not_found:
                            type: array
                            description: "`one_time_payment_id` values with no one-time payment."
                            items:
                              type: integer
              example:
                status: 200
                message: "quickbooks_journal_entry_id saved"
                data:
                  requestedBy: "acme"
                  updated: 2
                  not_found: []
        "400":
          description: Invalid request body
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_array:
                  summary: Body is not a non-empty array
                  value:
                    status: 400
                    message: "Request body must be a non-empty array of { one_time_payment_id, quickbooks_journal_entry_id }"
                    data: {}
                too_many:
                  summary: More than 500 items
                  value:
                    status: 400
                    message: "Batch size exceeds 500 items — split into multiple requests"
                    data: {}
                validation_errors:
                  summary: One or more items fail validation
                  value:
                    status: 400
                    message: "Validation failed"
                    data:
                      errors:
                        - "[0]: one_time_payment_id must be a positive integer"
                        - "[1]: quickbooks_journal_entry_id must be a non-empty string"
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error. Nothing in the batch was saved.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/one-time-payments/{id}:
    get:
      operationId: getOneTimePayment
      tags:
        - Payroll
      summary: Get a paid one-time payment
      description: |
        Returns one paid one-time payment by `one_time_payment_id`, in the same shape as GET /v1/one-time-payments. The response is a one-item page so your code can read both the same way.

        **What happens:**

        - Applies the same rules as the list: a payment that is not paid yet, or that failed, returns `404`.
        - A one-time payment that paid a whole open payroll returns `404` with `data.payroll_id`. Read it from GET /v1/payroll-history/{id} with that id.

        **Errors:**

        - `400 Invalid one-time payment id` when the id is not a positive integer.
        - `400 Cannot use query parameters when fetching a single one-time payment by id`.
        - `404 One-time payment not found`.

        **Related:**

        - GET /v1/one-time-payments/{id}/line-items itemizes the payment.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The payment's `one_time_payment_id`.
          schema:
            type: integer
            minimum: 1
          example: 14
      responses:
        "200":
          description: The payment, as a one-item page
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                          per_page:
                            type: integer
                          total:
                            type: integer
                          last_page:
                            type: integer
                          one_time_payments:
                            type: array
                            items:
                              $ref: '#/components/schemas/OneTimePayment'
        "400":
          description: Invalid id, or query parameters sent
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Invalid one-time payment id"
                data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: No paid one-time payment with this id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_found:
                  summary: Unknown, unpaid or failed payment
                  value:
                    status: 404
                    message: "One-time payment not found"
                    data: {}
                paid_a_payroll:
                  summary: Paid a whole payroll, so it is on payroll history
                  value:
                    status: 404
                    message: "This one-time payment paid a whole payroll. Read it from /v1/payroll-history."
                    data:
                      payroll_id: 9001
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/one-time-payments/{id}/line-items:
    get:
      operationId: listOneTimePaymentLineItems
      tags:
        - Payroll
      summary: List a one-time payment's line items
      description: |
        Returns the rows a paid one-time payment was built from (which deal, which milestone, how much), in the same shape as GET /v1/payroll-history/{id}/line-items. Sum only rows with `counts_toward_pay: true` to match the payment.

        **What happens:**

        - Reads the copy of each row that Sequifi saved when the payment was made, so figures do not change when live commissions are later recalculated.
        - Each row has a `category` matching a section of the stub: `commission`, `override`, `adjustment`, `reimbursement`, `additional_value` (custom payroll fields) or `deduction`.
        - A standalone payment, such as an approved bonus, is itself one row with `source: "one_time_payments"`, in `adjustment`, or in `reimbursement` for a reimbursement.
        - A row with `counts_toward_pay: false` was marked paid outside this payment. `excluded_reason` is `paid_externally`, `do_not_pay` or `marked_paid`, and the row is summed into `totals.excluded_total`.
        - Wages, overtime, reconciliation and taxes are not itemized. They are totals on GET /v1/one-time-payments.

        **Filtering and paging:**

        - `category` returns one section. `totals` respect `category` but always cover the whole payment, never only the current page.
        - `page` defaults to 1. `per_page` defaults to 50, maximum 500.

        **Formats:**

        - `(source, id)` identifies a row. `id` alone can repeat across sections.
        - `pay_date` and each row's `date` are dates (`YYYY-MM-DD`).

        **Errors:**

        - `400 Invalid one-time payment id`, `400 Invalid category`, or a bad `page` or `per_page`.
        - `404 One-time payment not found`: unknown, not paid yet, failed, or paid a whole payroll (use GET /v1/payroll-history/{id}/line-items for that one).

        **Related:**

        - GET /v1/one-time-payments/{id} returns the payment's totals.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: The payment's `one_time_payment_id`.
          schema:
            type: integer
            minimum: 1
          example: 14
        - name: category
          in: query
          required: false
          description: Return one section of the stub.
          schema:
            type: string
            enum: [commission, override, adjustment, reimbursement, additional_value, deduction]
        - name: page
          in: query
          required: false
          description: Page number.
          schema:
            type: integer
            minimum: 1
            default: 1
        - name: per_page
          in: query
          required: false
          description: Rows per page, maximum 500.
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 50
      responses:
        "200":
          description: The payment's line items
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  one_time_payment_id: 14
                  user:
                    id: 501
                    employee_id: "AC-0042"
                    first_name: "Jordan"
                    last_name: "Lee"
                    position_id: 3
                    position_name: "Sales Rep"
                    worker_type: "w2"
                  pay_period_from: "2026-10-26"
                  pay_period_to: "2026-11-01"
                  pay_frequency: 1
                  pay_date: "2026-10-30"
                  is_history: true
                  totals:
                    commission: 0
                    override: 0
                    adjustment: 1000
                    reimbursement: 0
                    additional_value: 0
                    deduction: 0
                    line_items_total: 1000
                    excluded_total: 0
                  filters: null
                  current_page: 1
                  per_page: 50
                  total: 1
                  last_page: 1
                  line_items:
                    - id: 14
                      source: "one_time_payments"
                      category: "adjustment"
                      type: "Bonus"
                      pid: null
                      customer_name: "Jordan Lee"
                      amount: 1000
                      date: "2026-10-30"
                      description: "Signing bonus"
                      counts_toward_pay: true
                      excluded_reason: null
        "400":
          description: Invalid id, category, page or per_page
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Invalid one-time payment id"
                data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: No paid one-time payment with this id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "One-time payment not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
  /v1/requests:
    post:
      operationId: createRequest
      tags:
        - Requests
      summary: Create a bonus, fine/fee or reimbursement request
      description: |
        Creates one bonus, fine/fee or reimbursement request for a worker. It is the same request an admin creates on the Requests & Approvals page, except that it always starts as **Pending**: it waits for an admin to approve it, and nothing is paid until they do. Use it to send the bonuses and fines you track in your own system instead of entering them one at a time.

        **Before you call:**

        - Name the worker with `user_email` or `user_id`, not both. `GET /v1/users` returns both.
        - Send every amount as a positive number, including a fine. The type says whether it adds to or comes out of pay.
        - Write `description` for the worker. It is what they see on their pay stub.
        - Send your own `external_id` with every request. It is what makes a retry safe (see below).

        **What happens:**

        - Sequifi creates the request as `Pending`, numbered like any other request (`B` for a bonus, `FF` for a fine/fee, `R` for a reimbursement).
        - It goes to your company's admins, not the worker's manager. Admins find it under Requests & Approvals, Pending, and approve or decline it there.
        - Once approved, it is paid like a request created in the app.
        - **Straight onto a payroll (on request):** send `pay_period_from`, `pay_period_to` and `approve: true` and the request skips admin approval and goes onto that payroll, the same as Add Request on Run Payroll. The worker then appears on Run Payroll even with no other pay that period. Sequifi turns this on per company; ask your Sequifi contact. The period must be an open pay period on the worker's own pay schedule, with both dates exactly matching it. `approve: true` is your approval of that one request: Sequifi records it on the request as approved through the API by your credential.
        - `date` is the request date for a bonus or fine/fee, and the cost date for a reimbursement.

        **Limits (per company):**

        - 60 calls a minute. Over the limit returns `429` with a `Retry-After` header.
        - Creates run one at a time. A call that waits more than 10 seconds behind another returns `409` with `data.code` `CREATE_IN_PROGRESS`. To send many requests, send them one after another.

        **Idempotency and retries:**

        - With an `external_id`, a retry is safe. If a request with that `external_id` already exists, the call returns `409` with `data.code` `REQUEST_ALREADY_EXISTS` and the existing request in `data.request`, and creates nothing. Treat that as success.
        - Without an `external_id`, two identical calls create two requests. That is right for two identical fines and wrong for a retry.
        - After a `504`, the request may still have been created. Re-send the identical body with the same `external_id` to find out.

        **Errors:**

        - `400`: a field failed validation. The message names it. Nothing was sent to Sequifi.
        - `409` with `data.code` `REQUEST_ALREADY_EXISTS` (see above) or `CREATE_IN_PROGRESS` (retry in a moment).
        - `422` with `data.code` `USER_NOT_FOUND` (no user with that email or id), `USER_AMBIGUOUS` (more than one user has that email; `data.user_ids` lists them, send `user_id` instead) or `USER_NOT_ACTIVE` (the worker was terminated, dismissed or past their contract end on `date`).
        - `422` with `data.errors`: a field was refused by Sequifi's own validation, keyed by field.
        - `403` with `data.code` `PAYROLL_SCHEDULING_NOT_ENABLED`: a pay period was sent but your company is not set up for it. Send without the two dates to create a pending request.
        - `422` with `data.code` `APPROVAL_REQUIRED`: a pay period was sent without `approve: true`.
        - `422` with `data.code` `PAY_PERIOD_NOT_OPEN` (the dates are not an open pay period on the worker's schedule) or `NO_PAY_SCHEDULE` (the worker has no pay schedule).
        - `409` with `data.code` `PAY_PERIOD_CLOSED`: that payroll is being finalized or has been paid.
        - `429`: over the rate limit. Wait for `Retry-After` seconds.
        - `500` `Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502` `The tenant returned an unreadable response` or `Could not reach the tenant`: retry later.
        - `503`: your company is not set up for this endpoint (`data.code` `NOT_PROVISIONED`, `TYPE_NOT_CONFIGURED` or `CREDENTIAL_MISSING`, or no code). Contact Sequifi support.
        - `504`: no answer in time. See retries above.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so nothing is created.

        **Related:**

        - `GET /v1/users` to look up a worker's email or id.
        - `GET /v1/payroll/{id}/line-items` to see approved requests on a pay stub.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - type
                - amount
                - date
                - description
              properties:
                type:
                  type: string
                  enum: [bonus, fine_fee, reimbursement]
                  description: What the request is. A bonus and a reimbursement add to pay; a fine/fee comes out of it.
                user_email:
                  type: string
                  format: email
                  maxLength: 255
                  description: The worker's email in Sequifi. Send this or `user_id`, not both.
                user_id:
                  type: integer
                  minimum: 1
                  description: The worker's Sequifi user id. Send this or `user_email`, not both.
                amount:
                  oneOf:
                    - type: number
                    - type: string
                  description: Positive, at most 2 decimal places, at most 1000000. A number or a numeric string. A fine is positive too.
                  example: 150.00
                date:
                  type: string
                  format: date
                  description: The request date (bonus, fine/fee) or the cost date (reimbursement), as `YYYY-MM-DD`.
                description:
                  type: string
                  maxLength: 1000
                  description: What the request is for, written for the worker. Shown on their pay stub.
                external_id:
                  type: string
                  maxLength: 100
                  pattern: '^[A-Za-z0-9._:-]+$'
                  description: Your own id for this request. A second call with the same `external_id` returns the first request instead of creating another.
                pay_period_from:
                  type: string
                  format: date
                  description: Optional, with `pay_period_to`. Puts the request straight onto this payroll instead of leaving it pending. Only for companies Sequifi has turned this on for.
                pay_period_to:
                  type: string
                  format: date
                  description: Optional, with `pay_period_from`. The last day of the pay period.
                approve:
                  type: boolean
                  description: Required as `true` with a pay period. Your approval of this one request, recorded on it in Sequifi. Ignored without a pay period.
            examples:
              bonus_by_email:
                summary: A bonus, worker named by email
                value:
                  type: "bonus"
                  user_email: "carson@example.com"
                  amount: 150.00
                  date: "2026-10-19"
                  description: "Top closer, week of Oct 12"
                  external_id: "bonus-2026-10-19-0042"
              fine_by_id:
                summary: A fine, worker named by id
                value:
                  type: "fine_fee"
                  user_id: 428
                  amount: 25
                  date: "2026-10-19"
                  description: "Late to team meeting"
                  external_id: "fine-2026-10-19-0007"
              bonus_onto_payroll:
                summary: A bonus straight onto a payroll (companies set up for it)
                value:
                  type: "bonus"
                  user_email: "carson@example.com"
                  amount: 150.00
                  date: "2026-10-19"
                  description: "Top closer, week of Oct 12"
                  external_id: "bonus-2026-10-19-0043"
                  pay_period_from: "2026-10-19"
                  pay_period_to: "2026-10-25"
                  approve: true
      responses:
        '201':
          description: Created as Pending. It waits for an admin to approve it.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          id:
                            type: integer
                            description: The request's id in Sequifi.
                          req_no:
                            type: string
                            description: The request number shown in the app, for example `B000124`.
                          status:
                            type: string
                            description: '`Pending` (waiting for an admin), or `Scheduled` when sent with a pay period (already on that payroll).'
                          type:
                            type: string
                            enum: [bonus, fine_fee, reimbursement]
                          user_id:
                            type: integer
                          user_email:
                            type: string
                          amount:
                            type: number
                            description: As stored, always positive.
                          date:
                            type: string
                            format: date
                          description:
                            type: string
                          external_id:
                            type: string
                            nullable: true
                          pay_period_from:
                            type: string
                            format: date
                            nullable: true
                            description: The payroll the request is on, when scheduled.
                          pay_period_to:
                            type: string
                            format: date
                            nullable: true
                          warnings:
                            type: array
                            items:
                              type: string
                            description: Present only when a pay period was sent but not applied (the request was created as pending). Do not re-send; contact Sequifi support.
                          created_at:
                            type: string
                            format: date-time
              example:
                status: 201
                message: "Request created. It is waiting for an admin to approve it."
                data:
                  id: 9001
                  req_no: "B000124"
                  status: "Pending"
                  type: "bonus"
                  user_id: 428
                  user_email: "carson@example.com"
                  amount: 150
                  date: "2026-10-19"
                  description: "Top closer, week of Oct 12"
                  external_id: "bonus-2026-10-19-0042"
                  created_at: "2026-10-20T16:04:11+00:00"
        '400':
          description: A field failed validation. Nothing was sent to Sequifi.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                both_users:
                  summary: Both user_email and user_id
                  value:
                    status: 400
                    message: "Send exactly one of user_email or user_id to say who the request is for"
                    data: {}
                bad_amount:
                  summary: Negative or over-precise amount
                  value:
                    status: 400
                    message: "amount is required and must be a positive number with at most 2 decimal places. Send a fine as a positive amount."
                    data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so nothing is created.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 401
                message: "Unauthorized"
                data: {}
        '403':
          description: A pay period was sent but your company is not set up to add requests to a payroll
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "This company is not set up to add requests to a payroll over the API. Send the request without pay_period_from and pay_period_to to create it as pending for an admin to approve."
                data:
                  code: "PAYROLL_SCHEDULING_NOT_ENABLED"
        '409':
          description: A request with this `external_id` already exists, another create is still running, or the payroll is closed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                already_exists:
                  summary: Same external_id already used (treat as success)
                  value:
                    status: 409
                    message: "A request with external_id \"bonus-2026-10-19-0042\" already exists (B000124)."
                    data:
                      code: "REQUEST_ALREADY_EXISTS"
                      request:
                        id: 9001
                        req_no: "B000124"
                        status: "Pending"
                        type: "bonus"
                        user_id: 428
                        user_email: "carson@example.com"
                        amount: 150
                        date: "2026-10-19"
                        description: "Top closer, week of Oct 12"
                        external_id: "bonus-2026-10-19-0042"
                        created_at: "2026-10-20T16:04:11+00:00"
                in_progress:
                  summary: Another create is running (retry in a moment)
                  value:
                    status: 409
                    message: "Another request create for this company is already running. Retry in a moment."
                    data:
                      code: "CREATE_IN_PROGRESS"
                pay_period_closed:
                  summary: That payroll is being finalized or has been paid
                  value:
                    status: 409
                    message: "The payroll for 2026-10-19 to 2026-10-25 is being finalized or has been paid, so requests can no longer be added to it."
                    data:
                      code: "PAY_PERIOD_CLOSED"
                      pay_period_from: "2026-10-19"
                      pay_period_to: "2026-10-25"
        '422':
          description: The worker could not be used, or Sequifi refused a field
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                user_not_found:
                  summary: No user with that email or id
                  value:
                    status: 422
                    message: "No user with email carson@example.com in this company."
                    data:
                      code: "USER_NOT_FOUND"
                      user_email: "carson@example.com"
                user_ambiguous:
                  summary: Email shared by more than one user
                  value:
                    status: 422
                    message: "More than one user has the email carson@example.com. Send user_id instead."
                    data:
                      code: "USER_AMBIGUOUS"
                      user_email: "carson@example.com"
                      user_ids: [428, 512]
                user_not_active:
                  summary: Worker not active on the date
                  value:
                    status: 422
                    message: "User 428 is not active on 2026-10-19, so a request cannot be created for them."
                    data:
                      code: "USER_NOT_ACTIVE"
                      user_id: 428
                      date: "2026-10-19"
                approval_required:
                  summary: Pay period sent without approve true
                  value:
                    status: 422
                    message: "A request sent with a pay period skips admin approval, so it must carry \"approve\": true to say you approve it. Send approve: true, or leave out the pay period to create it as pending."
                    data:
                      code: "APPROVAL_REQUIRED"
                pay_period_not_open:
                  summary: Not an open pay period on the worker's schedule
                  value:
                    status: 422
                    message: "2026-10-20 to 2026-10-25 is not an open pay period on this worker's pay schedule."
                    data:
                      code: "PAY_PERIOD_NOT_OPEN"
                      user_id: 428
                      pay_period_from: "2026-10-20"
                      pay_period_to: "2026-10-25"
                field_errors:
                  summary: Refused by Sequifi's validation
                  value:
                    status: 422
                    message: "The amount field must have 0-2 decimal places."
                    data:
                      errors:
                        amount: ["The amount field must have 0-2 decimal places."]
        '429':
          description: Over 60 calls a minute. Wait for `Retry-After` seconds.
          headers:
            Retry-After:
              description: Seconds to wait before trying again.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 429
                message: "Too Many Attempts."
                data: {}
        '500':
          description: Sequifi could not resolve your company's host
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Could not resolve the tenant host"
                data: {}
        '502':
          description: Sequifi could not complete the request. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 502
                message: "Could not reach the tenant"
                data: {}
        '503':
          description: Your company is not set up for this endpoint. Contact Sequifi support.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This company is not configured for creating requests over the API. Contact Sequifi support."
                    data: {}
                type_not_configured:
                  summary: Request type not set up
                  value:
                    status: 503
                    message: "This company is not set up for bonus requests over the API. Contact Sequifi support."
                    data:
                      code: "TYPE_NOT_CONFIGURED"
                      type: "bonus"
        '504':
          description: No answer in time. The request may still have been created; re-send with the same `external_id`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The request may still have been created. Re-post the identical body: you will get 201 if it was not, or 409 REQUEST_ALREADY_EXISTS with the existing request if it was."
                data: {}


  /v1/pay-frequency:
    get:
      operationId: listPayFrequencies
      tags:
        - Pay Frequency
      summary: List pay frequencies
      description: |
        Lists the pay frequencies your company has turned on, so you can map a pay frequency id to its name. Ids are fixed: `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily (on demand). There is no id `1`.

        **Filtering and paging:**

        - Only active frequencies are returned, sorted by `id`.
        - `page` defaults to 1. `per_page` defaults to 20 and is kept between 1 and 200: out-of-range values are adjusted, not rejected.
        - Unknown query parameters are ignored.

        **Formats:**

        - `status` is always `"Active"`.
        - `name` is the display name, for example `Bi-Weekly` or `Daily (on demand)`.

        **Related:**

        - GET /v1/payroll filters by pay frequency id.
        - GET /v1/pay-frequency/{id} reads one frequency.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            default: 1
          description: Page number. A value below 1 or not a number is treated as 1.
          example: 1
        - name: per_page
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 200
            default: 20
          description: Rows per page. Values above 200 are treated as 200.
          example: 20
      responses:
        "200":
          description: Active pay frequencies
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Rows per page after adjustment.
                          total:
                            type: integer
                            description: Active frequencies across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          filters:
                            type: object
                            nullable: true
                            description: Always null.
                          frequency_type:
                            type: array
                            description: The pay frequencies on this page.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Pay frequency id. `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily (on demand).
                                name:
                                  type: string
                                  description: Display name.
                                status:
                                  type: string
                                  description: Always `Active`.
              example:
                status: 200
                message: "success"
                data:
                  requested_by: "acme"
                  current_page: 1
                  per_page: 20
                  total: 5
                  last_page: 1
                  filters: null
                  frequency_type:
                    - id: 2
                      name: "Weekly"
                      status: "Active"
                    - id: 3
                      name: "Bi-Weekly"
                      status: "Active"
                    - id: 4
                      name: "Semi-Monthly"
                      status: "Active"
                    - id: 5
                      name: "Monthly"
                      status: "Active"
                    - id: 6
                      name: "Daily (on demand)"
                      status: "Active"
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/pay-frequency/{id}:
    get:
      operationId: getPayFrequency
      tags:
        - Pay Frequency
      summary: Get a pay frequency
      description: |
        Returns one active pay frequency by id. Ids are fixed: `2` Weekly, `3` Bi-Weekly, `4` Semi-Monthly, `5` Monthly, `6` Daily (on demand). Id `1` does not exist and returns 404.

        **What happens:**

        - The frequency comes back in `data.frequency_type` as a one-item array, in the same envelope as the list.
        - A frequency your company has not turned on returns 404.

        **Errors:**

        - `400 Invalid frequency type id`: the id is not a positive whole number (for example `2abc`).
        - `400 Cannot use query parameters when fetching a single frequency type by id`: remove the query string.
        - `404 Frequency type not found`: no such id, or the frequency is not active.

        **Related:**

        - GET /v1/pay-frequency lists all active frequencies.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            minimum: 1
          description: Pay frequency id.
          example: 2
      responses:
        "200":
          description: The pay frequency
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Label of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Always `1`.
                          per_page:
                            type: integer
                            description: Always `1`.
                          total:
                            type: integer
                            description: Always `1`.
                          last_page:
                            type: integer
                            description: Always `1`.
                          filters:
                            type: object
                            nullable: true
                            description: Always null.
                          frequency_type:
                            type: array
                            description: One pay frequency.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Pay frequency id.
                                name:
                                  type: string
                                  description: Display name.
                                status:
                                  type: string
                                  description: Always `Active`.
              example:
                status: 200
                message: "success"
                data:
                  requested_by: "acme"
                  current_page: 1
                  per_page: 1
                  total: 1
                  last_page: 1
                  filters: null
                  frequency_type:
                    - id: 2
                      name: "Weekly"
                      status: "Active"
        "400":
          description: Invalid id, or query parameters sent with the id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid frequency type id"
                    data: {}
                query_params_not_allowed:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single frequency type by id"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: No active pay frequency with this id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Frequency type not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/timesheet/{id}:
    get:
      operationId: getUserTimesheet
      tags:
        - Timesheet
      summary: Get a user's current timesheet
      description: |
        Returns the current pay period's day-by-day time records for one user. The path `id` is a user id, not a timesheet id. This is the same as GET /v1/timesheet with `pay_period=current`.

        **What happens:**

        - The response has the same shape as GET /v1/timesheet. See that endpoint for the four shapes a `day` can take.
        - The current period is the one containing today's date in UTC.
        - Deleted records are included: skip any day or event whose `deleted_at` is set.
        - An unknown user id returns `200` with `pay_frequency: null` and an empty `timesheets` array.

        **Errors:**

        - `400 Cannot use query parameters when fetching a single user by id`: remove the query string. Use GET /v1/timesheet for the previous period.
        - `400 Position pay frequency not found`: the user's position has no pay frequency, or it is Daily, which timesheets do not support.
        - `400 Pay period not found`: no pay period covers today.

        **Related:**

        - GET /v1/timesheet reads the current or previous period.
        - POST /v1/timesheet records time.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: User id (not a timesheet id).
          schema:
            type: integer
            minimum: 1
          example: 4821
      responses:
        '200':
          description: The user's current-period timesheet
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Label of the API credential that made the call.
                          pay_frequency:
                            type: object
                            nullable: true
                            description: The pay period shown, or null when the user does not exist. Other fields of the period may be present.
                            properties:
                              id:
                                type: integer
                                description: Pay period id.
                              pay_period_from:
                                type: string
                                description: Start of the period, `YYYY-MM-DD HH:MM:SS`.
                              pay_period_to:
                                type: string
                                description: End of the period, `YYYY-MM-DD HH:MM:SS`.
                          timesheets:
                            type: array
                            description: One entry per calendar day of the period, oldest first. See GET /v1/timesheet for the shapes of `day`.
                            items:
                              type: object
                              properties:
                                day:
                                  description: An object for a day with records, an absence or an adjustment, or a plain `YYYY-MM-DD` string when nothing applies.
                                  oneOf:
                                    - type: object
                                    - type: string
              example:
                status: 200
                message: "success"
                data:
                  requested_by: "acme"
                  pay_frequency:
                    id: 412
                    pay_period_from: "2026-10-05 00:00:00"
                    pay_period_to: "2026-10-11 00:00:00"
                  timesheets:
                    - day:
                        date: "2026-10-05"
                        user_attendance_list:
                          attendance_type: "absent"
                          attendance_time: "08:00:00"
                    - day:
                        id: 90812
                        user_id: 4821
                        current_time: "04:00:00"
                        lunch_time: "00:00:00"
                        break_time: "00:00:00"
                        is_synced: 1
                        date: "2026-10-06 00:00:00"
                        status: 1
                        deleted_at: null
                        user_attendance_list:
                          - id: 551203
                            type: "clock in"
                            attendance_type: "present"
                            attendance_date: "2026-10-06 08:00:00"
                            attendance_time: "04:00:00"
                            entry_type: "Marketplace-API"
                            external_reference_id: "fieldtool:entry:10482"
                            job_id: "1042"
                            job_name: "Unit turn clean"
                            labor_rate: "20.000"
                            earnings: "80.000"
                            office_id: 0
                            deleted_at: null
                          - id: 551204
                            type: "clock out"
                            attendance_type: "clock out"
                            attendance_date: "2026-10-06 12:00:00"
                            attendance_time: null
                            entry_type: "Marketplace-API"
                            external_reference_id: "fieldtool:entry:10482"
                            job_id: "1042"
                            job_name: "Unit turn clean"
                            labor_rate: null
                            earnings: null
                            office_id: 0
                            deleted_at: null
                    - day: "2026-10-07"
        '400':
          description: Query parameters sent with the id, or the user's pay period cannot be found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                query_params_not_allowed:
                  summary: Query parameters sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single user by id"
                    data: {}
                no_pay_frequency:
                  summary: Position has no supported pay frequency
                  value:
                    status: 400
                    message: "Position pay frequency not found"
                    data: {}
                pay_period_not_found:
                  summary: No pay period covers today
                  value:
                    status: 400
                    message: "Pay period not found"
                    data: {}
        '401':
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/timesheet:
    get:
      operationId: listTimesheetByPayPeriod
      tags:
        - Timesheet
      summary: Get a user's timesheet
      description: |
        Returns one user's day-by-day time records for their current or previous pay period. Send `user_id` (not `userId`) and `pay_period`; any other query key returns `400 Invalid query parameter(s)`.

        **Before you call:**

        - Get the user id from GET /v1/users.
        - The user's position needs a Weekly, Bi-Weekly, Semi-Monthly or Monthly pay frequency. Daily positions return `400 Position pay frequency not found`.

        **What happens:**

        - `current` is the pay period containing today's date in UTC. `previous` is the latest period that ended before that date. In US time zones the current period switches in the evening of its last day, local time.
        - `timesheets` has one entry per calendar day of the period, oldest first. Each entry's `day` takes one of four shapes:
          1. A day with time records: an object with daily totals and `user_attendance_list`, an array of clock events.
          2. A past scheduled day with no records: `{date, user_attendance_list: {attendance_type: "absent", attendance_time}}`. Here `user_attendance_list` is an object, not an array, and `attendance_time` is the scheduled length.
          3. A day with only an approved time adjustment: an object whose totals are null and whose `user_attendance_list` holds the adjustment (`attendance_type: "Adjustment"`, `clock_in`, `clock_out`, `attendance_time`).
          4. Any other day: `day` is the plain date string `"YYYY-MM-DD"`.
        - Deleted records are included. Skip any day or event whose `deleted_at` is set.
        - An unknown `user_id` returns `200` with `pay_frequency: null` and an empty `timesheets` array.

        **Formats:**

        - Dates and clock times are `YYYY-MM-DD HH:MM:SS` strings with no time zone, as stored. On absence and adjustment days, `date` is `YYYY-MM-DD`.
        - Durations are `HH:MM:SS`: `current_time` is net worked time for the day, `lunch_time` and `break_time` are the day's breaks, and `attendance_time` is the time until the next event.
        - `labor_rate` and `earnings` on clock events are decimal strings with three places, such as `"20.000"`, or null. Pay is stored on the clock-in event.
        - `time_format` does not change these values. With `time_format=12`, absence durations can come back as `"NaN:NaN:NaN"`, so omit it.
        - Each clock event can also carry other stored fields not listed here; ignore them.

        **Errors:**

        - `400 Invalid query parameter(s)`, with `data.invalid_params` and `data.allowed_params`.
        - `400 user_id is required`.
        - `400 Validation Failed` with `data.pay_period`: `"required"`, or `"Invalid. Allowed: current, previous"`.
        - `400 Position pay frequency not found`: no pay frequency on the user's position, or it is Daily.
        - `400 Pay period not found`: no pay period matches.

        **Related:**

        - POST /v1/timesheet records time.
        - GET /v1/timesheet/{id} is a shortcut for the current period.
        - GET /v1/payroll shows the resulting wages in `hourly_salary`.
      security:
        - bearerAuth: []
      parameters:
        - name: user_id
          in: query
          required: true
          description: User id from GET /v1/users. The name is `user_id`; `userId` is rejected.
          schema:
            type: integer
            minimum: 1
          example: 4821
        - name: pay_period
          in: query
          required: true
          description: "`current` for the period containing today (UTC), `previous` for the latest period that ended before today."
          schema:
            type: string
            enum: [current, previous]
          example: current
        - name: time_format
          in: query
          required: false
          description: Has no effect on returned clock times, and `12` can break absence durations. Omit it.
          schema:
            type: string
            enum: ["12", "24"]
            default: "24"
      responses:
        '200':
          description: The user's timesheet for the period
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Label of the API credential that made the call.
                          pay_frequency:
                            type: object
                            nullable: true
                            description: The pay period shown, or null when the user does not exist. Other fields of the period may be present.
                            properties:
                              id:
                                type: integer
                                description: Pay period id.
                              pay_period_from:
                                type: string
                                description: Start of the period, `YYYY-MM-DD HH:MM:SS`.
                              pay_period_to:
                                type: string
                                description: End of the period, `YYYY-MM-DD HH:MM:SS`.
                          timesheets:
                            type: array
                            description: One entry per calendar day of the period, oldest first.
                            items:
                              type: object
                              properties:
                                day:
                                  description: One calendar day.
                                  oneOf:
                                    - type: object
                                      title: Day with records, an absence or an adjustment
                                      properties:
                                        id:
                                          type: integer
                                          nullable: true
                                          description: Day record id. Null on adjustment days, absent on absence days.
                                        user_id:
                                          type: integer
                                          nullable: true
                                          description: User id. Null on adjustment days.
                                        current_time:
                                          type: string
                                          nullable: true
                                          description: Net worked time for the day, `HH:MM:SS`.
                                        lunch_time:
                                          type: string
                                          nullable: true
                                          description: Lunch time for the day, `HH:MM:SS`.
                                        break_time:
                                          type: string
                                          nullable: true
                                          description: Break time for the day, `HH:MM:SS`.
                                        is_synced:
                                          type: integer
                                          nullable: true
                                          description: "`1` once the day's totals have been calculated, otherwise `0`."
                                        date:
                                          type: string
                                          description: The day. `YYYY-MM-DD HH:MM:SS` on days with records, `YYYY-MM-DD` on absence and adjustment days.
                                        status:
                                          type: integer
                                          nullable: true
                                          description: "`1` when the day is approved for payroll, `0` when not."
                                        deleted_at:
                                          type: string
                                          nullable: true
                                          description: Set when the day was deleted in Sequifi. Skip the day when it is not null.
                                        user_attendance_list:
                                          description: Clock events for the day. On an absence day this is one object, not an array.
                                          oneOf:
                                            - type: array
                                              title: Clock events
                                              items:
                                                type: object
                                                properties:
                                                  id:
                                                    type: integer
                                                    description: Event id.
                                                  type:
                                                    type: string
                                                    description: "Event: `clock in`, `lunch`, `end lunch`, `break`, `end break` or `clock out`."
                                                  attendance_type:
                                                    type: string
                                                    enum: [present, lunch, break, clock out, Adjustment, unknown]
                                                    description: Simplified event type. `end lunch` and `end break` map to `present`.
                                                  attendance_date:
                                                    type: string
                                                    nullable: true
                                                    description: Event time, `YYYY-MM-DD HH:MM:SS`. Null on a lunch or break end that is still open.
                                                  attendance_time:
                                                    type: string
                                                    nullable: true
                                                    description: Time until the next event, `HH:MM:SS`. Null on the last event.
                                                  entry_type:
                                                    type: string
                                                    description: How the event was created. `Marketplace-API` for events posted through this API.
                                                  external_reference_id:
                                                    type: string
                                                    nullable: true
                                                    description: Your reference id from POST /v1/timesheet.
                                                  job_id:
                                                    type: string
                                                    nullable: true
                                                    description: Job reference.
                                                  job_name:
                                                    type: string
                                                    nullable: true
                                                    description: Job label.
                                                  labor_rate:
                                                    type: string
                                                    nullable: true
                                                    description: Hourly rate as a decimal string. Set on clock-in events.
                                                  earnings:
                                                    type: string
                                                    nullable: true
                                                    description: Pay for the entry as a decimal string. Set on clock-in events.
                                                  office_id:
                                                    type: integer
                                                    description: Office id, `0` when none.
                                                  deleted_at:
                                                    type: string
                                                    nullable: true
                                                    description: Set when the event was deleted. Skip the event when it is not null.
                                            - type: object
                                              title: Absence
                                              properties:
                                                attendance_type:
                                                  type: string
                                                  description: Always `absent`.
                                                attendance_time:
                                                  type: string
                                                  description: Scheduled length of the day, `HH:MM:SS`.
                                    - type: string
                                      title: Day with nothing recorded
                                      description: The date, `YYYY-MM-DD`.
              example:
                status: 200
                message: "success"
                data:
                  requested_by: "acme"
                  pay_frequency:
                    id: 412
                    pay_period_from: "2026-10-05 00:00:00"
                    pay_period_to: "2026-10-11 00:00:00"
                  timesheets:
                    - day:
                        date: "2026-10-05"
                        user_attendance_list:
                          attendance_type: "absent"
                          attendance_time: "08:00:00"
                    - day:
                        id: 90812
                        user_id: 4821
                        current_time: "04:00:00"
                        lunch_time: "00:00:00"
                        break_time: "00:00:00"
                        is_synced: 1
                        date: "2026-10-06 00:00:00"
                        status: 1
                        deleted_at: null
                        user_attendance_list:
                          - id: 551203
                            type: "clock in"
                            attendance_type: "present"
                            attendance_date: "2026-10-06 08:00:00"
                            attendance_time: "04:00:00"
                            entry_type: "Marketplace-API"
                            external_reference_id: "fieldtool:entry:10482"
                            job_id: "1042"
                            job_name: "Unit turn clean"
                            labor_rate: "20.000"
                            earnings: "80.000"
                            office_id: 0
                            deleted_at: null
                          - id: 551204
                            type: "clock out"
                            attendance_type: "clock out"
                            attendance_date: "2026-10-06 12:00:00"
                            attendance_time: null
                            entry_type: "Marketplace-API"
                            external_reference_id: "fieldtool:entry:10482"
                            job_id: "1042"
                            job_name: "Unit turn clean"
                            labor_rate: null
                            earnings: null
                            office_id: 0
                            deleted_at: null
                    - day: "2026-10-07"
        '400':
          description: Missing or invalid query parameter, or the user's pay period cannot be found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter (for example userId)
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["userId"]
                      allowed_params: ["user_id", "pay_period", "time_format"]
                missing_user_id:
                  summary: user_id not sent
                  value:
                    status: 400
                    message: "user_id is required"
                    data: {}
                missing_pay_period:
                  summary: pay_period not sent
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      pay_period: "required"
                invalid_pay_period:
                  summary: pay_period is not current or previous
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      pay_period: "Invalid. Allowed: current, previous"
                no_pay_frequency:
                  summary: Position has no supported pay frequency
                  value:
                    status: 400
                    message: "Position pay frequency not found"
                    data: {}
                pay_period_not_found:
                  summary: No matching pay period
                  value:
                    status: 400
                    message: "Pay period not found"
                    data: {}
        '401':
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}
    post:
      operationId: addTimesheetEntry
      tags:
        - Timesheet
      summary: Record a time entry
      description: |
        Records time for a user: a whole finished entry (a `checkin` with `end_time` and pay), or a single clock event. For imports from a field tool, send each finished entry as one `checkin` call with `time`, `end_time`, a stable `external_reference_id` and its pay fields.

        **Before you call:**

        - Get the user id from GET /v1/users. Terminated and disabled users are rejected.
        - Check that the user is set up for time: GET /v1/timesheet?user_id=...&pay_period=current should return `200`.
        - Send times as local wall-clock time without a UTC offset, for example `2026-10-06T08:00:00` (see Formats).

        **What happens:**

        - `checkin` finds or creates the user's day for the date of `time`. If `external_reference_id` matches a clock-in already on that same day, it updates that clock-in (time, pay, job) and, when `end_time` is sent, its clock-out. Otherwise it adds a clock-in, plus a clock-out when `end_time` is sent. With `end_time`, the day's worked, lunch and break totals are recalculated.
        - `approved: true` marks the day approved for payroll. It works only with `checkin` and cannot un-approve a day.
        - `start_lunch` and `start_break` need a day that already has a clock-in. They record the start and leave the end open. `stop_lunch` and `stop_break` close it.
        - `checkout` adds a clock-out every time (it never matches by reference id) and recalculates the day's totals.
        - Pay is stored on the clock-in: `labor_rate` × `final_duration` / 3600, rounded to three decimals, or exactly `flat_amount` when sent (then no rate is stored). Pay follows `final_duration`, not the clock times, so send `final_duration` equal to the worked seconds.
        - After a successful `checkin` or `checkout`, Sequifi recalculates the user's hourly pay on the open payroll. It normally shows within minutes; a scheduled catch-up runs every 30 minutes and nightly.

        **Idempotency and retries:**

        - A `checkin` re-sent with the same `external_reference_id` on the same day updates the entry instead of adding one. Without a reference id, every retry adds another entry. `checkout` retries always add another clock-out.
        - A re-post replaces the pay: if it omits `labor_rate`, `final_duration` and `flat_amount`, the entry's pay is cleared. Always resend the whole entry.
        - A re-post cannot add a missing clock-out. If the first post had no `end_time`, a later post with `end_time` and the same reference id updates the clock-in but adds no clock-out, and the entry's hours stay 0. Send `time` and `end_time` together in the first call.
        - Matching is per day. If an entry moves to another date, the old one stays; there is no delete endpoint, so ask an admin to remove it.
        - Send one request at a time per user and day. There is no locking, and parallel first posts for a day can create two day records.

        **Formats:**

        - `time`, `end_time` and `date` accept any date-time string. One with `Z` or an offset is converted to UTC before it is stored: `2026-10-06T18:30:00-06:00` is stored as `2026-10-07 00:30:00`, on the next day. A value without an offset is stored as sent.
        - Response times are `YYYY-MM-DD HH:MM:SS` and totals are `HH:MM:SS`.
        - `Total_earning` in the response is an estimate from the user's profile pay rate, not from the pay you sent, and the response totals cover only the day's last clock-in and clock-out. Read GET /v1/timesheet to check what was stored.

        **Errors:**

        - `400 Invalid JSON body`, `400 user_id is required`, `400 type is required`, `400 Invalid type` (with `data.allowed_types`).
        - `400 flat_amount must be a number greater than or equal to 0`. An empty string is accepted as 0.
        - `404 User not found`, `400 User is terminated and cannot perform this action`, `400 User account is disabled`: stop syncing that user.
        - `400 Invalid time format` and `400 Invalid end_time format`. An invalid `end_time` is reported after the clock-in was already saved; fix the value and ask an admin to check the day, because a re-post cannot add the clock-out.
        - `400 You not checked in today`: a break, lunch or `checkout` was sent for a day with no clock-in.
        - `400 Priority end lunch` (or `end break`): a lunch or break is still open; close it first.
        - `400 Missing Start time`: a stop was sent with no open lunch or break.
        - Rule failures (the last three) return the same `data.timesheet` block as a success.
        - A non-numeric `labor_rate` or `final_duration` returns `500`.

        **Related:**

        - GET /v1/timesheet reads back what was stored.
        - GET /v1/payroll shows the resulting wages in `hourly_salary`.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - user_id
                - type
              properties:
                user_id:
                  type: integer
                  description: User id from GET /v1/users.
                  example: 4821
                type:
                  type: string
                  description: The action. Case-sensitive.
                  enum: [checkin, start_lunch, stop_lunch, start_break, stop_break, checkout]
                  example: checkin
                time:
                  type: string
                  format: date-time
                  description: When the action happened. Send local wall-clock time without an offset. Defaults to now (UTC).
                  example: "2026-10-06T08:00:00"
                date:
                  type: string
                  format: date-time
                  description: Used only when `time` is not sent. Same rules as `time`.
                  example: "2026-10-06T08:00:00"
                end_time:
                  type: string
                  format: date-time
                  description: With `checkin` only. Records the matching clock-out at this time. Send it in the first call for the entry.
                  example: "2026-10-06T12:00:00"
                external_reference_id:
                  type: string
                  description: Your id for this entry. With `checkin`, a re-post with the same id on the same day updates the entry instead of adding one.
                  example: "fieldtool:entry:10482"
                labor_rate:
                  type: number
                  description: Hourly rate in dollars. Ignored when `flat_amount` is sent.
                  example: 20
                final_duration:
                  type: integer
                  description: Worked seconds, net of unpaid breaks. Pay is `labor_rate` × `final_duration` / 3600.
                  example: 14400
                flat_amount:
                  type: number
                  minimum: 0
                  description: Fixed pay in dollars for the entry, for example a fixed-price job. Replaces `labor_rate` × `final_duration`.
                  example: 85
                job_id:
                  type: string
                  description: Job reference shown on the pay stub line.
                  example: "1042"
                job_name:
                  type: string
                  description: Job label shown on the pay stub line.
                  example: "Unit turn clean"
                approved:
                  type: boolean
                  description: With `checkin` only. `true` marks the day approved for payroll.
                  example: true
                office_id:
                  type: integer
                  description: Office id. Defaults to `0`.
                  example: 0
            examples:
              finished_entry:
                summary: A finished hourly entry from a field tool
                value:
                  user_id: 4821
                  type: "checkin"
                  time: "2026-10-06T08:00:00"
                  end_time: "2026-10-06T12:00:00"
                  external_reference_id: "fieldtool:entry:10482"
                  job_id: "1042"
                  job_name: "Unit turn clean"
                  labor_rate: 20
                  final_duration: 14400
                  approved: true
              flat_price_entry:
                summary: A fixed-price job
                value:
                  user_id: 4821
                  type: "checkin"
                  time: "2026-10-07T09:00:00"
                  end_time: "2026-10-07T10:30:00"
                  external_reference_id: "fieldtool:entry:10483"
                  job_id: "1043"
                  job_name: "Carpet clean"
                  flat_amount: 85
                  final_duration: 0
                  approved: true
      responses:
        '200':
          description: Action recorded
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          timesheet:
                            type: object
                            description: Summary of the user's day. Covers only the last clock-in and clock-out pair.
                            properties:
                              checkin:
                                type: string
                                description: Latest clock-in, `YYYY-MM-DD HH:MM:SS`. Absent when there is none.
                              checkout:
                                type: string
                                description: Latest clock-out, `YYYY-MM-DD HH:MM:SS`. Absent when there is none.
                              current_state:
                                type: string
                                description: "Where the day stands, for example `Notcheckin`, `checkin`, `lunch`, `break` or `checkout`."
                              current_state_start_time:
                                type: string
                                description: When the current state started, `YYYY-MM-DD HH:MM:SS`, or an empty string.
                              Total_hour:
                                type: string
                                description: Clock-in to clock-out time, `HH:MM:SS`.
                              Total_hour_work:
                                type: string
                                description: That time minus lunch and breaks, `HH:MM:SS`.
                              Total_lunch:
                                type: string
                                description: Lunch time, `HH:MM:SS`.
                              Total_break:
                                type: string
                                description: Break time, `HH:MM:SS`.
                              Total_earning:
                                type: number
                                description: Estimate from the user's profile pay rate. Not the pay stored for the entry.
              examples:
                finished_entry:
                  summary: checkin with end_time
                  value:
                    status: 200
                    message: "Check-in and check-out successful"
                    data:
                      requestedBy: "acme"
                      timesheet:
                        checkin: "2026-10-06 08:00:00"
                        checkout: "2026-10-06 12:00:00"
                        current_state: "checkout"
                        current_state_start_time: "2026-10-06 12:00:00"
                        Total_hour: "04:00:00"
                        Total_hour_work: "04:00:00"
                        Total_lunch: "00:00:00"
                        Total_break: "00:00:00"
                        Total_earning: 80
                updated_entry:
                  summary: Re-post of an existing entry
                  value:
                    status: 200
                    message: "Timesheet entry updated"
                    data:
                      requestedBy: "acme"
                      timesheet:
                        checkin: "2026-10-06 08:00:00"
                        checkout: "2026-10-06 12:30:00"
                        current_state: "checkout"
                        current_state_start_time: "2026-10-06 12:30:00"
                        Total_hour: "04:30:00"
                        Total_hour_work: "04:30:00"
                        Total_lunch: "00:00:00"
                        Total_break: "00:00:00"
                        Total_earning: 90
        '400':
          description: Invalid request, or the action does not fit the user's day
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_user_id:
                  summary: user_id not sent
                  value:
                    status: 400
                    message: "user_id is required"
                    data:
                      required_fields: ["user_id", "type"]
                invalid_type:
                  summary: Unknown type
                  value:
                    status: 400
                    message: "Invalid type"
                    data:
                      provided_type: "clockin"
                      allowed_types: ["checkin", "start_lunch", "start_break", "stop_lunch", "stop_break", "checkout"]
                bad_flat_amount:
                  summary: Negative or non-numeric flat_amount
                  value:
                    status: 400
                    message: "flat_amount must be a number greater than or equal to 0"
                    data:
                      provided: -5
                terminated:
                  summary: User is terminated
                  value:
                    status: 400
                    message: "User is terminated and cannot perform this action"
                    data:
                      user_id: 4821
                      user_status: "terminated"
                invalid_end_time:
                  summary: end_time cannot be parsed (the clock-in was already saved)
                  value:
                    status: 400
                    message: "Invalid end_time format"
                    data:
                      provided: "noon"
                not_checked_in:
                  summary: Break or checkout with no clock-in that day
                  value:
                    status: 400
                    message: "You not checked in today"
                    data:
                      requestedBy: "acme"
                      timesheet:
                        current_state: "Notcheckin"
                        current_state_start_time: ""
                        Total_hour: "00:00:00"
                        Total_hour_work: "00:00:00"
                        Total_lunch: "00:00:00"
                        Total_break: "00:00:00"
                        Total_earning: 0
        '401':
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        '404':
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data:
                  user_id: 4821
        '500':
          description: Internal server error, including a non-numeric labor_rate or final_duration
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/sales:
    get:
      operationId: listSales
      tags:
        - Sales
      summary: List sales
      description: |
        Lists your company's processed sales (loans, for mortgage companies) with people, product, milestone dates, commission totals and custom field values. Use it to read sales back, or to poll for changes with `updated_after`. Decimal fields come back as strings and dates as timestamps such as `2026-05-01T00:00:00.000Z`, so compare dates on their first 10 characters.

        **Before you call:**

        - Not available to SequiPay companies (`403`).
        - A sale sent with `POST /v1/sales` appears here only after Sequifi has processed it.

        **What happens:**

        - Read-only. Sequifi loads every sale that matches your filters, then returns the page you asked for. An unfiltered call on a company with many sales is slow and can hit the 29-second gateway timeout (`504`); pass a date filter on large pulls.
        - `job_status` is calculated when you read it: `Clawback`, else `Cancelled` (has `date_cancelled`), else `Serviced` (has any milestone date), else `Pending`. A `job_status` you sent with the sale is not returned.
        - `all_milestone[]` has one entry per commission line, so the same milestone can repeat (for example once for the closer and once for the setter). An extra `Recon` entry appears when reconciliation is on. Each entry has a payroll `status`.
        - `milestone_dates[]` lists each milestone date once, in the shape you POST, including on sales with no `all_milestone[]` entries.
        - `commission_lines[]` lists every commission and override line with its payroll status: `paid`, `approved`, `pending` or `do_not_pay`. Before you send a milestone date, check that milestone's lines here so you don't create a second pending line.
        - `custom_field_values` is keyed by field name and shows the sale's current values, including edits made in the app. A field deleted from your configuration is left out.

        **Filtering and paging:**

        - Filters combine with AND. An unknown parameter returns `400` with `invalid_params` and `allowed_params`.
        - `page` defaults to 1 and `per_page` to 50, with no maximum. Neither is validated: `0`, a negative number or text returns `200` with an empty or unexpected page, not an error.
        - Default order is newest sale first. `start_date` and `end_date` apply only when both are sent.
        - To crawl or poll without skipping rows, use `sort_val=ASC` with `updated_after` (the newest `updated_at` you have seen) and `per_page=200`.
        - `search` and `customer_name` treat `%` and `_` as wildcards.

        **Formats:**

        - Dates (`customer_signoff`, `date_cancelled`, `last_service_date`, milestone `date`) are midnight UTC timestamps, for example `2026-05-01T00:00:00.000Z`. `created_at` and `updated_at` are UTC timestamps.
        - `kw`, `epc`, `adders`, `total_override`, the dealer fee fields and the pest and fiber fields are strings. `total_commission` is a string with 2 decimals. `gross_account_value`, milestone `value` and `last_payment` are numbers.
        - `projected_commission` and `projected_override` are flags (`1` projected, `0` final), not amounts.
        - Mortgage `net_epc` is returned multiplied by 100, so it does not equal the value you sent.
        - The list uses `requested_by` and `Sales` (capital S). `GET /v1/sales/{pid}` uses `requestedBy` and `sale`.

        **Errors:**

        - `400 Invalid query parameter(s)`: an unknown parameter.
        - `400 date_from must be in YYYY-MM-DD format` (or `date_to`): not a real `YYYY-MM-DD` date.
        - `400 updated_after must be a date (YYYY-MM-DD) or ISO 8601 timestamp` (same for `updated_before`, `created_after`, `created_before`).
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `403 Forbidden: This endpoint is not available for SequiPay companies`.
        - `500 Database Connection Error` or `Internal Server Error`: retry later.

        **Common mistakes:**

        - Reading an empty page caused by a bad `page` or `per_page` as "no sales".
        - Comparing `job_status` with the value you sent.
        - Comparing dates without cutting them to `YYYY-MM-DD`.
        - Expecting `product_id=1` to return only that product: it also returns sales with no product.

        **Related:**

        - `GET /v1/sales/{pid}`: one sale.
        - `POST /v1/sales`: create or update sales.
        - `GET /v1/users/{id}/commissions`: rates to reconcile commissions against custom field values.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 1 }
          description: "Page number, starting at 1. Not validated: `0`, a negative number or text returns an empty or unexpected page."
        - name: per_page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 50 }
          description: "Sales per page. Default 50, no maximum. Not validated: `0` returns an empty `Sales` array with `last_page: null`."
        - name: start_date
          in: query
          required: false
          schema: { type: string, format: date, example: "2026-01-01" }
          description: "Start of an inclusive range (`YYYY-MM-DD`), used only together with `end_date`; one alone is ignored. Filters `customer_signoff`, or a milestone date when `milestone_date=true`. The format is not checked."
        - name: end_date
          in: query
          required: false
          schema: { type: string, format: date, example: "2026-06-30" }
          description: "End of the inclusive range started by `start_date` (`YYYY-MM-DD`)."
        - name: milestone_date
          in: query
          required: false
          schema: { type: boolean, default: false }
          description: "`true` or `1` makes `start_date` and `end_date` filter a milestone date instead of `customer_signoff`. Name the milestone with `sale_type`."
        - name: sale_type
          in: query
          required: false
          schema: { type: string, example: "Install" }
          description: "With `milestone_date=true`: the milestone `name` or `trigger_date_label` (from `GET /v1/milestones`) whose date must fall in the range. `Cancel Date` filters the cancellation date instead."
        - name: date_from
          in: query
          required: false
          schema: { type: string, format: date, pattern: '^\d{4}-\d{2}-\d{2}$', example: "2026-01-01" }
          description: "Sales with `customer_signoff` on or after this date. Must be a real `YYYY-MM-DD` date, else `400`."
        - name: date_to
          in: query
          required: false
          schema: { type: string, format: date, pattern: '^\d{4}-\d{2}-\d{2}$', example: "2026-06-30" }
          description: "Sales with `customer_signoff` on or before this date. Must be a real `YYYY-MM-DD` date, else `400`."
        - name: updated_after
          in: query
          required: false
          schema: { type: string, example: "2026-05-06T13:43:14Z" }
          description: "Sales changed at or after this time. Send `YYYY-MM-DD` (midnight UTC) or an ISO 8601 timestamp; a timestamp without a zone is read as UTC. For polling, pass the newest `updated_at` you have seen. Distinct from `date_from`, which filters the sale date."
        - name: updated_before
          in: query
          required: false
          schema: { type: string, example: "2026-05-31" }
          description: "Sales changed at or before this time. A bare `YYYY-MM-DD` covers the whole day (through 23:59:59 UTC)."
        - name: created_after
          in: query
          required: false
          schema: { type: string, example: "2026-05-01" }
          description: "Sales created at or after this time. Same formats as `updated_after`."
        - name: created_before
          in: query
          required: false
          schema: { type: string, example: "2026-05-31" }
          description: "Sales created at or before this time. A bare `YYYY-MM-DD` covers the whole day (through 23:59:59 UTC)."
        - name: date_filter
          in: query
          required: false
          schema: { type: string, example: "Install" }
          description: "Only sales that have a given date set: a milestone `name` or `trigger_date_label`, `Cancel Date`, or for pest companies `Service Completion Date` or `Initial Service Date`."
        - name: pid
          in: query
          required: false
          schema: { type: string }
          description: "Exact pid. Use this instead of `GET /v1/sales/{pid}` when the pid contains `/`."
          example: "SALE-10482"
        - name: search
          in: query
          required: false
          schema: { type: string }
          description: "Partial match on pid, customer name, closer 1 name or setter 1 name. `%` and `_` act as wildcards."
        - name: customer_name
          in: query
          required: false
          schema: { type: string }
          description: "Partial match on the customer name. `%` and `_` act as wildcards."
        - name: customer_state
          in: query
          required: false
          schema: { type: string, example: "AZ" }
          description: "Exact match on the customer state."
        - name: product_id
          in: query
          required: false
          schema: { type: string, example: "12" }
          description: "Integer product `id` from `GET /v1/products`. `null` or `unassigned` returns sales with no product; `all` applies no filter. `1` also returns sales with no product."
        - name: product_name
          in: query
          required: false
          schema: { type: string }
          description: "Case-insensitive partial match on the returned `product_name` (`Name - CODE`)."
        - name: install_partner
          in: query
          required: false
          schema: { type: string }
          description: "Case-insensitive partial match on the install partner. Surrounding quotes and spaces are removed, and `%` and `_` match literally."
          example: "Brightline Solar"
        - name: data_source_type
          in: query
          required: false
          schema: { type: string, example: "Marketplace API" }
          description: "Exact match on the sale's source label. No filter applies unless you send it, and `all` also means no filter. Sales sent through this API carry `Marketplace API`."
        - name: job_status
          in: query
          required: false
          schema: { type: string, enum: [Pending, Cancelled, Serviced, Clawback] }
          description: "Case-insensitive. Uses the same calculation as the returned `job_status`. Other values match an older stored status that is not kept up to date."
        - name: is_exempted
          in: query
          required: false
          schema: { type: integer, enum: [0, 1] }
          description: "`1` for sales exempted from clawback, `0` for the rest."
        - name: office_id
          in: query
          required: false
          schema: { type: integer }
          description: "Sales where closer 1 or 2, or setter 1 or 2, is a user whose current office is this one (not the office at the time of the sale). `all` applies no filter."
        - name: user_id
          in: query
          required: false
          schema: { type: integer }
          description: "Sales where this user is closer 1 or 2, or setter 1 or 2. With `office_id`, the user must also be in that office."
        - name: closer1_id
          in: query
          required: false
          schema: { type: integer }
          description: "Exact closer 1 user id."
        - name: setter1_id
          in: query
          required: false
          schema: { type: integer }
          description: "Exact setter 1 user id."
        - name: sort
          in: query
          required: false
          schema: { type: string, enum: [last_payment, product_name, product, job_status, status, customer_name] }
          description: "Sorts all matching sales before paging. `product` is `product_name` and `status` is `job_status`. Values compare as text, so `last_payment` sorts `100` before `20`. Other values are ignored."
        - name: sort_val
          in: query
          required: false
          schema: { type: string, enum: [ASC, DESC], default: DESC }
          description: "`ASC` or `DESC` (default), case-insensitive. Also sets the default order (oldest or newest sale first) when `sort` is not sent."
      responses:
        "200":
          description: One page of sales.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requested_by:
                            type: string
                            description: Name of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned, as sent.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Number of sales that match the filters.
                          last_page:
                            type: integer
                            nullable: true
                            description: Last page number. `0` when nothing matches; `null` when `per_page` is `0`.
                          Sales:
                            type: array
                            description: The sales on this page.
                            items:
                              $ref: '#/components/schemas/Sale'
              example:
                status: 200
                message: "Successfully"
                data:
                  requested_by: "acme"
                  current_page: 1
                  per_page: 50
                  total: 1
                  last_page: 1
                  Sales:
                    - id: 7731
                      pid: "SALE-10482"
                      customer_name: "Alex Morgan"
                      data_source_type: "Marketplace API"
                      job_status: "Serviced"
                      product_id: 12
                      product_code: "SOL-ROOF"
                      product_name: "Solar Rooftop - SOL-ROOF"
                      org_product_id: "SOL-ROOF"
                      customer_state: "AZ"
                      customer_address: "1200 Desert Willow Rd"
                      customer_address_2: null
                      customer_city: "Phoenix"
                      customer_zip: "85001"
                      customer_phone: "555-010-4821"
                      customer_email: "alex.morgan@example.com"
                      last_milestone:
                        name: "Site Survey"
                        trigger: "Site Survey Date"
                        value: 500
                        date: "2026-05-08T00:00:00.000Z"
                      last_payment: 500
                      all_milestone:
                        - name: "Site Survey"
                          trigger: "Site Survey Date"
                          milestone_id: 41
                          value: 500
                          date: "2026-05-08T00:00:00.000Z"
                          is_projected: 0
                          status: "paid"
                        - name: "Install"
                          trigger: "Install Date"
                          milestone_id: 42
                          value: 750
                          date: null
                          is_projected: 1
                          status: "projected"
                      milestone_dates:
                        - product_id: 12
                          milestone_id: 41
                          milestone_date: "2026-05-08"
                        - product_id: 12
                          milestone_id: 42
                          milestone_date: null
                      commission_lines:
                        - type: "commission"
                          milestone: "m1"
                          milestone_id: 41
                          user_id: 101
                          amount: 500
                          status: "paid"
                          pay_period_from: "2026-05-04"
                          pay_period_to: "2026-05-10"
                      total_commission: "1250.00"
                      projected_commission: 1
                      total_override: "0"
                      projected_override: 1
                      kw: "7.2"
                      epc: "3.8500"
                      net_epc: 3.2
                      adders: "1100"
                      gross_account_value: 27720
                      service_completed: null
                      date_cancelled: null
                      customer_signoff: "2026-05-01T00:00:00.000Z"
                      install_partner: "Brightline Solar"
                      service_schedule: null
                      length_of_agreement: null
                      initial_service_cost: null
                      subscription_payment: null
                      card_on_file: null
                      auto_pay: null
                      bill_status: null
                      balance_age: null
                      last_service_date: null
                      dealer_fee_amount: "4158"
                      dealer_fee_percentage: "0.15"
                      is_exempted: 0
                      sales_type: "Sales"
                      created_at: "2026-05-01T16:05:43.000Z"
                      updated_at: "2026-05-08T18:12:09.000Z"
                      mark_account_status_name: "Paid"
                      closer1_detail:
                        id: 4821
                        first_name: "Jordan"
                        last_name: "Reyes"
                        dismiss: 0
                        terminate: 0
                        contract_ended: 0
                        stop_payroll: 0
                      closer2_detail: null
                      setter1_detail:
                        id: 5310
                        first_name: "Casey"
                        last_name: "Lee"
                        dismiss: 0
                        terminate: 0
                        contract_ended: 0
                        stop_payroll: 0
                      setter2_detail: null
                      custom_field_values:
                        Roof Type: "Shingle"
                        Panel Count: 18
        "400":
          description: Unknown query parameter or invalid date filter.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_query_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["filter"]
                      allowed_params: ["per_page", "page", "pid", "search", "start_date", "end_date", "milestone_date", "sale_type", "office_id", "user_id", "customer_name", "product_id", "product_name", "customer_state", "install_partner", "date_filter", "data_source_type", "closer1_id", "setter1_id", "job_status", "date_from", "date_to", "is_exempted", "sort", "sort_val", "updated_after", "updated_before", "created_after", "created_before"]
                invalid_date_from:
                  summary: date_from is not a real YYYY-MM-DD date
                  value:
                    status: 400
                    message: "date_from must be in YYYY-MM-DD format"
                    data: {}
                invalid_updated_after:
                  summary: updated_after is not a date or timestamp
                  value:
                    status: 400
                    message: "updated_after must be a date (YYYY-MM-DD) or ISO 8601 timestamp"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        "403":
          description: SequiPay companies cannot use this endpoint.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Forbidden: This endpoint is not available for SequiPay companies"
                data: {}
        "500":
          description: Server error. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                internal:
                  summary: Unexpected error
                  value:
                    status: 500
                    message: "Internal Server Error"
                    data: {}
                db_connection:
                  summary: Sequifi could not reach your company's data. `details` is a technical message; do not parse it.
                  value:
                    status: 500
                    message: "Database Connection Error"
                    data:
                      details: "Connection timed out"

    post:
      operationId: upsertSales
      tags:
        - Sales
      summary: Create or update sales
      description: |
        Creates or updates sales (loans, for mortgage companies) in bulk, keyed by your own `pid`. A new `pid` creates a sale and a known `pid` updates it, so resending a batch never creates duplicates. A `200` or `201` means the records were queued, not that the sale changed: confirm with `GET /v1/sales/{pid}` after processing, and read the Posting Sales guide before building a bulk sync.

        **Before you call:**

        - Not available to SequiPay companies (`403`).
        - Know your company's vertical (Solar, Turf, Roofing, Pest, Fiber or Mortgage). It decides which fields are required (see `PostSaleRecord` and the Vertical Labels page). No endpoint returns it, so ask your Sequifi admin.
        - Look up the values you will send: product `id` from `GET /v1/products`, milestone ids from `GET /v1/milestones?product=<id>`, custom field ids from `GET /v1/custom-fields?type=sales`, and user ids or emails from `GET /v1/users`.
        - Set `"partial_success": true` so one bad record does not reject the whole request.

        **What happens:**

        - Every `pid` is checked first. A missing, non-string, too long (over 255 characters) or duplicate `pid` rejects the whole request with `400`, even with `partial_success`. Leading and trailing spaces are trimmed.
        - A new `pid` must pass every check: required fields, formats, custom fields and your vertical's required fields. It is queued as a new sale.
        - A known `pid` is an update: only the fields you send are merged into the sale, and no field is required. A field you leave out, including the product, closer, setter and location, keeps its current value. Milestone dates are the exception: the list you send replaces the sale's list.
        - Accepted records are saved together and then processed in the background: the sale is created or updated and commissions are recalculated. This usually takes minutes; a large run can take an hour or more, and a sale whose payroll is being finalized waits until that payroll completes.
        - Processing can still reject a queued record, for example a milestone date earlier than `customer_signoff`, or a change to a paid milestone, product, closer or setter. No API reports this: the sale stays missing or unchanged in `GET /v1/sales/{pid}`.
        - People, product, milestone and custom field values are matched as described on each `PostSaleRecord` field. Unknown top-level fields are dropped and listed in `data.warnings[]`.
        - A product that matches nothing is listed in `data.warnings[]`. A new sale then goes to your company's default product (its lowest-numbered product), and an update keeps the sale's current product.
        - `data.warnings[]` is not a complete list of what was not applied. An unmatched closer, setter or email leaves that person off the sale and is not reported. Check `data.sales[]`: `closer1_id` should be present.

        **Idempotency and retries:**

        - `pid` is the key. A retried batch never creates a second sale; if the first attempt was saved, the retry takes the update path.
        - `400`: nothing was saved. Fix every record listed in `data.errors` (`Record [i]` is the position in your `data` array) and resend. Without `partial_success`, checks run in stages and stop at the first stage with errors, so new errors can appear on the next attempt.
        - `500`, `502`, `503`, `504` or a timeout: resend the same batch after a pause (for example 2, 4, 8 and 16 seconds). A `504` can arrive after the batch was saved; resending it is safe.
        - With `partial_success`, an update (known `pid`) that fails a format check is listed in `rejected[]` and is not saved. Fix it and resend it.
        - Send one request at a time. Two requests in flight with the same new `pid` can both queue it.
        - Recommended size and pace: up to 200 records per request and no more than 30 requests a minute. These are not enforced per request, but larger batches risk the 29-second gateway timeout.

        **Formats:**

        - `pid` is a string. A JSON number such as `12345` is rejected; send `"12345"`.
        - Dates are `YYYY-MM-DD` and must be real calendar dates. A date such as `2026-02-30` or `2026-13-01` in `milestone_dates`, `customer_signoff`, `last_service_date`, `date_cancelled` or `scheduled_install` is rejected with a 400.
        - Numbers can be JSON numbers or numeric strings. `kw` and `gross_account_value` also accept `$`, commas and spaces; a value that cannot be read is saved as `0`, and so is `null` on an update. `kw` keeps every decimal you send (up to 10), so a battery adder sent as `0.00001` is saved as `0.00001`; exponent form such as `1e-5` is accepted.
        - `card_on_file` and `auto_pay` must be JSON booleans.
        - In the response, dates in `data.sales[]` are timestamps such as `2026-05-01T00:00:00.000Z`.

        **Errors:**

        - `400 Bad Request: Expected a JSON object with a "data" array`: the body is not a JSON object.
        - `400 Bad Request: "data" must be a non-empty array of records`.
        - `400 Validation Failed`: `data.errors[]` lists each problem as `Record [i]: <message> (field: <name>)`.
        - `400 Custom Field Validation Failed`: an unknown custom field, or a number or date field with a wrong value, on a new record without `partial_success`.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `403 Forbidden: This endpoint is not available for SequiPay companies`.
        - `404 Record not found`: rare. A held copy was cleared while the request ran; nothing was saved. Resend.
        - `500 Database Connection Error`, `Database Insert Error`, `Database Execution Error` or `Internal Server Error`: nothing was saved. Resend.

        **Common mistakes:**

        - Sending `sale_date`, `trigger_date`, `product_code` or `mp_base_payment_amount`. They are accepted and ignored, with no warning. The sale date goes in `customer_signoff`.
        - Sending only the milestone that changed. `milestone_dates` replaces the sale's dates and is read by position: send every milestone of the product's schema, in order, with `milestone_date: null` for the ones not reached yet.
        - Sending the schema `id` from `GET /v1/milestones` as `milestone_id`. Send the ids from its `milestones[]` array.
        - Expecting `rep_email` to set the rep. It assigns no one; use `closer_email` or `closer1_id`.
        - Sending `data_source_type`. Leave it out.
        - Treating `201` as success without reading the body. With `partial_success`, a batch in which every record was rejected still returns `201` with `recordsProcessed: 0`.

        **Related:**

        - The Posting Sales guide: the full bulk-sync procedure, including how to confirm each sale.
        - `GET /v1/sales/{pid}`: confirm a sale after processing.
        - `GET /v1/products`, `GET /v1/milestones`, `GET /v1/custom-fields?type=sales`, `GET /v1/users`: the values to send.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - data
              properties:
                data:
                  type: array
                  description: The sales to create or update, one record each. At least one record. Each `pid` may appear only once.
                  minItems: 1
                  items:
                    $ref: '#/components/schemas/PostSaleRecord'
                partial_success:
                  type: boolean
                  default: false
                  description: >
                    `true` (or the string `"true"`) checks each record on its
                    own: valid records are queued and invalid ones come back in
                    `data.rejected[]`. Any other value, or leaving it out,
                    rejects the whole request with `400` at the first check
                    stage that finds an error. Errors in the body shape or in a
                    `pid` reject the whole request either way. Recommended for
                    every request.
            examples:
              single_solar:
                summary: One Solar sale (works for a new sale and for an update)
                value:
                  partial_success: true
                  data:
                    - pid: "SALE-10482"
                      customer_name: "Alex Morgan"
                      customer_signoff: "2026-05-01"
                      customer_email: "alex.morgan@example.com"
                      customer_phone: "555-010-4821"
                      customer_address: "1200 Desert Willow Rd"
                      customer_city: "Phoenix"
                      customer_state: "AZ"
                      customer_zip: "85001"
                      location_code: "AZ"
                      product_id: 12
                      kw: 7.2
                      epc: 3.85
                      net_epc: 3.2
                      gross_account_value: 27720
                      adders: 1100
                      dealer_fee_amount: 4158
                      dealer_fee_percentage: 0.15
                      install_partner: "Brightline Solar"
                      closer_email: "jordan.reyes@example.com"
                      setter_email: "casey.lee@example.com"
                      milestone_dates:
                        - product_id: 12
                          milestone_id: 41
                          milestone_date: "2026-05-08"
                        - product_id: 12
                          milestone_id: 42
                          milestone_date: null
                      custom_field_values:
                        "7": "Shingle"
                        "9": 18
              batch_partial_success:
                summary: Two Solar sales in one request, with partial_success
                value:
                  partial_success: true
                  data:
                    - pid: "SALE-10483"
                      customer_name: "Jamie Carter"
                      customer_signoff: "2026-05-03"
                      customer_state: "AZ"
                      location_code: "AZ"
                      product_id: 12
                      kw: 8.4
                      closer1_id: 4821
                      milestone_dates:
                        - product_id: 12
                          milestone_id: 41
                          milestone_date: null
                        - product_id: 12
                          milestone_id: 42
                          milestone_date: null
                    - pid: "SALE-10484"
                      customer_name: "Riley Nguyen"
                      customer_signoff: "2026-05-04"
                      customer_state: "NV"
                      location_code: "NV"
                      product_id: 12
                      kw: 6.1
                      closer_email: "jordan.reyes@example.com"
                      milestone_dates:
                        - product_id: 12
                          milestone_id: 41
                          milestone_date: "2026-05-11"
                        - product_id: 12
                          milestone_id: 42
                          milestone_date: null
              pest_sale:
                summary: One Pest sale
                value:
                  partial_success: true
                  data:
                    - pid: "PC-55120"
                      customer_name: "Taylor Brooks"
                      customer_signoff: "2026-04-14"
                      customer_state: "TX"
                      gross_account_value: 899
                      product_id: 5
                      closer_email: "riley.chen@example.com"
                      service_schedule: "Quarterly"
                      length_of_agreement: "12 months"
                      initial_service_cost: 149
                      subscription_payment: 62.5
                      card_on_file: true
                      auto_pay: true
                      service_completed: 1
                      bill_status: "Current"
                      balance_age: 0
                      last_service_date: "2026-04-21"
                      milestone_dates:
                        - product_id: 5
                          milestone_id: 17
                          milestone_date: "2026-04-21"
              mortgage_loan:
                summary: One Mortgage loan, no milestones reached yet
                value:
                  partial_success: true
                  data:
                    - pid: "LN-2026-0042"
                      customer_name: "Morgan Ellis"
                      customer_signoff: "2026-05-15"
                      customer_state: "TX"
                      location_code: "TX"
                      gross_account_value: 350000
                      sale_product_name: "Conventional"
                      closer_email: "morgan.hayes@example.com"
                      external_job_status: "Clear to Close"
              with_external_workers:
                summary: Mortgage loan with extra credited people
                value:
                  partial_success: true
                  data:
                    - pid: "LN-2026-0050"
                      customer_name: "Drew Patel"
                      customer_signoff: "2026-05-10"
                      customer_state: "TX"
                      location_code: "TX"
                      gross_account_value: 412000
                      sale_product_name: "Conventional"
                      closer_email: "morgan.hayes@example.com"
                      external_workers:
                        - email: "dana.kim@example.com"
                          type: 2
                        - name: "Sam Ortiz"
                          type: 3
              clear_external_workers:
                summary: Same loan, removing every extra credited person
                value:
                  partial_success: true
                  data:
                    - pid: "LN-2026-0050"
                      customer_name: "Drew Patel"
                      customer_signoff: "2026-05-10"
                      customer_state: "TX"
                      location_code: "TX"
                      gross_account_value: 412000
                      sale_product_name: "Conventional"
                      closer_email: "morgan.hayes@example.com"
                      external_workers: []
      responses:
        '201':
          description: New records queued, or every record rejected. Check `recordsProcessed` and `rejected[]`.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/PostSalesResult'
              examples:
                created:
                  summary: One new sale queued
                  value:
                    status: 201
                    message: "Sales Data Processed Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 1
                      recordsPatched: 0
                      recordsProcessed: 1
                      recordsRejected: 0
                      rejected: []
                      sales:
                        - id: 90412
                          pid: "SALE-10482"
                          customer_name: "Alex Morgan"
                          customer_signoff: "2026-05-01T00:00:00.000Z"
                          customer_state: "AZ"
                          location_code: "AZ"
                          kw: "7.2"
                          gross_account_value: 27720
                          product_id: 12
                          product_code: "sol-roof"
                          product: "Solar Rooftop"
                          closer1_id: 4821
                          setter1_id: 5310
                          sales_rep_email: "jordan.reyes@example.com"
                          sales_rep_name: "Jordan Reyes"
                          data_source_type: "Marketplace API"
                          custom_field_values:
                            Roof Type: "Shingle"
                            Panel Count: 18
                partial_success_mixed:
                  summary: One record queued, one rejected
                  value:
                    status: 201
                    message: "Sales Data Processed Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 1
                      recordsPatched: 0
                      recordsProcessed: 1
                      recordsRejected: 1
                      rejected:
                        - index: 1
                          pid: "SALE-10484"
                          messages:
                            - "Customer State is required for Solar (field: customer_state)"
                      sales:
                        - id: 90413
                          pid: "SALE-10483"
                          customer_name: "Jamie Carter"
                          customer_signoff: "2026-05-03T00:00:00.000Z"
                          product_id: 12
                          product_code: "sol-roof"
                          product: "Solar Rooftop"
                          closer1_id: 4821
                          data_source_type: "Marketplace API"
                          custom_field_values: {}
                all_rejected:
                  summary: Every record rejected, still 201
                  value:
                    status: 201
                    message: "Sales Data Processed Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 0
                      recordsPatched: 0
                      recordsProcessed: 0
                      recordsRejected: 2
                      rejected:
                        - index: 0
                          pid: "SALE-10483"
                          messages:
                            - "customer_name is required (field: customer_name)"
                        - index: 1
                          pid: "SALE-10484"
                          messages:
                            - "Sale Date is required for Solar (field: customer_signoff)"
                      sales: []
                with_warning:
                  summary: Queued, with an ignored field reported in warnings
                  value:
                    status: 201
                    message: "Sales Data Processed Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 1
                      recordsPatched: 0
                      recordsProcessed: 1
                      recordsRejected: 0
                      rejected: []
                      warnings:
                        - "Record [0]: field 'milestone_date' is not a recognized top-level field and was ignored. Milestone dates must be sent inside the `milestone_dates[]` array as { product_id, milestone_id, milestone_date }."
                      sales:
                        - id: 90414
                          pid: "SALE-10485"
                          customer_name: "Sydney Ward"
                          customer_signoff: "2026-05-05T00:00:00.000Z"
                          product_id: 12
                          product_code: "sol-roof"
                          product: "Solar Rooftop"
                          closer1_id: 4821
                          data_source_type: "Marketplace API"
                          custom_field_values: {}
        '200':
          description: Every saved record was an update; no new record was queued.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        $ref: '#/components/schemas/PostSalesResult'
              examples:
                all_updates:
                  summary: Two updates
                  value:
                    status: 200
                    message: "Sales Data Updated Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 0
                      recordsPatched: 2
                      recordsProcessed: 2
                      recordsRejected: 0
                      rejected: []
                      sales:
                        - id: 90415
                          pid: "SALE-10483"
                          customer_name: "Jamie Carter"
                          customer_signoff: "2026-05-03T00:00:00.000Z"
                          product_id: 12
                          closer1_id: 4821
                          data_source_type: "Marketplace API"
                          custom_field_values: {}
                        - id: 90416
                          pid: "SALE-10484"
                          customer_name: "Riley Nguyen"
                          customer_signoff: "2026-05-04T00:00:00.000Z"
                          product_id: 12
                          closer1_id: 4821
                          data_source_type: "Marketplace API"
                          custom_field_values: {}
                update_with_warning:
                  summary: Update with an unknown custom field name dropped
                  value:
                    status: 200
                    message: "Sales Data Updated Successfully"
                    data:
                      requestedBy: "acme"
                      recordsInserted: 0
                      recordsPatched: 1
                      recordsProcessed: 1
                      recordsRejected: 0
                      rejected: []
                      warnings:
                        - "Record [0]: custom_field_values field name \"Roof Typ\" does not exist and was ignored. Send the numeric field id from GET /v1/custom-fields?type=sales."
                      sales:
                        - id: 90417
                          pid: "SALE-10482"
                          customer_name: "Alex Morgan"
                          customer_signoff: "2026-05-01T00:00:00.000Z"
                          product_id: 12
                          closer1_id: 4821
                          data_source_type: "Marketplace API"
                          custom_field_values:
                            Roof Type: "Shingle"
        '400':
          description: Nothing was saved. Fix the records in `data.errors[]` and resend.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          errors:
                            type: array
                            description: 'One message per problem, as `Record [i]: <message> (field: <name>)`. Absent for body-shape errors.'
                            items: { type: string }
              examples:
                invalid_payload:
                  summary: The body is not a JSON object with a data array
                  value:
                    status: 400
                    message: "Bad Request: Expected a JSON object with a \"data\" array"
                    data: {}
                empty_data:
                  summary: data is missing or empty
                  value:
                    status: 400
                    message: "Bad Request: \"data\" must be a non-empty array of records"
                    data: {}
                missing_pid:
                  summary: pid is missing, empty or not a string (whole request rejected)
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: pid is required and must be a non-empty string (field: pid)"
                pid_too_long:
                  summary: pid is longer than 255 characters
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: pid max 255 characters (field: pid)"
                duplicate_pid:
                  summary: The same pid twice in one request
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [1]: duplicate pid \"SALE-10482\" in request (field: pid)"
                missing_customer_name:
                  summary: customer_name missing on a new record
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: customer_name is required (field: customer_name)"
                bad_date_format:
                  summary: A date not in YYYY-MM-DD form
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: customer_signoff must be Y-m-d format (field: customer_signoff)"
                invalid_email:
                  summary: An email field with a bad format
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: closer_email must be a valid email (field: closer_email)"
                bad_milestone_entry:
                  summary: A milestone_dates entry without a milestone_id
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0] milestone_dates[1]: milestone_id is required and must be an integer (field: milestone_dates[1].milestone_id)"
                vertical_required:
                  summary: A field your vertical requires is missing
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: Sale Date is required for Solar (field: customer_signoff)"
                        - "Record [0]: Customer State is required for Solar (field: customer_state)"
                unknown_custom_field:
                  summary: Custom field name does not exist
                  value:
                    status: 400
                    message: "Custom Field Validation Failed"
                    data:
                      errors:
                        - "Record [0]: custom_field_values field name \"Roof Typ\" does not exist"
                invalid_cf_number:
                  summary: Number custom field with a non-numeric value
                  value:
                    status: 400
                    message: "Custom Field Validation Failed"
                    data:
                      errors:
                        - "Record [0]: custom_field_values[\"9\"] — expected number, got \"eighteen\""
                invalid_cf_date:
                  summary: Date custom field not in YYYY-MM-DD form
                  value:
                    status: 400
                    message: "Custom Field Validation Failed"
                    data:
                      errors:
                        - "Record [0]: custom_field_values[\"11\"] — expected date (YYYY-MM-DD), got \"07/15/2026\""
        '401':
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        '403':
          description: SequiPay companies cannot use this endpoint.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Forbidden: This endpoint is not available for SequiPay companies"
                data: {}
        '404':
          description: Rare. A held copy was cleared mid-request; nothing was saved. Resend.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Record not found"
                data:
                  details: "pid \"SALE-10482\" row missing at merge time"
        '500':
          description: Server error; nothing was saved. Resend the same batch.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                db_connection:
                  summary: Sequifi could not reach your company's data
                  value:
                    status: 500
                    message: "Database Connection Error"
                    data:
                      details: "Connection timed out"
                save_failed:
                  summary: The save failed and was rolled back
                  value:
                    status: 500
                    message: "Database Execution Error"
                    data:
                      details: "Technical detail"
                internal:
                  summary: Unexpected error
                  value:
                    status: 500
                    message: "Internal Server Error"
                    data: {}

  /v1/integration-raw-data:
    post:
      operationId: ingestIntegrationRawData
      tags:
        - Integrations
      summary: Store raw integration records
      description: |
        Stores raw records from a connected source system (a CRM or lender system) with change detection, and returns the records that are new or changed so you can map them into sales. It creates no sales and starts no processing: send the mapped records to `POST /v1/sales` afterwards.

        **Before you call:**

        - Pick the `integration_type` for your source. Each type has a natural key that identifies a record: `encompass` `loan_id`, `enerflo` `pid`, `arive` `arive_loan_id`, `jobnimbus` `jnid`, `pipesolar` `pid`, `proline` `project_id`, `byte` `byte_loan_id`, `sonar` and `gaiia` `account_id`, `subhub` `pid`, `hubspot` `hs_object_id`, `monday` `item_id`, `gohighlevel` `opportunity_id`, `pocomos` `pcc_id`, `acculynx` `job_id`.
        - Records are kept per company, type and key. Sending a key again updates that record.

        **What happens:**

        - Every record is checked first. Any error rejects the whole request with `400` and nothing is stored.
        - Fixed-field types (`encompass`, `enerflo`, `arive`, `jobnimbus`, `pipesolar`, `proline`, `byte`): only the fields listed for the type are stored; other fields are dropped without a warning. The whole request is saved in one transaction.
        - Flexible types (`sonar`, `gaiia`, `subhub`, `hubspot`, `monday`, `gohighlevel`, `pocomos`, `acculynx`): every field you send is stored, including misspelled ones. Records are saved in groups, not in one transaction, so a failed request can leave some records stored. A record over 400 KB is rejected.
        - New key: the record is stored. On fixed-field types, fields you leave out are stored empty.
        - Known key: a field you leave out keeps its stored value, `null` clears it, and any other value replaces it. Some date fields cannot be cleared once set (`sale_date` on most types, `status_date_won` on `proline`, `signed_date` on `hubspot`): `null` or `""` keeps the stored date.
        - Changes are found field by field after normalizing values. Date-time values are compared by date only, so a change to the time of day alone counts as unchanged.
        - `changed_records` holds the new records, then the updated ones, each as stored after the merge. Unchanged records are only counted, unless you send `return_all: true` (fixed-field types only), which adds them at the end.

        **Idempotency and retries:**

        - Resending identical data stores nothing new and reports the records as `unchanged`. Retrying after a `500` or a timeout is safe and completes a partly stored request.

        **Formats:**

        - Natural keys can be strings or numbers. They are trimmed, stored as strings (at most 255 characters), and must be unique within the request.
        - Date fields listed for a type must start with a real `YYYY-MM-DD` date; only the first 10 characters are checked.
        - On fixed-field types, send date-time fields such as `modified_date_time` as `YYYY-MM-DD HH:MM:SS`. A value ending in `Z` fails the whole request with `500`, and a value with an offset (`-04:00`) is converted to the server's time zone.
        - JobNimbus dates are Unix timestamps in seconds, not `YYYY-MM-DD`.
        - `data` holds at most 1,000 records. About 100 records per request stays well inside the 29-second gateway timeout.

        **Errors:**

        - `400 Bad Request: Expected a JSON object with integration_type and data array`: the body is not a JSON object.
        - `400 Bad Request: integration_type is required` or `Bad Request: unknown integration_type`: `data.supported` lists the valid types.
        - `400 Bad Request: "data" must be a non-empty array of records`.
        - `400 Bad Request: data array exceeds 1000 records — chunk client-side`: `data.received` and `data.max` give the counts.
        - `400 Validation Failed`: `data.errors[]` lists each problem (missing or duplicate key, bad date, record not an object, record too large).
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `500 Database Connection Error` or `Internal Server Error`: retry. `data.details` is a technical message; do not parse it.

        **Common mistakes:**

        - Expecting sales to appear. Map `changed_records` and send them to `POST /v1/sales`.
        - Leaving out a field the store needs on a new fixed-field record (for example `pid` on `encompass`, `total_loan_amount` on `byte` and `arive`, or the fee fields on `arive`). The whole request fails with `500`.
        - Sending `return_all` for a flexible type. It is ignored.

        **Related:**

        - `POST /v1/sales`: send the mapped sales.
        - `GET /v1/products`, `GET /v1/milestones`, `GET /v1/users`: values for the mapping.
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - integration_type
                - data
              properties:
                integration_type:
                  type: string
                  enum: [encompass, enerflo, arive, jobnimbus, pipesolar, proline, byte, sonar, gaiia, subhub, hubspot, monday, gohighlevel, pocomos, acculynx]
                  description: >
                    Source system. Case-insensitive; surrounding spaces are
                    removed. `encompass`, `enerflo`, `arive`, `jobnimbus`,
                    `pipesolar`, `proline` and `byte` store a fixed list of
                    fields. `sonar`, `gaiia`, `subhub`, `hubspot`, `monday`,
                    `gohighlevel`, `pocomos` and `acculynx` store every field sent.
                data:
                  type: array
                  description: >
                    1 to 1,000 raw records. The shape depends on
                    `integration_type`. Only the natural key is required; every
                    other field is optional.
                  minItems: 1
                  maxItems: 1000
                  items:
                    oneOf:
                      - $ref: '#/components/schemas/EncompassRawDataRecord'
                      - $ref: '#/components/schemas/EnerfloRawDataRecord'
                      - $ref: '#/components/schemas/AriveRawDataRecord'
                      - $ref: '#/components/schemas/JobNimbusRawDataRecord'
                      - $ref: '#/components/schemas/PipeSolarRawDataRecord'
                      - $ref: '#/components/schemas/ProlineRawDataRecord'
                      - $ref: '#/components/schemas/ByteRawDataRecord'
                      - $ref: '#/components/schemas/FlexibleRawDataRecord'
                return_all:
                  type: boolean
                  default: false
                  description: >
                    `true` also returns unchanged records at the end of
                    `changed_records`, so you can map and resend them (for
                    example after adding a rep who was missing). They are still
                    counted as `unchanged` and not rewritten. Fixed-field types
                    only; ignored for flexible types.
            examples:
              enerflo_batch:
                summary: Enerflo, one solar install
                value:
                  integration_type: enerflo
                  data:
                    - pid: "EF-20931"
                      customer_id: "67890"
                      proposal_id: "PROP-2026-0042"
                      product_name: "Solar Rooftop"
                      customer_name: "Alex Morgan"
                      customer_email: "alex.morgan@example.com"
                      customer_phone: "555-010-4821"
                      customer_address: "1200 Desert Willow Rd"
                      customer_city: "Phoenix"
                      customer_state: "AZ"
                      location_code: "AZ"
                      customer_zip: "85001"
                      install_partner: "Brightline Solar"
                      gross_account_value: 27720
                      kw: 7.2
                      epc: 3.85
                      net_epc: 3.2
                      dealer_fee: 4158
                      dealer_fee_percentage: 0.15
                      adders_total: 1100
                      system_cost_base_adders: 28820
                      job_status: "Install Scheduled"
                      sale_date: "2026-05-01"
                      m1_date: "2026-05-08"
                      m2_date: null
                      m3_date: null
                      sales_rep_id: "4521"
                      sales_rep_name: "Jordan Reyes"
                      sales_rep_email: "jordan.reyes@example.com"
                      setter_id: "3310"
                      setter_name: "Casey Lee"
                      setter_email: "casey.lee@example.com"
              encompass_batch:
                summary: Encompass, one loan
                value:
                  integration_type: encompass
                  data:
                    - loan_id: "95f78daa-bcc7-4f08-88ed-eb29a811d57d"
                      pid: "LN-2026-0042"
                      customer_name: "Morgan Ellis"
                      customer_email: "morgan.ellis@example.com"
                      customer_mobile: "5550104821"
                      customer_address1: "88 Live Oak Ln"
                      customer_city: "Austin"
                      customer_state: "TX"
                      customer_zip: "78701"
                      base_amount: "350000"
                      gross_revenue: "3500"
                      credit_report_fee: "75"
                      loan_status: "Funded"
                      sale_date: "2026-05-15"
                      product_name: "Conventional"
                      mlo_email: "morgan.hayes@example.com"
                      loa_email: "dana.kim@example.com"
                      processor_email: "sam.ortiz@example.com"
              arive_batch:
                summary: Arive, one loan
                value:
                  integration_type: arive
                  data:
                    - arive_loan_id: "AR-2026-0001"
                      lender_loan_identifier: "LL-001"
                      lender_name: "Example Lending"
                      mortgage_type: "Conventional"
                      borrower_name: "Morgan Ellis"
                      borrower_email: "morgan.ellis@example.com"
                      borrower_state: "TX"
                      borrower_city: "Austin"
                      borrower_zip: "78701"
                      total_loan_amount: "350000"
                      dealer_fee: "0"
                      dealer_fee_percentage: "0"
                      sow_adder_fee: "0"
                      compensation_type: "Broker"
                      loan_status: "Funded"
                      sale_date: "2026-05-15"
                      loan_originator_email: "morgan.hayes@example.com"
                      loan_officer_assistant_email: "dana.kim@example.com"
              byte_batch:
                summary: Byte, one funded loan
                value:
                  integration_type: byte
                  data:
                    - byte_loan_id: "1027892"
                      lender_loan_identifier: "23848"
                      lender_name: "Example Lending"
                      mortgage_type: "VA"
                      borrower_name: "Drew Patel"
                      borrower_email: "drew.patel@example.com"
                      borrower_phone: "5550107733"
                      borrower_address: "410 Cedar St"
                      borrower_city: "Salem"
                      borrower_state: "OR"
                      borrower_zip: "97301"
                      total_loan_amount: "295000.00"
                      broker_compensation: "7618.38"
                      product_name: "Lender"
                      compensation_type: "Lender"
                      credit_report_fee: "137.50"
                      loan_status: "Funded"
                      loan_originator_email: "morgan.hayes@example.com"
                      loan_processor_email: "sam.ortiz@example.com"
                      loan_officer_assistant_email: "dana.kim@example.com"
                      sale_date: "2026-06-12"
                      m1_date: "2026-06-12"
                      m2_date: "2026-06-24"
                      cancel_date: null
                      modified_date_time: "2026-06-24 15:10:43"
                      create_date_time: "2026-05-02 12:13:05"
              jobnimbus_batch:
                summary: JobNimbus, one job (dates in Unix seconds)
                value:
                  integration_type: jobnimbus
                  data:
                    - jnid: "abc123def456"
                      customer_id: "cust-987"
                      customer_name: "Taylor Brooks"
                      customer_email: "taylor.brooks@example.com"
                      address_line1: "456 Maple Street"
                      city: "Austin"
                      state_text: "TX"
                      zip: "78701"
                      system_size_kw: "8.5"
                      gross_ppw: 3.92
                      net_ppw: 3.40
                      contract_price: 33320
                      dealer_fee: 4500
                      status: "signed"
                      signed_contract_date: 1741017600
                      cancel_date: null
                      m1_date: 1741104000
                      m2_date: null
                      sales_closer_email: "jordan.reyes@example.com"
                      sales_closer_name: "Jordan Reyes"
                      sales_setter_name: "Casey Lee"
              pipesolar_batch:
                summary: Pipe Solar, one solar install
                value:
                  integration_type: pipesolar
                  data:
                    - pid: "PS-2026-0001"
                      contract_sign_date: "2026-03-10"
                      customer_name: "Jamie Carter"
                      customer_email: "jamie.carter@example.com"
                      customer_state: "AZ"
                      location_code: "AZ"
                      install_partner: "Brightline Solar"
                      epc: "3.85"
                      gross_account_value: "30800"
                      kw: "8.0"
                      job_status: "Site Survey Complete"
                      sale_product_name: "Solar Rooftop"
                      sales_rep_email: "jordan.reyes@example.com"
                      setter_email: "casey.lee@example.com"
                      sale_date: "2026-03-15"
                      m1_date: "2026-03-20"
                      m2_date: null
              hubspot_batch:
                summary: HubSpot, flexible type (every field is stored)
                value:
                  integration_type: hubspot
                  data:
                    - hs_object_id: "38848"
                      dealname: "Brooks Residence"
                      dealstage: "Closed Won"
                      closer_email: "jordan.reyes@example.com"
                      firstname: "Taylor"
                      lastname: "Brooks"
                      email: "taylor.brooks@example.com"
                      customer_state: "Florida"
                      signed_date: "2026-04-11"
                      total_loan_amount: "25075.60"
              sonar_batch:
                summary: Sonar, flexible type (every field is stored)
                value:
                  integration_type: sonar
                  data:
                    - account_id: "ACC-100245"
                      customer_name: "Riley Nguyen"
                      customer_email: "riley.nguyen@example.com"
                      plan: "fiber-1g"
                      mrr: 79.99
                      status: "active"
      responses:
        '200':
          description: Records stored. Read `changed_records` for what to map.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          integration_type:
                            type: string
                            description: The type used, lower case.
                          stats:
                            type: object
                            description: Counts for this request.
                            properties:
                              inserted:
                                type: integer
                                description: New keys stored.
                              updated:
                                type: integer
                                description: Known keys with at least one changed field.
                              unchanged:
                                type: integer
                                description: Known keys with no change.
                              totalProcessed:
                                type: integer
                                description: Records in the request.
                          changed_records:
                            type: array
                            description: >
                              New records, then updated records, then (with
                              `return_all`) unchanged records. Fixed-field types
                              return every stored field of the type, with
                              `null` for empty ones; flexible types return the
                              fields stored for the record.
                            items:
                              type: object
              example:
                status: 200
                message: "Integration Raw Data Processed Successfully"
                data:
                  integration_type: enerflo
                  stats:
                    inserted: 1
                    updated: 0
                    unchanged: 1
                    totalProcessed: 2
                  changed_records:
                    - pid: "EF-20931"
                      customer_id: "67890"
                      proposal_id: "PROP-2026-0042"
                      product_name: "Solar Rooftop"
                      customer_name: "Alex Morgan"
                      customer_email: "alex.morgan@example.com"
                      customer_phone: "555-010-4821"
                      customer_address: "1200 Desert Willow Rd"
                      customer_city: "Phoenix"
                      customer_state: "AZ"
                      location_code: "AZ"
                      customer_zip: "85001"
                      install_partner: "Brightline Solar"
                      gross_account_value: 27720
                      kw: 7.2
                      epc: 3.85
                      net_epc: 3.2
                      dealer_fee: 4158
                      dealer_fee_percentage: 0.15
                      adders_total: 1100
                      system_cost_base_adders: 28820
                      job_status: "Install Scheduled"
                      sale_date: "2026-05-01"
                      cancel_date: null
                      m1_date: "2026-05-08"
                      m2_date: null
                      m3_date: null
                      sales_rep_id: "4521"
                      sales_rep_name: "Jordan Reyes"
                      sales_rep_email: "jordan.reyes@example.com"
                      setter_id: "3310"
                      setter_name: "Casey Lee"
                      setter_email: "casey.lee@example.com"
        '400':
          description: Nothing was stored. The message says what to fix.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_type:
                  summary: integration_type missing
                  value:
                    status: 400
                    message: "Bad Request: integration_type is required"
                    data:
                      supported: [encompass, enerflo, arive, jobnimbus, pipesolar, proline, byte, sonar, gaiia, subhub, hubspot, monday, gohighlevel, pocomos, acculynx]
                unknown_type:
                  summary: integration_type not supported
                  value:
                    status: 400
                    message: "Bad Request: unknown integration_type"
                    data:
                      integration_type: "salesforce"
                      supported: [encompass, enerflo, arive, jobnimbus, pipesolar, proline, byte, sonar, gaiia, subhub, hubspot, monday, gohighlevel, pocomos, acculynx]
                empty_data:
                  summary: data missing or empty
                  value:
                    status: 400
                    message: "Bad Request: \"data\" must be a non-empty array of records"
                    data: {}
                too_many:
                  summary: More than 1,000 records
                  value:
                    status: 400
                    message: "Bad Request: data array exceeds 1000 records — chunk client-side"
                    data:
                      received: 1500
                      max: 1000
                missing_key:
                  summary: A record without its natural key
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: pid is required and must be a non-empty string or number"
                duplicate_key:
                  summary: The same key twice in one request
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [2]: duplicate pid \"EF-20931\" in request"
                bad_date:
                  summary: A date field that is not a real date
                  value:
                    status: 400
                    message: "Validation Failed"
                    data:
                      errors:
                        - "Record [0]: sale_date must be a valid Y-m-d calendar date"
        '401':
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        '500':
          description: Server error. Some flexible-type records may be stored; resending is safe.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data:
                  details: "Technical detail"

  /v1/sales/{pid}:
    get:
      operationId: getSale
      tags:
        - Sales
      summary: Get a sale
      description: |
        Returns one processed sale by its `pid`, with the same fields as an item of `GET /v1/sales`. Use it to confirm that a sale sent with `POST /v1/sales` was processed. A `404` shortly after a successful POST is normal: the sale appears only after background processing.

        **Before you call:**

        - Not available to SequiPay companies (`403`).
        - URL-encode the pid. A pid that contains `/` may not reach this route; use `GET /v1/sales?pid=<pid>` instead.

        **What happens:**

        - Read-only. Returns `data.sale` (singular) and `data.requestedBy`, with no paging fields.
        - The pid must match exactly.
        - `job_status` is calculated when you read it, and `all_milestone[]` has one entry per commission line (see `GET /v1/sales`).

        **Formats:**

        - Dates are midnight UTC timestamps such as `2026-05-01T00:00:00.000Z`; compare the first 10 characters with the date you sent.
        - Mortgage `net_epc` is returned multiplied by 100. See `Sale` for the type of every field.

        **Errors:**

        - `400 Cannot use query parameters when fetching a single sale by pid`: any query parameter was sent.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `403 Forbidden: This endpoint is not available for SequiPay companies`.
        - `404 Sale not found`: the pid is unknown, still queued, or was rejected during processing. The API cannot tell these apart.
        - `500`: retry later.

        **Common mistakes:**

        - Resending a record because this returns `404` right after the POST. Wait. If it is still `404` a few hours later, processing rejected it: send the pid to Sequifi support.
        - Comparing `job_status`, or mortgage `net_epc`, with what you sent.
        - Expecting exactly one `all_milestone[]` entry per milestone. Entries repeat per commission line, and a sale with no commission lines has none. Compare dates with `milestone_dates[]` instead.

        **Related:**

        - `POST /v1/sales`: create or update the sale.
        - `GET /v1/sales`: list and filter sales.
      security:
        - bearerAuth: []
      parameters:
        - name: pid
          in: path
          required: true
          schema: { type: string }
          description: "Your sale id, exactly as sent on `POST /v1/sales`. URL-encode it."
          example: "SALE-10482"
      responses:
        "200":
          description: The sale.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential that made the call.
                          sale:
                            $ref: '#/components/schemas/Sale'
              example:
                status: 200
                message: "Successfully"
                data:
                  requestedBy: "acme"
                  sale:
                    id: 7731
                    pid: "SALE-10482"
                    customer_name: "Alex Morgan"
                    data_source_type: "Marketplace API"
                    job_status: "Serviced"
                    product_id: 12
                    product_code: "SOL-ROOF"
                    product_name: "Solar Rooftop - SOL-ROOF"
                    org_product_id: "SOL-ROOF"
                    customer_state: "AZ"
                    customer_address: "1200 Desert Willow Rd"
                    customer_address_2: null
                    customer_city: "Phoenix"
                    customer_zip: "85001"
                    customer_phone: "555-010-4821"
                    customer_email: "alex.morgan@example.com"
                    last_milestone:
                      name: "Site Survey"
                      trigger: "Site Survey Date"
                      value: 500
                      date: "2026-05-08T00:00:00.000Z"
                    last_payment: 500
                    all_milestone:
                      - name: "Site Survey"
                        trigger: "Site Survey Date"
                        milestone_id: 41
                        value: 500
                        date: "2026-05-08T00:00:00.000Z"
                        is_projected: 0
                        status: "paid"
                      - name: "Install"
                        trigger: "Install Date"
                        milestone_id: 42
                        value: 750
                        date: null
                        is_projected: 1
                        status: "projected"
                    milestone_dates:
                      - product_id: 12
                        milestone_id: 41
                        milestone_date: "2026-05-08"
                      - product_id: 12
                        milestone_id: 42
                        milestone_date: null
                    commission_lines:
                      - type: "commission"
                        milestone: "m1"
                        milestone_id: 41
                        user_id: 101
                        amount: 500
                        status: "paid"
                        pay_period_from: "2026-05-04"
                        pay_period_to: "2026-05-10"
                    total_commission: "1250.00"
                    projected_commission: 1
                    total_override: "0"
                    projected_override: 1
                    kw: "7.2"
                    epc: "3.8500"
                    net_epc: 3.2
                    adders: "1100"
                    gross_account_value: 27720
                    service_completed: null
                    date_cancelled: null
                    customer_signoff: "2026-05-01T00:00:00.000Z"
                    install_partner: "Brightline Solar"
                    service_schedule: null
                    length_of_agreement: null
                    initial_service_cost: null
                    subscription_payment: null
                    card_on_file: null
                    auto_pay: null
                    bill_status: null
                    balance_age: null
                    last_service_date: null
                    dealer_fee_amount: "4158"
                    dealer_fee_percentage: "0.15"
                    is_exempted: 0
                    sales_type: "Sales"
                    created_at: "2026-05-01T16:05:43.000Z"
                    updated_at: "2026-05-08T18:12:09.000Z"
                    mark_account_status_name: "Paid"
                    closer1_detail:
                      id: 4821
                      first_name: "Jordan"
                      last_name: "Reyes"
                      dismiss: 0
                      terminate: 0
                      contract_ended: 0
                      stop_payroll: 0
                    closer2_detail: null
                    setter1_detail:
                      id: 5310
                      first_name: "Casey"
                      last_name: "Lee"
                      dismiss: 0
                      terminate: 0
                      contract_ended: 0
                      stop_payroll: 0
                    setter2_detail: null
                    custom_field_values:
                      Roof Type: "Shingle"
                      Panel Count: 18
        "400":
          description: A query parameter was sent with the pid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "Cannot use query parameters when fetching a single sale by pid"
                data: {}
        "401":
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        "403":
          description: SequiPay companies cannot use this endpoint.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Forbidden: This endpoint is not available for SequiPay companies"
                data: {}
        "404":
          description: The pid is unknown, still queued, or was rejected during processing.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Sale not found"
                data: {}
        "500":
          description: Server error. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/sales/{pid}/recalculate:
    post:
      operationId: recalculateSale
      tags:
        - Sales
      summary: Recalculate a sale
      description: |
        Recalculates one sale's commissions, milestones and overrides from its current data and the current pay plans. It is the same as pressing Recalculate on the sale in the web app. Use it after you change something a sale's pay depends on, such as a worker's position or a pay plan, when the sale itself did not change.

        **Before you call:**

        - You do not need this after `POST /v1/sales`. A sale you send is recalculated as part of processing.
        - URL-encode the pid. A pid that contains `/` cannot be used here.
        - The sale needs a closer. Not available to SequiPay companies (`403`).
        - Send no body. Anything you send is ignored.

        **What happens:**

        - Sequifi recalculates the sale and answers when it is done, usually within a few seconds.
        - Amounts already paid are never edited in place. If a recalculated amount differs from what was paid, the difference is recorded the same way as for a recalculation in the web app.
        - If the sale's final milestone was paid more than three months ago, that milestone is not re-evaluated. Change it in the web app if you need to.
        - Some tiered sales are priced only when their tier period closes. For those the call returns `200` with `skipped: true` and changes nothing.
        - Recalculation is refused while a payroll that includes the sale is being finalized or paid (`409`). Retry after the payroll completes.

        **Limits (per company):**

        - One recalculation at a time. A call made while another is running returns `429` with `data.code` `RECALCULATION_IN_PROGRESS`.
        - The same sale can be recalculated once every 10 minutes. An earlier call returns `429` with `data.code` `COOLDOWN` and `data.last_run`, which says when the last run started and how it ended.
        - At most 20 calls a minute and 300 an hour, including calls refused with `404`, `409` or `422`. Over the limit returns `429` with `data.code` `RATE_LIMITED`.
        - Every `429` and `503` carries a `Retry-After` header and `data.retry_after_seconds`. Wait that many seconds before trying again. To recalculate many sales, send them one at a time and wait for each answer.

        **Idempotency and retries:**

        - Recalculating twice gives the same result, so a retry is safe.
        - After a `504`, the recalculation may still finish. Retry the same call: it returns `429` `COOLDOWN`, and `data.last_run.outcome` says whether the first attempt landed (`recalculated`, `skipped`, `failed`, or `running` if it has not finished).

        **Errors:**

        - `400` `pid is required`, or the pid is longer than 255 characters.
        - `403` with `data.code` `NOT_AVAILABLE`: SequiPay company.
        - `404` with `data.code` `SALE_NOT_FOUND`: no sale with that pid. A sale sent with `POST /v1/sales` appears only after processing.
        - `409` with `data.code` `PAYROLL_IN_PROGRESS` (retry later) or `RECON_FINALIZED` (the sale has finalized reconciliation amounts and can no longer be recalculated).
        - `422` with `data.code` `CLOSER_MISSING`: assign a closer first.
        - `429`: one of the limits above. Read `data.code` and `Retry-After`.
        - `500` with `data.code` `RECALCULATION_FAILED`, or `Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502` `The tenant returned an unreadable response` or `Could not reach the tenant`: retry later.
        - `503` with `data.code` `LIMITER_UNAVAILABLE`: temporarily unavailable, retry after `Retry-After`. A `503` with no `data.code` means your company is not set up for this endpoint yet. Contact Sequifi support.
        - `504`: no answer in time. See retries above.
        - Errors passed back from Sequifi carry `data.code`, `data.pid` and `data.requestedBy`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Related:**

        - `GET /v1/sales/{pid}` to read the sale and its commission lines after the recalculation.
      security:
        - bearerAuth: []
      parameters:
        - name: pid
          in: path
          required: true
          schema:
            type: string
            maxLength: 255
          description: The sale's pid, as sent with `POST /v1/sales` and returned by `GET /v1/sales`. URL-encoded.
          example: "16653"
      responses:
        '200':
          description: Recalculated, or skipped because the sale is priced when its tier period closes
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          pid:
                            type: string
                            description: The sale.
                          recalculated:
                            type: boolean
                            description: True when the sale was recalculated.
                          skipped:
                            type: boolean
                            description: True when the sale is priced at tier period close and nothing changed.
                          duration_ms:
                            type: integer
                            description: How long the recalculation took, in milliseconds.
                          next_allowed_at:
                            type: string
                            format: date-time
                            description: Earliest time this sale can be recalculated over the API again.
              examples:
                recalculated:
                  summary: Recalculated
                  value:
                    status: 200
                    message: "Sale recalculated."
                    data:
                      requestedBy: "acme"
                      pid: "16653"
                      recalculated: true
                      skipped: false
                      duration_ms: 4312
                      next_allowed_at: "2026-10-09T15:10:00+00:00"
                skipped:
                  summary: Priced at tier period close
                  value:
                    status: 200
                    message: "Skipped: this sale is priced by the retroactive-tier period-close engine, so Recalculate does not apply to it."
                    data:
                      requestedBy: "acme"
                      pid: "16653"
                      recalculated: false
                      skipped: true
                      duration_ms: 38
                      next_allowed_at: "2026-10-09T15:10:00+00:00"
        '400':
          description: Missing or over-long pid
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 400
                message: "pid is required"
                data: {}
        '401':
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        '403':
          description: Not available for SequiPay companies
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Sale recalculation is not available for SequiPay companies."
                data:
                  requestedBy: "acme"
                  code: "NOT_AVAILABLE"
                  pid: "16653"
        '404':
          description: No sale with that pid
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "No sale with pid 16653."
                data:
                  requestedBy: "acme"
                  code: "SALE_NOT_FOUND"
                  pid: "16653"
        '409':
          description: A payroll with this sale is being finalized or paid, or its reconciliation is finalized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                payroll_in_progress:
                  summary: Payroll in progress (retry later)
                  value:
                    status: 409
                    message: "A payroll that includes this sale is being finalized or executed. Try again after it completes."
                    data:
                      requestedBy: "acme"
                      code: "PAYROLL_IN_PROGRESS"
                      pid: "16653"
                recon_finalized:
                  summary: Reconciliation finalized (permanent)
                  value:
                    status: 409
                    message: "This sale has reconciliation amounts that are finalized or executed, so it can no longer be recalculated."
                    data:
                      requestedBy: "acme"
                      code: "RECON_FINALIZED"
                      pid: "16653"
        '422':
          description: The sale has no closer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 422
                message: "This sale has no closer. Assign a closer before recalculating it."
                data:
                  requestedBy: "acme"
                  code: "CLOSER_MISSING"
                  pid: "16653"
        '429':
          description: A limit was reached. Wait for `Retry-After` seconds.
          headers:
            Retry-After:
              description: Seconds to wait before trying again.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                cooldown:
                  summary: Same sale recalculated within the last 10 minutes
                  value:
                    status: 429
                    message: "This sale was recalculated over the API recently. It can be recalculated again in 412 seconds."
                    data:
                      requestedBy: "acme"
                      code: "COOLDOWN"
                      pid: "16653"
                      retry_after_seconds: 412
                      last_run:
                        started_at: "2026-10-09T15:00:00+00:00"
                        finished_at: "2026-10-09T15:00:04+00:00"
                        outcome: "recalculated"
                in_progress:
                  summary: Another recalculation is running
                  value:
                    status: 429
                    message: "Another sale is being recalculated over the API for this tenant. Recalculations run one at a time."
                    data:
                      requestedBy: "acme"
                      code: "RECALCULATION_IN_PROGRESS"
                      pid: "16653"
                      retry_after_seconds: 5
                rate_limited:
                  summary: Per-minute or per-hour limit reached
                  value:
                    status: 429
                    message: "This tenant has reached its limit for sale recalculations over the API. Try again in 37 seconds."
                    data:
                      requestedBy: "acme"
                      code: "RATE_LIMITED"
                      pid: "16653"
                      retry_after_seconds: 37
        '500':
          description: The sale could not be recalculated
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The sale could not be recalculated."
                data:
                  requestedBy: "acme"
                  code: "RECALCULATION_FAILED"
                  pid: "16653"
        '502':
          description: Sequifi could not complete the request. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 502
                message: "Could not reach the tenant"
                data:
                  pid: "16653"
        '503':
          description: Temporarily unavailable (retry after `Retry-After`), or your company is not set up for this endpoint
          headers:
            Retry-After:
              description: Seconds to wait before trying again. Present on `LIMITER_UNAVAILABLE`.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unavailable:
                  summary: Temporarily unavailable
                  value:
                    status: 503
                    message: "Sale recalculation over the API is temporarily unavailable. Try again shortly."
                    data:
                      requestedBy: "acme"
                      code: "LIMITER_UNAVAILABLE"
                      pid: "16653"
                      retry_after_seconds: 60
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This tenant is not configured for sale recalculation over the API. Contact Sequifi support."
                    data: {}
        '504':
          description: No answer in time. The recalculation may still finish; retry and read `data.last_run.outcome`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The recalculation may still finish. Retry this call: while the sale is cooling down it returns 429 with data.last_run.outcome, which says whether the first attempt landed."
                data:
                  pid: "16653"


  /v1/custom-fields:
    get:
      operationId: listCustomFields
      tags:
        - Custom Fields
      summary: List custom fields
      description: |
        Lists your company's custom field definitions for one `type`: `sales`, `payroll`, `employee`, `employee_admin` or `onboarding`. Use `type=sales` to get the field `id`s to send in `custom_field_values` on `POST /v1/sales`. Answer options for select and multi-select fields are not returned.

        **What happens:**

        - Read-only: definitions, not values. Values are written through the endpoint that owns the record: `POST /v1/sales` (`custom_field_values`, keyed by field `id` or exact name), `POST /v1/payroll` (`custom_fields`, by exact `field_name`) and `POST /v1/onboarding` (`custom_fields`, by exact `field_name`).
        - `sales`: active fields only, ordered by `sort_order` then name. Each field has `can_archive`, plus `usage_details` when commission, override or upfront settings use it. Archived fields are hidden here, but `POST /v1/sales` still accepts values for them and `GET /v1/sales` still returns them.
        - `payroll`: every field, by `id`.
        - `employee`: fields that are not deleted, by `id`. `attribute_option` is the list of options.
        - `employee_admin`: admin-only fields that are not deleted, by `id`. Use these ids in `employee_admin_only_fields` on `POST /v1/users`.
        - `onboarding`: fields that are not deleted, by `id`, in a different shape: `data.onboard[]` and `data.custom_lead_form_settings`, with no paging fields.

        **Filtering and paging:**

        - `type` is required and case-insensitive. Other query parameters are ignored, not rejected.
        - `page` (default 1) and `per_page` (default 20, maximum 500) must be whole numbers in range, else `400`. The `onboarding` type checks them and then returns every field.
        - `last_page` is at least `1`, even when there are no fields.

        **Formats:**

        - Sales field `type` is `text`, `number`, `date` or `multi_select`. A single-select field is a `text` field with configured options, and this endpoint cannot tell it apart from free text.
        - `created_at` and `updated_at` are UTC timestamps.

        **Errors:**

        - `400 Bad Request: ?type= is required. Valid values: sales, payroll, onboarding, employee, employee_admin`.
        - `400 Bad Request: invalid type "<type>". Valid values: sales, payroll, onboarding, employee, employee_admin`.
        - `400 Bad Request: page must be a positive integer` or `Bad Request: per_page must be a positive integer between 1 and 500`.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `500 Database Connection Error`, `Database Query Error` or `Internal Server Error`: retry later. `data.details` is a technical message; do not parse it.

        **Common mistakes:**

        - Keying `custom_field_values` on `POST /v1/sales` by a name with different capitals or spaces. Names must match exactly; send the numeric `id`.
        - Sending values for fields with `is_calculated: true`. Sequifi calculates them.

        **Related:**

        - `POST /v1/sales`: write sales custom field values.
        - `GET /v1/sales`: read values back, keyed by field name.
      security:
        - bearerAuth: []
      parameters:
        - name: type
          in: query
          required: true
          schema:
            type: string
            enum: [sales, payroll, onboarding, employee, employee_admin]
          description: "Which fields to list. Case-insensitive."
          example: sales
        - name: page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 1 }
          description: "Page number, starting at 1. Must be a whole number, else `400`."
        - name: per_page
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 500, default: 20 }
          description: "Fields per page. Default 20, maximum 500. Must be a whole number in range, else `400`."
      responses:
        "200":
          description: Field definitions for the requested type.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          type:
                            type: string
                            description: The type listed. Not returned for `onboarding`.
                          current_page:
                            type: integer
                            description: Page returned. Not returned for `onboarding`.
                          per_page:
                            type: integer
                            description: Page size used. Not returned for `onboarding`.
                          total:
                            type: integer
                            description: Number of fields of this type. Not returned for `onboarding`.
                          last_page:
                            type: integer
                            description: Last page number, at least `1`. Not returned for `onboarding`.
                          custom_fields:
                            type: array
                            description: The fields on this page. The item shape below is for `type=sales`; see the examples for `payroll` and `employee`.
                            items:
                              $ref: '#/components/schemas/SalesCustomField'
                          onboard:
                            type: array
                            description: Onboarding fields. Returned only for `type=onboarding`.
                            items:
                              type: object
                          custom_lead_form_settings:
                            type: object
                            description: Onboarding form settings. Returned only for `type=onboarding`.
              examples:
                sales_response:
                  summary: "type=sales"
                  value:
                    status: 200
                    message: "Custom fields fetched successfully"
                    data:
                      type: sales
                      current_page: 1
                      per_page: 20
                      total: 2
                      last_page: 1
                      custom_fields:
                        - id: 7
                          name: "Roof Type"
                          type: "text"
                          field_category: "custom_sales"
                          is_calculated: false
                          is_available_in_position: false
                          formula: null
                          visiblecustomer: false
                          status: true
                          sort_order: 1
                          created_at: "2026-01-05T17:20:00.000Z"
                          updated_at: "2026-03-02T15:45:10.000Z"
                          can_archive: true
                        - id: 9
                          name: "Panel Count"
                          type: "number"
                          field_category: "custom_sales"
                          is_calculated: false
                          is_available_in_position: true
                          formula: null
                          visiblecustomer: true
                          status: true
                          sort_order: 2
                          created_at: "2026-01-05T17:21:00.000Z"
                          updated_at: "2026-03-02T15:45:10.000Z"
                          can_archive: false
                          usage_details:
                            position_commissions:
                              count: 2
                              positions:
                                - id: 1
                                  name: "Sales Rep"
                                - id: 2
                                  name: "Manager"
                payroll_response:
                  summary: "type=payroll"
                  value:
                    status: 200
                    message: "Custom fields fetched successfully"
                    data:
                      type: payroll
                      current_page: 1
                      per_page: 20
                      total: 1
                      last_page: 1
                      custom_fields:
                        - id: 10
                          field_name: "Car Allowance"
                          worked_type: "hourly"
                          payment_type: "addition"
                          status: 1
                employee_response:
                  summary: "type=employee"
                  value:
                    status: 200
                    message: "Custom fields fetched successfully"
                    data:
                      type: employee
                      current_page: 1
                      per_page: 20
                      total: 2
                      last_page: 1
                      custom_fields:
                        - id: 1
                          configuration_id: 1
                          field_name: "Shirt Size"
                          field_type: "dropdown"
                          field_required: "required"
                          attribute_option: ["Small", "Medium", "Large", "Extra Large"]
                          height_value: null
                          is_deleted: 0
                          created_at: "2025-10-16T08:14:27.000Z"
                          updated_at: "2026-02-15T18:49:35.000Z"
                        - id: 7
                          configuration_id: 1
                          field_name: "Shoe Size"
                          field_type: "number"
                          field_required: "required"
                          attribute_option: null
                          height_value: null
                          is_deleted: 0
                          created_at: "2025-11-29T18:06:39.000Z"
                          updated_at: "2026-02-15T18:49:35.000Z"
                onboarding_response:
                  summary: "type=onboarding (different shape, no paging)"
                  value:
                    status: 200
                    message: "Custom fields fetched successfully"
                    data:
                      onboard:
                        - id: 22
                          configuration_id: null
                          field_name: "Years of Experience"
                          field_type: "number"
                          field_required: "optional"
                          type: "onboard"
                          attribute_option: null
                          attribute_option_rating: null
                          height_value: null
                          is_deleted: 0
                          scored: 0
                      custom_lead_form_settings:
                        id: 1
                        rating_status: 0
                        created_at: "2026-01-02T00:00:00.000Z"
                        updated_at: "2026-06-01T00:00:00.000Z"
        "400":
          description: Missing or invalid `type`, `page` or `per_page`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                missing_type:
                  summary: type missing
                  value:
                    status: 400
                    message: "Bad Request: ?type= is required. Valid values: sales, payroll, onboarding, employee"
                    data: {}
                invalid_type:
                  summary: type not supported
                  value:
                    status: 400
                    message: "Bad Request: invalid type \"leads\". Valid values: sales, payroll, onboarding, employee"
                    data: {}
                invalid_page:
                  summary: page not a positive whole number
                  value:
                    status: 400
                    message: "Bad Request: page must be a positive integer"
                    data: {}
                invalid_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "Bad Request: per_page must be a positive integer between 1 and 500"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        "500":
          description: Server error. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                db_connection:
                  summary: Sequifi could not reach your company's data
                  value:
                    status: 500
                    message: "Database Connection Error"
                    data:
                      details: "Connection timed out"
                db_query:
                  summary: The lookup failed
                  value:
                    status: 500
                    message: "Database Query Error"
                    data:
                      details: "Technical detail"

  /v1/products:
    get:
      operationId: listProducts
      tags:
        - Products
      summary: List products
      description: |
        Lists your company's active products so you can map each product or package in your system to a Sequifi product. Send the integer `id` as `product_id` on `POST /v1/sales`. The string field called `product_id` in this response is the product code, not the id.

        **What happens:**

        - Read-only. Only active products that are not deleted are listed.
        - `product_codes` lists every code `POST /v1/sales` matches for each product, in lowercase. Send a code as listed; case does not matter. `POST /v1/sales` also matches the product name.

        **Filtering and paging:**

        - `name` is a partial match on the product name; `%` and `_` act as wildcards.
        - `page` (default 1) must be a positive whole number and `per_page` (default 100) a whole number from 1 to 200, else `400`. An unknown parameter returns `400`.
        - Ordered by name, then `id`. `last_page` is `0` when nothing matches.

        **Formats:**

        - `effective_date` is `YYYY-MM-DD`. `created_date` and `updated_date` are `YYYY-MM-DD HH:MM:SS` with no time zone.

        **Errors:**

        - `400 Invalid query parameter(s)`: an unknown parameter; `data.allowed_params` lists the valid ones.
        - `400 page must be a positive integer` or `per_page must be an integer between 1 and 200`.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `500 Internal Server Error`: retry later.

        **Common mistakes:**

        - Posting a sale with the `id` of a product that is not in this list (inactive or deleted). A new sale then lands on your company's default product, and `data.warnings[]` says so. Ask your Sequifi admin first.
        - Mapping only to `product_id`. A product can have several codes; check `product_codes` before reporting a product as unmapped.
        - Matching by name when two products share a name. `POST /v1/sales` picks one of them; send the `id`.

        **Related:**

        - `GET /v1/products/{id}`: one product, including inactive ones.
        - `GET /v1/milestones?product=<id>`: the milestones for a product.
        - `POST /v1/sales`: send `product_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 1 }
          description: "Page number, starting at 1. Must be a positive whole number, else `400`."
        - name: per_page
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 200, default: 100 }
          description: "Products per page. Default 100, maximum 200. Must be a whole number in range, else `400`."
        - name: name
          in: query
          required: false
          schema: { type: string }
          description: "Partial match on the product name. `%` and `_` act as wildcards."
          example: "Solar"
      responses:
        "200":
          description: One page of active products.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential that made the call.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Page size used.
                          total:
                            type: integer
                            description: Number of active products that match.
                          last_page:
                            type: integer
                            description: Last page number. `0` when nothing matches.
                          products:
                            type: array
                            description: Products on this page, ordered by name.
                            items:
                              $ref: '#/components/schemas/Product'
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 100
                  total: 2
                  last_page: 1
                  products:
                    - id: 14
                      product_id: "SOL-GRND"
                      product_codes: ["sol-grnd", "sol-ground"]
                      name: "Solar Ground Mount"
                      description: "Ground-mounted residential system"
                      effective_date: "2026-01-01"
                      created_date: "2026-01-02 09:00:00"
                      updated_date: "2026-04-02 11:15:00"
                      status: active
                    - id: 12
                      product_id: "SOL-ROOF"
                      product_codes: ["sol-roof"]
                      name: "Solar Rooftop"
                      description: "Roof-mounted residential system"
                      effective_date: "2026-01-01"
                      created_date: "2026-01-02 09:00:00"
                      updated_date: "2026-05-12 14:30:00"
                      status: active
        "400":
          description: Unknown parameter, or invalid `page` or `per_page`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                unknown_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: [category]
                      allowed_params: [page, per_page, name]
                invalid_page:
                  summary: page not a positive whole number
                  value:
                    status: 400
                    message: "page must be a positive integer"
                    data: {}
                invalid_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "per_page must be an integer between 1 and 200"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        "500":
          description: Server error. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/products/{id}:
    get:
      operationId: getProduct
      tags:
        - Products
      summary: Get a product
      description: |
        Returns one product by its integer `id`, whether active or inactive (deleted products return `404`). Use it to check a stored product mapping. An inactive product returned here is not matched by `id` on `POST /v1/sales`: a new sale sent with that id lands on your company's default product, with a warning in `data.warnings[]`.

        **What happens:**

        - Read-only. Same fields as an item of `GET /v1/products`, under `data.product`. `status` is `active` or `inactive`.

        **Errors:**

        - `400 Cannot use query parameters when fetching a single product by id`: any query parameter was sent (checked first).
        - `400 Invalid product id`: the id is not a positive whole number.
        - `401`: missing, invalid or expired token. The body is `{"message": "Unauthorized"}`.
        - `404 Product not found`: no product has this id, or it was deleted.
        - `500 Internal Server Error`: retry later.

        **Related:**

        - `GET /v1/products`: the active product list.
        - `POST /v1/sales`: send `product_id`.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: integer, minimum: 1 }
          description: The product's integer `id` from `GET /v1/products`.
          example: 12
      responses:
        "200":
          description: The product.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential that made the call.
                          product:
                            $ref: '#/components/schemas/Product'
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  product:
                    id: 12
                    product_id: "SOL-ROOF"
                    product_codes: ["sol-roof"]
                    name: "Solar Rooftop"
                    description: "Roof-mounted residential system"
                    effective_date: "2026-01-01"
                    created_date: "2026-01-02 09:00:00"
                    updated_date: "2026-05-12 14:30:00"
                    status: active
        "400":
          description: Invalid id, or query parameters sent with the id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: The id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid product id"
                    data: {}
                query_params_with_id:
                  summary: A query parameter was sent with the id
                  value:
                    status: 400
                    message: "Cannot use query parameters when fetching a single product by id"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The body has only `message`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GatewayError'
              example:
                message: "Unauthorized"
        "404":
          description: No product has this id, or it was deleted.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "Product not found"
                data: {}
        "500":
          description: Server error. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/commissions:
    get:
      operationId: listUserCommissions
      tags:
        - Commissions
      summary: List a user's commission rates
      description: |
        Returns a user's commission rate card, the same settings as the Commission tab on their profile in Sequifi, grouped by product and split by role (closer, setter, self-gen). These are rates, not money earned; use GET /v1/users/{id}/earnings for amounts.

        **What happens:**

        - Products returned are those the user has any commission, milestone, override or withheld setting for. The full catalog is at GET /v1/products.
        - Each rate is the one in effect today in your company's time zone: the latest setting effective on or before today, otherwise the next upcoming one.
        - Roles come from the user's own commission settings for the product: `closer`, `setter` or `self_gen`.
        - `redlines` are per role, not per product, so they are returned once at the top level. The list is empty when the user has no redline settings.
        - `tiered: true` means the actual rate depends on a tier table that this endpoint does not return, so `amount` alone is not the rate.

        **Filtering and paging:**

        - `product_id` limits the result to one product.
        - `role` limits each product's `roles` to that role and returns only products where the user has commission or milestone settings for it. Products with only override or withheld settings are left out under a role filter.
        - Paging is over products, sorted by name. `per_page` defaults to 25, maximum 200. `last_page` is `0` when the user has no products.

        **Formats:**

        - Read each rate's `unit` to interpret `amount`: `percent`, `per_sale`, `per_kw`, `per_watt`, `flat` or `custom_field`. With `custom_field`, a `custom_field_id` names the sale field the rate uses.
        - `effective_date` is `YYYY-MM-DD`.

        **Errors:**

        - `400 Invalid user id`, `400 Invalid product_id`, `400 Bad Request: role must be one of closer, setter, self_gen`, `400 page must be a positive integer`, `400 per_page must be an integer between 1 and 200`, and `400 Invalid query parameter(s)` for any other query key.
        - `404 User not found`.

        **Related:**

        - GET /v1/users/{id}/earnings shows what these rates produced.
        - GET /v1/products lists the product catalog.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: integer, minimum: 1 }
          description: User id from GET /v1/users.
          example: 4821
        - name: product_id
          in: query
          required: false
          schema: { type: integer, minimum: 1 }
          description: Limit to one product (`id` from GET /v1/products).
        - name: role
          in: query
          required: false
          schema: { type: string, enum: [closer, setter, self_gen] }
          description: Limit to one role. Case-insensitive.
        - name: page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 1 }
          description: Page number, over products.
        - name: per_page
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 200, default: 25 }
          description: Products per page.
      responses:
        "200":
          description: The user's commission rates
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          user:
                            type: object
                            description: The user.
                            properties:
                              id:
                                type: integer
                                description: User id.
                              employee_id:
                                type: string
                                nullable: true
                                description: Employee id shown in Sequifi.
                              first_name:
                                type: string
                                description: First name.
                              last_name:
                                type: string
                                description: Last name.
                              position_id:
                                type: integer
                                nullable: true
                                description: Position id.
                              position_name:
                                type: string
                                nullable: true
                                description: Position name.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Products per page.
                          total:
                            type: integer
                            description: Products across all pages.
                          last_page:
                            type: integer
                            description: Last page number. `0` when there are no products.
                          filters:
                            type: object
                            nullable: true
                            description: "`product_id` and `role` as applied, or null."
                          redlines:
                            type: array
                            description: One redline per role the user has a redline setting for.
                            items:
                              type: object
                              properties:
                                role:
                                  type: string
                                  enum: [closer, setter, self_gen]
                                  description: Role.
                                core_position_id:
                                  type: integer
                                  nullable: true
                                  description: "`2` closer, `3` setter, null self-gen."
                                amount:
                                  type: number
                                  nullable: true
                                  description: Redline value.
                                unit:
                                  type: string
                                  nullable: true
                                  description: Unit of `amount`.
                                redline_type:
                                  type: string
                                  nullable: true
                                  description: Redline type as set in Sequifi.
                                effective_date:
                                  type: string
                                  nullable: true
                                  description: Date the setting took effect, `YYYY-MM-DD`.
                          commissions:
                            type: array
                            description: One group per product on this page.
                            items:
                              type: object
                              properties:
                                product:
                                  type: object
                                  description: "`id`, `product_id` (your product code) and `name`."
                                overrides:
                                  type: object
                                  nullable: true
                                  description: "Override rates: `direct`, `indirect`, `office` and `manager`, each `{amount, unit, tiered, effective_date}` or null. Null when the user has no override setting for the product."
                                withheld:
                                  type: object
                                  nullable: true
                                  description: "Withheld setting `{amount, unit, effective_date}`, or null."
                                roles:
                                  type: array
                                  description: Rates per role.
                                  items:
                                    type: object
                                    properties:
                                      role:
                                        type: string
                                        enum: [closer, setter, self_gen]
                                        description: Role.
                                      core_position_id:
                                        type: integer
                                        nullable: true
                                        description: "`2` closer, `3` setter, null self-gen."
                                      commission:
                                        type: object
                                        nullable: true
                                        description: "Commission rate `{amount, unit, tiered, effective_date}`, plus `custom_field_id` when `unit` is `custom_field`. Null when not set."
                                      milestones:
                                        type: array
                                        description: "Milestone payments `{name, amount, unit, trigger, effective_date}` in effect today."
                                        items:
                                          type: object
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 5
                    position_name: "Closer"
                  current_page: 1
                  per_page: 25
                  total: 1
                  last_page: 1
                  filters: { product_id: 7 }
                  redlines:
                    - role: self_gen
                      core_position_id: null
                      amount: 2.5
                      unit: per_watt
                      redline_type: "Fixed"
                      effective_date: "2026-01-01"
                  commissions:
                    - product:
                        id: 7
                        product_id: "FIBER-500"
                        name: "Fiber 500"
                      overrides:
                        direct: { amount: 1.0, unit: percent, tiered: false, effective_date: "2026-06-16" }
                        indirect: { amount: 0.5, unit: percent, tiered: false, effective_date: "2026-06-16" }
                        office: null
                        manager: null
                      withheld: null
                      roles:
                        - role: closer
                          core_position_id: 2
                          commission: { amount: 85, unit: per_sale, tiered: false, effective_date: "2026-06-16" }
                          milestones:
                            - { name: "Milestone 1", amount: 0, unit: percent, trigger: "Install", effective_date: "2026-06-16" }
                            - { name: "Milestone 2", amount: 85, unit: percent, trigger: "Activation", effective_date: "2026-06-16" }
        "400":
          description: Invalid user id, query parameter, role, or paging value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: [foo]
                      allowed_params: [product_id, role, page, per_page]
                bad_role:
                  summary: Unknown role
                  value:
                    status: 400
                    message: "Bad Request: role must be one of closer, setter, self_gen"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/earnings:
    get:
      operationId: getUserEarnings
      tags:
        - Earnings
      summary: Get a user's earnings
      description: |
        Returns what a user has earned in commissions and overrides, split into pending, paid, projected and clawbacks, plus a per-pay-period breakdown. It mirrors the Earnings page in Sequifi. The buckets overlap with the reserve: `paid` includes money held in the user's reserve, so never add the reserve `balance` to `paid`.

        **What happens:**

        - Figures come from the earning lines themselves, so a user has numbers as soon as they earn, before any payroll is built.
        - `pending`: earned and not paid yet, excluding lines on cancelled accounts and lines an admin marked Do Not Pay. Lines already on a finalized but unpaid payroll are included.
        - `paid`: every line marked paid, including lines on accounts cancelled later and lines diverted into the user's reserve (Reserve Balances add-on). Reserve-held dollars therefore appear both here and in GET /v1/users/{id}/reserve.
        - `projected`: forecast for milestones that have not happened yet, on accounts that are not cancelled.
        - `clawbacks`: the lifetime total of every clawback on record, as a negative amount. It includes clawbacks already deducted from earlier paychecks or settled against the reserve.
        - `totals.unpaid` is `pending + projected + clawbacks`, and `totals.lifetime` adds `paid` (it matches the total on the Earnings page). Because `clawbacks` is lifetime, `unpaid` is not a balance still owed.
        - Commission figures count only sales where the user is a closer or setter. Overrides count every override paid to the user, since they are earned on other users' sales.
        - Lines marked Do Not Pay are in no bucket.
        - `accounts` counts distinct sales, not lines.

        **Filtering and paging:**

        - `pay_period_from` and `pay_period_to` filter on each line's own pay period, inclusive: the period starts on or after `pay_period_from` and ends on or before `pay_period_to`.
        - With either filter, `projected` and `clawbacks` are returned as `0`. To see clawbacks for a period, call GET /v1/users/{id}/earnings/items with the same filter and `pay_status=clawed_back`.
        - `pay_periods` lists periods newest first, commissions and overrides merged, each split into `pending` and `paid`. `periods` caps the list (default 12, maximum 60), and `pay_periods_truncated` is `true` when more exist.
        - `pay_periods` does not add up to the buckets: its `pending` includes lines on cancelled accounts, it skips lines with no pay period, and it has no projections or clawbacks.

        **Formats:**

        - Amounts are JSON numbers in dollars, rounded to cents. Clawbacks are negative.
        - Pay period dates are `YYYY-MM-DD`.

        **Errors:**

        - `400 Invalid user id`, `400 Invalid query parameter(s)`, `400 pay_period_from must be in YYYY-MM-DD format` (or `pay_period_to`), `400 pay_period_from must be on or before pay_period_to`, `400 periods must be an integer between 1 and 60`.
        - `404 User not found`.

        **Common mistakes:**

        - Adding the reserve `balance` to `paid`. They share the same dollars.
        - Treating `totals.unpaid` as money owed.
        - Safe practice: for money waiting to be paid, sum `pending` and `approved` lines from GET /v1/users/{id}/earnings/items. For money paid to the user's paychecks, sum its `paid` lines (which exclude reserve). For money held, read `balance` from GET /v1/users/{id}/reserve.

        **Related:**

        - GET /v1/users/{id}/earnings/items lists the lines behind these totals.
        - GET /v1/users/{id}/reserve shows money held back from payroll.
        - GET /v1/users/{id}/commissions shows the rates behind the earnings.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: User id from GET /v1/users.
          schema: { type: integer, minimum: 1 }
          example: 4821
        - name: pay_period_from
          in: query
          required: false
          description: Only lines whose pay period starts on or after this date. Format `YYYY-MM-DD`. Sets `projected` and `clawbacks` to 0.
          schema: { type: string, format: date }
          example: "2026-08-01"
        - name: pay_period_to
          in: query
          required: false
          description: Only lines whose pay period ends on or before this date. Format `YYYY-MM-DD`. Sets `projected` and `clawbacks` to 0.
          schema: { type: string, format: date }
          example: "2026-08-31"
        - name: periods
          in: query
          required: false
          description: How many pay periods to return in `pay_periods`.
          schema: { type: integer, minimum: 1, maximum: 60, default: 12 }
          example: 12
      responses:
        "200":
          description: The user's earnings
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          user:
                            type: object
                            description: "The user: `id`, `employee_id`, `first_name`, `last_name`, `position_id`, `position_name`."
                          filters:
                            type: object
                            nullable: true
                            description: "`pay_period_from`, `pay_period_to` and `periods` as applied, or null."
                          commissions:
                            type: object
                            description: "Commission buckets `pending`, `paid`, `projected` and `clawbacks`, each `{accounts, amount}`."
                          overrides:
                            type: object
                            description: "Override buckets `pending`, `paid`, `projected` and `clawbacks`, each `{accounts, amount}`."
                          totals:
                            type: object
                            description: Commissions plus overrides.
                            properties:
                              pending:
                                type: number
                                description: Earned, not paid, not cancelled, not Do Not Pay.
                              paid:
                                type: number
                                description: Marked paid. Includes reserve-held money.
                              projected:
                                type: number
                                description: Forecast. `0` under a pay-period filter.
                              clawbacks:
                                type: number
                                description: Lifetime clawbacks, negative. `0` under a pay-period filter.
                              unpaid:
                                type: number
                                description: "`pending + projected + clawbacks`. Not a balance owed."
                              lifetime:
                                type: number
                                description: "`pending + paid + projected + clawbacks`."
                          pay_periods:
                            type: array
                            description: Per-pay-period breakdown, newest first.
                            items:
                              type: object
                              properties:
                                pay_period_from:
                                  type: string
                                  format: date
                                  description: Period start.
                                pay_period_to:
                                  type: string
                                  format: date
                                  description: Period end.
                                commission:
                                  type: number
                                  description: Commission in the period, pending plus paid.
                                override:
                                  type: number
                                  description: Overrides in the period, pending plus paid.
                                pending:
                                  type: number
                                  description: Not yet paid. Includes lines on cancelled accounts.
                                paid:
                                  type: number
                                  description: Paid.
                                amount:
                                  type: number
                                  description: Everything in the period.
                          pay_periods_truncated:
                            type: boolean
                            description: "`true` when more periods exist than `periods` allowed."
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 5
                    position_name: "Closer"
                  filters: null
                  commissions:
                    pending:   { accounts: 3, amount: 1500.00 }
                    paid:      { accounts: 8, amount: 6200.00 }
                    projected: { accounts: 2, amount: 900.00 }
                    clawbacks: { accounts: 1, amount: -400.00 }
                  overrides:
                    pending:   { accounts: 2, amount: 120.00 }
                    paid:      { accounts: 5, amount: 480.00 }
                    projected: { accounts: 0, amount: 0 }
                    clawbacks: { accounts: 0, amount: 0 }
                  totals:
                    pending: 1620.00
                    paid: 6680.00
                    projected: 900.00
                    clawbacks: -400.00
                    unpaid: 2120.00
                    lifetime: 8800.00
                  pay_periods:
                    - pay_period_from: "2026-09-14"
                      pay_period_to: "2026-09-20"
                      commission: 1500.00
                      override: 120.00
                      pending: 1620.00
                      paid: 0
                      amount: 1620.00
                    - pay_period_from: "2026-09-07"
                      pay_period_to: "2026-09-13"
                      commission: 2100.00
                      override: 180.00
                      pending: 0
                      paid: 2280.00
                      amount: 2280.00
                  pay_periods_truncated: false
        "400":
          description: Invalid user id, query parameter, date, range, or periods value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["foo"]
                      allowed_params: ["pay_period_from", "pay_period_to", "periods"]
                bad_date:
                  summary: Invalid date
                  value:
                    status: 400
                    message: "pay_period_from must be in YYYY-MM-DD format"
                    data: {}
                inverted_range:
                  summary: Range is backwards
                  value:
                    status: 400
                    message: "pay_period_from must be on or before pay_period_to"
                    data: {}
                bad_periods:
                  summary: periods out of range
                  value:
                    status: 400
                    message: "periods must be an integer between 1 and 60"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/earnings/items:
    get:
      operationId: listUserEarningItems
      tags:
        - Earnings
      summary: List a user's earning lines
      description: |
        Returns the lines behind GET /v1/users/{id}/earnings, one per commission milestone, override, projection or clawback, each with a `pay_status` that says where the money is now. Unlike the summary, this splits reserve-held money out of `paid` into `reserved`.

        **What happens:**

        - A sale usually produces one line per milestone, plus override lines for the user's managers. Group by `pid` for a per-sale view.
        - `pay_status` values:
          - `projected`: forecast; the milestone has not happened yet. No pay period.
          - `pending`: earned, not on a finalized payroll yet.
          - `approved`: on a payroll an admin finalized, not paid yet.
          - `paid`: paid on a paycheck. `pay_date` is set.
          - `reserved`: diverted into the user's reserve instead of a paycheck. See GET /v1/users/{id}/reserve.
          - `do_not_pay`: withheld by an admin and not paid on this run.
          - `cancelled`: unpaid line on a cancelled account.
          - `clawed_back`: money taken back after a cancellation, as a negative amount. Includes clawbacks already deducted on past paychecks.
        - Scoping matches the summary: commission lines count only sales where the user is a closer or setter; override lines count every override paid to the user, and `override_from_user_id` is the user whose sale earned it.
        - `summary` gives lines, accounts and amount for every status over the filtered set, before paging.
        - Tie-out to GET /v1/users/{id}/earnings with no filters: its `pending` equals `pending` + `approved` here, and its `paid` equals `paid` + `reserved` here. `do_not_pay` and `cancelled` lines are in no summary bucket. With a pay-period filter the two do not tie out, because the summary zeroes clawbacks and this endpoint does not.

        **Filtering and paging:**

        - Filters combine with AND. `pay_status` takes a comma-separated list and matches any of them.
        - `pay_period_from` and `pay_period_to` filter on the line's pay period. Lines with no pay period, such as projections, drop out.
        - `date_from` and `date_to` filter on the sale date (`customer_signoff`). All date filters are inclusive.
        - `page` defaults to 1. `per_page` defaults to 50, maximum 5000. A rep's whole list usually fits in one call at `per_page=5000`, which is much faster than paging: every call does the same work regardless of page size.
        - Sorted newest first by pay period, then milestone date, then sale date.

        **Formats:**

        - Amounts are JSON numbers in dollars, rounded to cents. Clawbacks are negative.
        - Dates are `YYYY-MM-DD`.
        - `(source, id)` is the unique row key; `id` alone repeats across sources. Treat `source` as an opaque label.
        - `product_name` is the product the sale was sold under, as the app names it, and `product_code` is its code. A sale whose product was retired and moved to the Default product reports the original product in both. `product_name` is null when the sale has no product.
        - `payroll_id` is the pay stub the line belongs to, or null. Use it with GET /v1/payroll-history/{id} or GET /v1/payroll/{id}.

        **Errors:**

        - `400 Invalid user id`, `400 Invalid query parameter(s)`, `400 pay_status must be one or more of: ...`, `400 category must be one of: commission, override`, `400 <field> must be in YYYY-MM-DD format`, `400 pay_period_from must be on or before pay_period_to` (or `date_from`), `400 page must be a positive integer`, `400 per_page must be an integer between 1 and 5000`.
        - `404 User not found`.

        **Related:**

        - GET /v1/users/{id}/earnings returns the bucket totals.
        - GET /v1/payroll-history/{id}/line-items itemizes the stub a line was paid on.
        - GET /v1/users/{id}/reserve explains `reserved` lines.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: User id. Look it up by email with GET /v1/users?email=.
          schema: { type: integer, minimum: 1 }
          example: 4821
        - name: pay_status
          in: query
          required: false
          description: "Comma-separated pay statuses: `projected`, `pending`, `approved`, `paid`, `reserved`, `do_not_pay`, `cancelled`, `clawed_back`."
          schema:
            type: string
            example: "pending,approved,paid"
        - name: category
          in: query
          required: false
          description: "`commission` or `override`."
          schema: { type: string, enum: [commission, override] }
        - name: pid
          in: query
          required: false
          description: Only lines for this sale id.
          schema: { type: string }
        - name: pay_period_from
          in: query
          required: false
          description: Only lines whose pay period starts on or after this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
          example: "2026-08-01"
        - name: pay_period_to
          in: query
          required: false
          description: Only lines whose pay period ends on or before this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
          example: "2026-08-31"
        - name: date_from
          in: query
          required: false
          description: Only lines on sales dated on or after this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
        - name: date_to
          in: query
          required: false
          description: Only lines on sales dated on or before this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
        - name: page
          in: query
          required: false
          description: Page number.
          schema: { type: integer, minimum: 1, default: 1 }
        - name: per_page
          in: query
          required: false
          description: Lines per page.
          schema: { type: integer, minimum: 1, maximum: 5000, default: 50 }
      responses:
        "200":
          description: The user's earning lines
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          user:
                            type: object
                            description: "The user: `id`, `employee_id`, `first_name`, `last_name`, `position_id`, `position_name`."
                          filters:
                            type: object
                            nullable: true
                            description: Filters as applied (`pay_status` as an array), or null.
                          summary:
                            type: object
                            description: "One entry per pay status, always all eight, each `{lines, accounts, amount}`, over the filtered set before paging."
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Lines per page.
                          total:
                            type: integer
                            description: Lines across all pages.
                          last_page:
                            type: integer
                            description: Last page number. At least `1`.
                          items:
                            type: array
                            description: The lines on this page.
                            items:
                              type: object
                              properties:
                                source:
                                  type: string
                                  description: Opaque label for the kind of line. Use with `id` as the row key.
                                id:
                                  type: integer
                                  description: Line id. Unique only together with `source`.
                                category:
                                  type: string
                                  enum: [commission, override]
                                  description: Commission or override.
                                pay_status:
                                  type: string
                                  enum: [projected, pending, approved, paid, reserved, do_not_pay, cancelled, clawed_back]
                                  description: Where the money is now.
                                amount:
                                  type: number
                                  description: Dollars. Negative for clawbacks.
                                pid:
                                  type: string
                                  description: Sale id.
                                customer_name:
                                  type: string
                                  nullable: true
                                  description: Sale customer.
                                product_code:
                                  type: string
                                  nullable: true
                                  description: Product code on the sale.
                                product_name:
                                  type: string
                                  nullable: true
                                  description: Name of the product the sale was sold under (the original product if the sale was moved to the Default product).
                                customer_signoff:
                                  type: string
                                  nullable: true
                                  description: Sale date.
                                date_cancelled:
                                  type: string
                                  nullable: true
                                  description: Date the sale was cancelled, or null.
                                milestone_name:
                                  type: string
                                  nullable: true
                                  description: Milestone name.
                                milestone_trigger:
                                  type: string
                                  nullable: true
                                  description: What triggers the milestone.
                                milestone_date:
                                  type: string
                                  nullable: true
                                  description: Date the milestone was reached.
                                override_type:
                                  type: string
                                  nullable: true
                                  description: Override kind on override lines, for example `Direct`.
                                override_from_user_id:
                                  type: integer
                                  nullable: true
                                  description: User whose sale earned the override.
                                pay_period_from:
                                  type: string
                                  nullable: true
                                  description: Start of the pay period the line belongs to.
                                pay_period_to:
                                  type: string
                                  nullable: true
                                  description: End of that pay period.
                                payroll_id:
                                  type: integer
                                  nullable: true
                                  description: Pay stub id, or null.
                                pay_date:
                                  type: string
                                  nullable: true
                                  description: Date the line was paid. Set on paid lines and clawbacks.
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 5
                    position_name: "Closer"
                  filters: null
                  summary:
                    projected:   { lines: 0, accounts: 0, amount: 0 }
                    pending:     { lines: 0, accounts: 0, amount: 0 }
                    approved:    { lines: 1, accounts: 1, amount: 500.00 }
                    paid:        { lines: 1, accounts: 1, amount: 120.00 }
                    reserved:    { lines: 0, accounts: 0, amount: 0 }
                    do_not_pay:  { lines: 0, accounts: 0, amount: 0 }
                    cancelled:   { lines: 0, accounts: 0, amount: 0 }
                    clawed_back: { lines: 1, accounts: 1, amount: -400.00 }
                  current_page: 1
                  per_page: 50
                  total: 3
                  last_page: 1
                  items:
                    - source: "user_commission"
                      id: 90211
                      category: "commission"
                      pay_status: "approved"
                      amount: 500.00
                      pid: "SALE-10482"
                      customer_name: "Riley Chen"
                      product_code: "SOLAR"
                      product_name: "Solar 300"
                      customer_signoff: "2026-08-02"
                      date_cancelled: null
                      milestone_name: "M1"
                      milestone_trigger: "Install"
                      milestone_date: "2026-09-10"
                      override_type: null
                      override_from_user_id: null
                      pay_period_from: "2026-09-14"
                      pay_period_to: "2026-09-20"
                      payroll_id: 5521
                      pay_date: null
                    - source: "user_overrides"
                      id: 3310
                      category: "override"
                      pay_status: "paid"
                      amount: 120.00
                      pid: "SALE-10391"
                      customer_name: "Sam Patel"
                      product_code: "SOLAR"
                      product_name: "Solar 300"
                      customer_signoff: "2026-07-01"
                      date_cancelled: null
                      milestone_name: null
                      milestone_trigger: null
                      milestone_date: null
                      override_type: "Direct"
                      override_from_user_id: 4877
                      pay_period_from: "2026-07-20"
                      pay_period_to: "2026-07-26"
                      payroll_id: 5107
                      pay_date: "2026-08-01"
                    - source: "clawback_settlements"
                      id: 712
                      category: "commission"
                      pay_status: "clawed_back"
                      amount: -400.00
                      pid: "SALE-10355"
                      customer_name: "Casey Brooks"
                      product_code: "SOLAR"
                      product_name: "Solar 300"
                      customer_signoff: "2026-06-11"
                      date_cancelled: "2026-07-02"
                      milestone_name: "M1"
                      milestone_trigger: "Install"
                      milestone_date: "2026-06-25"
                      override_type: null
                      override_from_user_id: null
                      pay_period_from: "2026-07-06"
                      pay_period_to: "2026-07-12"
                      payroll_id: 5033
                      pay_date: "2026-07-17"
        "400":
          description: Invalid user id, query parameter, status, category, date, range, or paging value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["periods"]
                      allowed_params: ["pay_status", "category", "pid", "pay_period_from", "pay_period_to", "date_from", "date_to", "page", "per_page"]
                bad_status:
                  summary: Unknown pay status
                  value:
                    status: 400
                    message: "pay_status must be one or more of: projected, pending, approved, paid, reserved, do_not_pay, cancelled, clawed_back"
                    data: {}
                bad_per_page:
                  summary: per_page out of range
                  value:
                    status: 400
                    message: "per_page must be an integer between 1 and 5000"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/reserve:
    get:
      operationId: getUserReserve
      tags:
        - Reserve
      summary: Get a user's reserve balance
      description: |
        Returns a user's Reserve Balances position: the current `balance`, lifetime `totals`, and the ledger of every movement, newest first. The same dollars are counted as `paid` in GET /v1/users/{id}/earnings, so never add `balance` to that figure.

        **What happens:**

        - When the Reserve Balances add-on is on, part of a user's earnings is held in a reserve instead of going onto a pay stub. Held money leaves the reserve only when an admin sends it to payroll, which puts a Reserve Payout adjustment on a stub and writes a `send_to_payroll_debit` entry here.
        - Held lines are never on a pay stub, so they are absent from pay stub line items. Use line items to reconcile what was paid, and this endpoint to explain where the rest went.
        - `reserve_status` says whether your company uses the reserve: `active` (new movements are recorded), `deactivated` (frozen, but existing balances are still owed and visible, so do not hide them), or `available`, `requested` or `coming_soon` (never turned on). When it was never turned on, `balance` is `0`, `entries` is empty and `last_page` is `0`.
        - `reserve_enabled` is `true` only when `reserve_status` is `active`.
        - `balance` is the stored current balance, the same figure the app shows.
        - A clawback settled against the reserve appears here as `clawback_debit` and is also counted in the earnings `clawbacks` total. Do not subtract it twice.

        **Filtering and paging:**

        - `entry_type`, `date_from` and `date_to` narrow `entries` only. `totals` are lifetime and never filtered; `total` (the pager count) is.
        - Dates filter on `effective_date`, inclusive.
        - `entry_type` accepts any lowercase identifier, so a type added after this page was written still works. An unknown but well-formed type returns an empty page.
        - `page` defaults to 1. `per_page` defaults to 50, maximum 500. `last_page` is `0` when there are no entries.

        **Formats:**

        - Amounts are JSON numbers in dollars, rounded to cents, signed as they move the balance: credits positive, debits negative.
        - `direction` comes from the sign of `amount`, not from `entry_type`. A `send_to_payroll_debit` that clears a negative balance is a `credit`.
        - `totals.paid_out` is the signed sum of payouts and their reversals, so it is normally negative.
        - Deal entries carry `pid` and `customer_name` and no pay period. Payout entries carry the paycheck's `pay_period_from` and `pay_period_to` and no `pid`.
        - `effective_date` is `YYYY-MM-DD`. `created_at` is `YYYY-MM-DD HH:MM:SS` with no time zone.
        - `ref_type` and `ref_id` identify the source record. Treat `ref_type` as an opaque label.
        - `entry_type` values in use today: `milestone_credit`, `milestone_adjustment`, `milestone_adjustment_reversal`, `override_credit`, `clawback_debit`, `deduction_accrual_clawback`, `advance_repayment_debit`, `send_to_payroll_debit`, `send_to_payroll_reversal`, `source_retired_reversal` (the source line was removed, so its entry is reversed) and `source_retired_reversal_correction` (a reversal that should not have been written, undone). The list can grow.

        **Errors:**

        - `400 Invalid user id`, `400 Invalid query parameter(s)`, `400 entry_type must be a lowercase identifier` (with `data.known_entry_types`), `400 date_from must be in YYYY-MM-DD format` (or `date_to`), `400 date_from must be on or before date_to`, `400 page must be a positive integer`, `400 per_page must be an integer between 1 and 500`.
        - `404 User not found`.

        **Related:**

        - GET /v1/users/{id}/earnings/items marks held lines as `reserved`.
        - GET /v1/payroll-history/{id}/line-items shows the Reserve Payout adjustment on a stub.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          description: User id from GET /v1/users.
          schema: { type: integer, minimum: 1 }
          example: 4821
        - name: entry_type
          in: query
          required: false
          description: Only entries of this type. An unknown but well-formed value returns an empty page.
          schema: { type: string }
          example: "milestone_credit"
        - name: date_from
          in: query
          required: false
          description: Only entries with `effective_date` on or after this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
          example: "2026-08-01"
        - name: date_to
          in: query
          required: false
          description: Only entries with `effective_date` on or before this date. Format `YYYY-MM-DD`.
          schema: { type: string, format: date }
          example: "2026-08-31"
        - name: page
          in: query
          required: false
          description: Page of entries.
          schema: { type: integer, minimum: 1, default: 1 }
          example: 1
        - name: per_page
          in: query
          required: false
          description: Entries per page.
          schema: { type: integer, minimum: 1, maximum: 500, default: 50 }
          example: 50
      responses:
        "200":
          description: The user's reserve balance and ledger
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Label of the API credential that made the call.
                          user:
                            type: object
                            description: "The user: `id`, `employee_id`, `first_name`, `last_name`, `position_id`, `position_name`."
                          reserve_status:
                            type: string
                            description: "`active`, `deactivated`, or a value meaning never turned on (`available`, `requested`, `coming_soon`)."
                          reserve_enabled:
                            type: boolean
                            description: "`true` only when `reserve_status` is `active`."
                          balance:
                            type: number
                            description: Current reserve balance in dollars.
                          totals:
                            type: object
                            description: Lifetime totals, never filtered.
                            properties:
                              credited:
                                type: number
                                description: Sum of positive entries.
                              debited:
                                type: number
                                description: Sum of negative entries.
                              paid_out:
                                type: number
                                description: Signed sum of payouts and payout reversals. Normally negative.
                              entry_count:
                                type: integer
                                description: Number of entries.
                          filters:
                            type: object
                            nullable: true
                            description: Filters as applied, or null.
                          current_page:
                            type: integer
                            description: Page returned.
                          per_page:
                            type: integer
                            description: Entries per page.
                          total:
                            type: integer
                            description: Entries matching the filters.
                          last_page:
                            type: integer
                            description: Last page number. `0` when there are no entries.
                          entries:
                            type: array
                            description: Ledger entries, newest first.
                            items:
                              type: object
                              properties:
                                id:
                                  type: integer
                                  description: Entry id.
                                entry_type:
                                  type: string
                                  description: Kind of movement.
                                direction:
                                  type: string
                                  enum: [credit, debit]
                                  description: From the sign of `amount`.
                                amount:
                                  type: number
                                  description: Signed dollars.
                                pid:
                                  type: string
                                  nullable: true
                                  description: Sale id on deal entries.
                                customer_name:
                                  type: string
                                  nullable: true
                                  description: Sale customer on deal entries.
                                description:
                                  type: string
                                  nullable: true
                                  description: Text describing the movement.
                                effective_date:
                                  type: string
                                  description: When the movement counts, `YYYY-MM-DD`.
                                pay_period_from:
                                  type: string
                                  nullable: true
                                  description: Pay period start of the paycheck, on payout entries.
                                pay_period_to:
                                  type: string
                                  nullable: true
                                  description: Pay period end of the paycheck, on payout entries.
                                ref_type:
                                  type: string
                                  nullable: true
                                  description: Opaque label for the source record.
                                ref_id:
                                  type: integer
                                  nullable: true
                                  description: Id of the source record.
                                created_at:
                                  type: string
                                  description: When the entry was written, `YYYY-MM-DD HH:MM:SS` with no time zone.
              example:
                status: 200
                message: "success"
                data:
                  requestedBy: "acme"
                  user:
                    id: 4821
                    employee_id: "EMP-4821"
                    first_name: "Alex"
                    last_name: "Morgan"
                    position_id: 5
                    position_name: "Closer"
                  reserve_status: "active"
                  reserve_enabled: true
                  balance: 740.00
                  totals:
                    credited: 1450.00
                    debited: -710.00
                    paid_out: -500.00
                    entry_count: 6
                  filters:
                    date_from: "2026-08-01"
                  current_page: 1
                  per_page: 50
                  total: 3
                  last_page: 1
                  entries:
                    - id: 3108
                      entry_type: "milestone_credit"
                      direction: "credit"
                      amount: 420.00
                      pid: "SALE-10482"
                      customer_name: "Riley Chen"
                      description: "Final commission milestone for sale SALE-10482"
                      effective_date: "2026-08-14"
                      pay_period_from: null
                      pay_period_to: null
                      ref_type: "user_commission"
                      ref_id: 70114
                      created_at: "2026-08-14 09:12:00"
                    - id: 3102
                      entry_type: "clawback_debit"
                      direction: "debit"
                      amount: -180.00
                      pid: "SALE-10517"
                      customer_name: "Jordan Patel"
                      description: "Clawback settled against reserve for sale SALE-10517"
                      effective_date: "2026-08-11"
                      pay_period_from: null
                      pay_period_to: null
                      ref_type: "clawback_settlements"
                      ref_id: 712
                      created_at: "2026-08-11 17:02:41"
                    - id: 3095
                      entry_type: "send_to_payroll_debit"
                      direction: "debit"
                      amount: -500.00
                      pid: null
                      customer_name: null
                      description: "Reserve payout to payroll"
                      effective_date: "2026-08-09"
                      pay_period_from: "2026-08-09"
                      pay_period_to: "2026-08-15"
                      ref_type: "approvals_and_requests"
                      ref_id: 3307
                      created_at: "2026-08-08 11:20:05"
        "400":
          description: Invalid user id, query parameter, entry type, date, or paging value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_params:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: ["pay_period_from"]
                      allowed_params: ["entry_type", "date_from", "date_to", "page", "per_page"]
                bad_entry_type:
                  summary: entry_type is not a lowercase identifier
                  value:
                    status: 400
                    message: "entry_type must be a lowercase identifier"
                    data:
                      known_entry_types: ["milestone_credit", "milestone_adjustment", "milestone_adjustment_reversal", "override_credit", "clawback_debit", "deduction_accrual_clawback", "advance_repayment_debit", "send_to_payroll_debit", "send_to_payroll_reversal", "source_retired_reversal", "source_retired_reversal_correction"]
                bad_date:
                  summary: Invalid date
                  value:
                    status: 400
                    message: "date_from must be in YYYY-MM-DD format"
                    data: {}
        "401":
          description: Missing, invalid or expired token. The gateway rejects the call before it reaches Sequifi, so the body has only a `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
              example:
                message: "Unauthorized"
        "404":
          description: User not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "User not found"
                data: {}
        "500":
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/users/{id}/transfer:
    post:
      operationId: transferUser
      tags:
        - Users
      summary: Transfer a user to an office
      description: |
        Moves a user to another office from `effective_date`, either permanently or for a set window (for example a two-week blitz) after which they move back on their own. This changes pay: overrides on a sale follow the office the rep was in on the sale's approval date, so a transfer changes who earns overrides on the rep's sales from `effective_date` on. Try it on one or two reps before running it in bulk, and never change `effective_date` on a retry.

        **Before you call:**

        - `id` is the user id from `GET /v1/users` of an already-hired rep. For someone still in onboarding, set the office with `POST /v1/onboarding`.
        - Get `office_id` from `GET /v1/locations`. Office names are not accepted.
        - The rep must not be dismissed.

        **What happens:**

        - Permanent (no `end_date`): one office history entry dated `effective_date`.
        - Temporary (`end_date` set): two entries, the move on `effective_date` and a move back to the rep's previous office on the day after `end_date`. The window includes `end_date`, so a one-day blitz uses the same date for both.
        - Manager, team, department and state carry over from the rep's current assignment unless you send them. The rep keeps their own direct reports unless you send `existing_employee_new_manager_id`.
        - Commission, override, upfront and redline values are not accepted. Sequifi works them out from the new office.
        - A transfer dated today or earlier also recalculates the rep's open sales that are not fully paid.
        - `team_id` changes the team shown on the rep's record but does not add the rep to that team's members, so the team manager's override does not follow. Change team membership in the app.
        - `GET /v1/users/{id}` shows today's office, so a future-dated transfer does not appear there until its date.

        **Idempotency and retries:**

        - After a timeout, re-post the identical body. It updates the same entries instead of adding new ones and normally returns `200` again.
        - For a rep with no earlier office history, a re-posted permanent transfer can return `409` `NO_CHANGE` instead. After a timeout, treat `NO_CHANGE` as success.
        - For a rep with no earlier office history, re-posting a temporary transfer whose `effective_date` has already arrived can record the return to the temporary office instead of the original one. Check the rep's office history in the app before re-posting a temporary transfer.
        - Never change `effective_date` on a retry. A different date is a second transfer.

        **Formats:**

        - Dates are `YYYY-MM-DD` and must be real calendar days. `end_date` must be on or after `effective_date`.
        - `end_date` sent as `null` or `""` is the same as leaving it out, which makes the transfer permanent.
        - Ids are positive integers; numeric strings also work. `null` or `""` for an optional id keeps the current value.
        - Other body fields are ignored.
        - The success response `status` is the number `200`.

        **Errors:**

        - `400` for an invalid path id, malformed JSON, or a missing or invalid field (messages in the examples).
        - `404` `NOT_FOUND`: no user with that id.
        - `409` `NO_CHANGE`: permanent transfer to the office the rep is already in on `effective_date`.
        - `422` `USER_DISMISSED` (the rep is dismissed), `OFFICE_NOT_FOUND` (no office with that id, or it is archived; inactive offices are accepted), `TEAM_NOT_FOUND`, or `NO_RETURN_OFFICE` (temporary transfer for a rep with no earlier office to return to; leave out `end_date` instead).
        - `500` `TRANSFER_FAILED` or `Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502` `The tenant returned an unreadable response` or `Could not reach the tenant`: retry later with the identical body.
        - `503`: your company is not set up for this endpoint yet. Contact Sequifi support.
        - `504`: no answer in time. The transfer may still have been applied (see retries above).
        - Error codes are in `data.code`, alongside `data.requestedBy`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Common mistakes:**

        - Sending `end_date: ""` to mean "set later". It makes the move permanent.
        - Sending a `manager_id` that is not a real user id. It is not checked and is saved as sent. Look managers up with `GET /v1/users`.
        - Expecting the new office in `GET /v1/users/{id}` before `effective_date`.

        **Related:**

        - `GET /v1/locations` for `office_id`; `GET /v1/teams` for `team_id`.
        - `POST /v1/users/{id}/position` to change position.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            minimum: 1
          description: User id of an already-hired rep, from `GET /v1/users`. Not an onboarding id.
          example: 4821
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - office_id
                - effective_date
              properties:
                office_id:
                  type: integer
                  minimum: 1
                  description: Target office, from `GET /v1/locations`. Must not be archived.
                  example: 31
                effective_date:
                  type: string
                  format: date
                  description: First day the rep works out of the target office, YYYY-MM-DD.
                  example: "2026-08-11"
                end_date:
                  type: string
                  format: date
                  nullable: true
                  description: Last day of a temporary transfer, inclusive. Leave it out for a permanent move. Must be on or after `effective_date`.
                  example: "2026-08-22"
                manager_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: New manager's user id. Defaults to the rep's current manager. Not checked for existence.
                  example: 87
                team_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: New team id. Defaults to the rep's current team. Changes the team label only, not team membership.
                  example: 4
                existing_employee_new_manager_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: >
                    Who the rep's own direct reports answer to afterwards. Defaults
                    to the rep, so they keep their team, which is usually right for
                    a temporary transfer. Send it only to hand the reports to
                    someone else.
                  example: 87
            examples:
              permanent:
                summary: Permanent transfer
                value:
                  office_id: 31
                  effective_date: "2026-08-11"
              blitz:
                summary: Two-week blitz, moves back automatically
                value:
                  office_id: 31
                  effective_date: "2026-08-11"
                  end_date: "2026-08-22"
      responses:
        "200":
          description: Transfer applied
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          user_id:
                            type: integer
                            description: The transferred user.
                          temporary:
                            type: boolean
                            description: True when `end_date` was sent.
                          transfers:
                            type: array
                            description: Every office history entry written, in date order. One for a permanent transfer, two for a temporary one.
                            items:
                              type: object
                              properties:
                                office_id:
                                  type: integer
                                  description: Office from this date.
                                effective_date:
                                  type: string
                                  format: date
                                  description: Date the entry takes effect, YYYY-MM-DD.
                          returns_to_office_id:
                            type: integer
                            nullable: true
                            description: Office the rep moves back to after a temporary transfer. Null for a permanent one.
              examples:
                temporary:
                  summary: Temporary transfer applied
                  value:
                    status: 200
                    message: "Temporary transfer applied."
                    data:
                      requestedBy: "acme"
                      user_id: 4821
                      temporary: true
                      transfers:
                        - office_id: 31
                          effective_date: "2026-08-11"
                        - office_id: 19
                          effective_date: "2026-08-23"
                      returns_to_office_id: 19
                permanent:
                  summary: Permanent transfer applied
                  value:
                    status: 200
                    message: "Transfer applied."
                    data:
                      requestedBy: "acme"
                      user_id: 4821
                      temporary: false
                      transfers:
                        - office_id: 31
                          effective_date: "2026-08-11"
                      returns_to_office_id: null
        "400":
          description: Invalid id, body or field
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Path id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid user id"
                    data: {}
                bad_office:
                  summary: office_id missing or not a positive integer
                  value:
                    status: 400
                    message: "office_id is required and must be a positive integer. Look one up with GET /v1/locations."
                    data: {}
                bad_effective_date:
                  summary: effective_date missing or not a real date
                  value:
                    status: 400
                    message: "effective_date is required and must be a real calendar date in YYYY-MM-DD format."
                    data: {}
                bad_end_date:
                  summary: end_date not a real date
                  value:
                    status: 400
                    message: "end_date must be a real calendar date in YYYY-MM-DD format. Omit it for a permanent transfer."
                    data: {}
                end_before_start:
                  summary: end_date before effective_date
                  value:
                    status: 400
                    message: "end_date must be on or after effective_date."
                    data: {}
                bad_optional_id:
                  summary: Optional id not a positive integer
                  value:
                    status: 400
                    message: "manager_id must be a positive integer."
                    data: {}
        "401":
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        "404":
          description: No user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "No user with id 4821."
                data:
                  requestedBy: "acme"
                  code: "NOT_FOUND"
        "409":
          description: The rep is already in that office on `effective_date` and no `end_date` was sent. After a timed-out first attempt, treat this as success.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 409
                message: "User 4821 is already assigned to office 31 as of 2026-08-11."
                data:
                  requestedBy: "acme"
                  code: "NO_CHANGE"
        "422":
          description: The rep, office or team cannot be used
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                user_dismissed:
                  summary: The rep is dismissed
                  value:
                    status: 422
                    message: "User 4821 is dismissed and cannot be transferred."
                    data:
                      requestedBy: "acme"
                      code: "USER_DISMISSED"
                office_not_found:
                  summary: Unknown or archived office
                  value:
                    status: 422
                    message: "No active office with id 31."
                    data:
                      requestedBy: "acme"
                      code: "OFFICE_NOT_FOUND"
                team_not_found:
                  summary: Unknown team
                  value:
                    status: 422
                    message: "No team with id 4."
                    data:
                      requestedBy: "acme"
                      code: "TEAM_NOT_FOUND"
                no_return_office:
                  summary: Temporary transfer with no earlier office
                  value:
                    status: 422
                    message: "User 4821 has no office assigned before 2026-08-11, so there is nothing to return them to when the temporary transfer ends. Omit end_date to make this a permanent transfer."
                    data:
                      requestedBy: "acme"
                      code: "NO_RETURN_OFFICE"
        "500":
          description: The transfer could not be applied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The transfer could not be applied."
                data:
                  requestedBy: "acme"
                  code: "TRANSFER_FAILED"
        "502":
          description: Sequifi could not complete the request. Retry later with the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 502
                message: "Could not reach the tenant"
                data:
                  user_id: 4821
        "503":
          description: Your company is not set up for transfers over the API. Contact Sequifi support; this is not a problem with your token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This tenant is not configured for transfers over the API. Contact Sequifi support."
                    data: {}
                not_provisioned:
                  summary: Not provisioned
                  value:
                    status: 503
                    message: "This tenant is not provisioned for Marketplace API writes. Contact Sequifi support."
                    data:
                      requestedBy: "acme"
                      code: "NOT_PROVISIONED"
        "504":
          description: No answer in time. The transfer may still have been applied; re-post the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The transfer may still have been applied — re-post the identical body, which converges rather than transferring twice. Do not change effective_date on a retry."
                data:
                  user_id: 4821

  /v1/users/{id}/position:
    post:
      operationId: changeUserPosition
      tags:
        - Users
      summary: Change a user's position
      description: |
        Changes a user's position from `effective_date`. From that date the new position's own settings supply the rep's wages, commissions, upfronts and overrides, as when an admin changes a position in the app. Re-posting the identical body is a safe retry, but a different `effective_date` makes a second position change.

        **Before you call:**

        - `id` is the user id from `GET /v1/users` of an already-hired rep. For someone still in onboarding, set the position with `POST /v1/onboarding`.
        - Get `position_id` (and `sub_position_id` if your company uses sub-positions) from `GET /v1/positions`. Position names are not accepted.
        - This endpoint accepts any existing position id, including inactive ones that `GET /v1/positions` hides. Pick from that list.
        - The rep must not be dismissed.

        **What happens:**

        - The change is added to the rep's position history dated `effective_date`.
        - Commission, wage, upfront and override values are not accepted. Sequifi works them out from the position.
        - There is no department field.
        - Manager, team, recruiter, additional recruiters and additional office assignments carry over. The rep keeps their own direct reports unless you send `existing_employee_new_manager_id`.
        - `team_id` changes the team shown on the rep's record but does not add the rep to that team's members, so the team manager's override does not follow. Change team membership in the app.

        **Idempotency and retries:**

        - After a timeout, re-post the identical body. It updates the same history entry instead of adding a second one.
        - Never change `effective_date` on a retry. A different date is a second position change.

        **Formats:**

        - `effective_date` is `YYYY-MM-DD` and must be a real calendar day.
        - Ids are positive integers; numeric strings also work. `null` or `""` for an optional id keeps the current value.
        - Other body fields are ignored.
        - The success response `status` is the number `200`.

        **Errors:**

        - `400` for an invalid path id, malformed JSON, or a missing or invalid field (messages in the examples).
        - `404` `NOT_FOUND`: no user with that id.
        - `422` `USER_DISMISSED` (the rep is dismissed), `POSITION_NOT_FOUND` (no position with that `position_id` or `sub_position_id`), or `TEAM_NOT_FOUND`.
        - `500` `POSITION_CHANGE_FAILED` or `Could not resolve the tenant host`. Contact Sequifi support if it repeats.
        - `502` `The tenant returned an unreadable response` or `Could not reach the tenant`: retry later with the identical body.
        - `503`: your company is not set up for this endpoint yet. Contact Sequifi support.
        - `504`: no answer in time. The change may still have been applied; re-post the identical body.
        - Error codes are in `data.code`, alongside `data.requestedBy`.
        - `401` when the token is missing, malformed, expired or revoked. It is rejected before the request is processed, so the body is only `{"message":"Unauthorized"}`, with no `status` or `data`.

        **Common mistakes:**

        - Sending a `manager_id` that is not a real user id. It is not checked and is saved as sent. Look managers up with `GET /v1/users`.
        - Using an id from a user's `position_id` that `GET /v1/positions` does not list (an inactive position).

        **Related:**

        - `GET /v1/positions` for `position_id`; `GET /v1/teams` for `team_id`.
        - `GET /v1/users/{id}` shows `position_id` and `sub_position_id` as of today.
        - `POST /v1/users/{id}/transfer` to change office.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            minimum: 1
          description: User id of an already-hired rep, from `GET /v1/users`. Not an onboarding id.
          example: 4821
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - position_id
                - effective_date
              properties:
                position_id:
                  type: integer
                  minimum: 1
                  description: Target position, from `GET /v1/positions`.
                  example: 7
                sub_position_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: >
                    Where your company uses sub-positions, the position pay is read
                    from. Leave it out if you do not use them.
                  example: 12
                effective_date:
                  type: string
                  format: date
                  description: First day in the new position, YYYY-MM-DD.
                  example: "2026-09-01"
                manager_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: New manager's user id. Defaults to the rep's current manager. Not checked for existence.
                  example: 87
                team_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: New team id. Defaults to the rep's current team. Changes the team label only, not team membership.
                  example: 4
                existing_employee_new_manager_id:
                  type: integer
                  minimum: 1
                  nullable: true
                  description: >
                    Who the rep's own direct reports answer to afterwards. Defaults
                    to the rep, so they keep their team. Send it only when moving
                    someone out from over their reports.
                  example: 87
            examples:
              promotion:
                summary: Promote a rep to a manager position
                value:
                  position_id: 7
                  effective_date: "2026-09-01"
      responses:
        "200":
          description: Position change applied
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/ApiResponse'
                  - type: object
                    properties:
                      data:
                        type: object
                        properties:
                          requestedBy:
                            type: string
                            description: Name of the API credential your token belongs to.
                          user_id:
                            type: integer
                            description: The user whose position changed.
                          position_id:
                            type: integer
                            description: New position.
                          sub_position_id:
                            type: integer
                            nullable: true
                            description: New sub-position, or null when none was sent.
                          effective_date:
                            type: string
                            format: date
                            description: Date the change takes effect, YYYY-MM-DD.
              example:
                status: 200
                message: "Position change applied."
                data:
                  requestedBy: "acme"
                  user_id: 4821
                  position_id: 7
                  sub_position_id: null
                  effective_date: "2026-09-01"
        "400":
          description: Invalid id, body or field
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Path id is not a positive whole number
                  value:
                    status: 400
                    message: "Invalid user id"
                    data: {}
                bad_position:
                  summary: position_id missing or not a positive integer
                  value:
                    status: 400
                    message: "position_id is required and must be a positive integer. Look one up with GET /v1/positions."
                    data: {}
                bad_effective_date:
                  summary: effective_date missing or not a real date
                  value:
                    status: 400
                    message: "effective_date is required and must be a real calendar date in YYYY-MM-DD format."
                    data: {}
                bad_optional_id:
                  summary: Optional id not a positive integer
                  value:
                    status: 400
                    message: "sub_position_id must be a positive integer."
                    data: {}
        "401":
          description: Missing, malformed, expired or revoked token. Rejected before processing, so the body has only `message`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: Unauthorized
              example:
                message: "Unauthorized"
        "404":
          description: No user with that id
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 404
                message: "No user with id 4821."
                data:
                  requestedBy: "acme"
                  code: "NOT_FOUND"
        "422":
          description: The rep, position or team cannot be used
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                user_dismissed:
                  summary: The rep is dismissed
                  value:
                    status: 422
                    message: "User 4821 is dismissed and cannot change position."
                    data:
                      requestedBy: "acme"
                      code: "USER_DISMISSED"
                position_not_found:
                  summary: Unknown position or sub-position
                  value:
                    status: 422
                    message: "No position with id 7."
                    data:
                      requestedBy: "acme"
                      code: "POSITION_NOT_FOUND"
                team_not_found:
                  summary: Unknown team
                  value:
                    status: 422
                    message: "No team with id 4."
                    data:
                      requestedBy: "acme"
                      code: "TEAM_NOT_FOUND"
        "500":
          description: The position change could not be applied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "The position change could not be applied."
                data:
                  requestedBy: "acme"
                  code: "POSITION_CHANGE_FAILED"
        "502":
          description: Sequifi could not complete the request. Retry later with the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 502
                message: "The tenant returned an unreadable response"
                data: {}
        "503":
          description: Your company is not set up for position changes over the API. Contact Sequifi support; this is not a problem with your token.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                not_configured:
                  summary: Not configured
                  value:
                    status: 503
                    message: "This tenant is not configured for position changes over the API. Contact Sequifi support."
                    data: {}
                not_provisioned:
                  summary: Not provisioned
                  value:
                    status: 503
                    message: "This tenant is not provisioned for Marketplace API writes. Contact Sequifi support."
                    data:
                      requestedBy: "acme"
                      code: "NOT_PROVISIONED"
        "504":
          description: No answer in time. The change may still have been applied; re-post the identical body.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 504
                message: "The tenant did not respond in time. The change may still have been applied — re-post the identical body, which converges rather than applying twice. Do not change effective_date on a retry."
                data:
                  user_id: 4821

  /v1/documents:
    get:
      operationId: listDocuments
      tags:
        - Documents
      summary: List documents
      description: |
        Lists file details for people in your company: uploaded onboarding documents, signed e-sign documents and profile photos. It returns no file contents and no links; exchange a document `id` for a short-lived link with `GET /v1/documents/{id}/download`. Your company must be set up for the Documents API, or every call returns `403`.

        **What happens:**

        - Read-only.
        - Three sources are combined. `manual`: uploaded documents such as a driver's license, W-9 or voided check (the latest version of each). `esign`: signed e-sign documents such as agreements and offer letters; unsigned and pending ones never appear. `photo`: profile photos; the default avatar is left out.

        **Filtering and paging:**

        - `user_id` alone matches the user's documents and those on the onboarding record they were hired from. Add `user_id_from=users` for the user's own documents only, or `user_id_from=onboarding_employees` to pass an onboarding id (from `GET /v1/onboarding`) instead of a user id.
        - `source` limits the list to `manual`, `esign` or `photo`. `document_type_id` filters uploads by type and implies `source=manual`.
        - `updated_since` takes `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` (UTC, a space, no `T` or zone). Inclusive. Use it for incremental sync.
        - Sorted by creation time, newest first. `per_page` defaults to 50, maximum 200. `last_page` is `0` when nothing matches.
        - Unknown query parameters are rejected with `400`.

        **Formats:**

        - `id` is a string such as `manual_19014`, `esign_9101`, `photo_u_57` (a user's photo) or `photo_oe_12` (an onboarding record's photo). Pass it to the download route unchanged.
        - `user_id` with `user_id_from` says whose document it is: `users` (a user id) or `onboarding_employees` (an onboarding id). Documents from before an API hire keep the onboarding id, so map both ids to the person.
        - `document_type` is `{id, name}`. `id` is set for uploads only. `name` is the upload type, the e-sign template name, or `Profile Photo`.
        - `file_name` is the file name only. Storage paths are never returned.
        - `file_version` is set for uploads only.
        - `signed` is `1` for e-sign documents and null otherwise (not a boolean). `signed_date` is when it was signed.
        - `created_at`, `updated_at` and `signed_date` are `"YYYY-MM-DD HH:MM:SS"` in UTC, with no `T` and no zone, unlike most other endpoints.
        - A photo's `updated_at` changes whenever anything on that person's record changes, so `updated_since` can return photos that did not change.
        - `filters` echoes the parameters you sent, as strings.

        **Errors:**

        - `400 Invalid query parameter(s)`, with `data.invalid_params` and `data.allowed_params`.
        - `400 per_page must be an integer between 1 and 200`, `400 page must be a positive integer`
        - `400 user_id must be a positive integer`, `400 document_type_id must be a positive integer`
        - `400 user_id_from must be one of: users, onboarding_employees`
        - `400 source must be one of: manual, esign, photo`
        - `400 document_type_id is only valid for source=manual`
        - `400 updated_since must be 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'`
        - `403 Documents API is not provisioned for this client`: contact Sequifi support.

        **Related:**

        - `GET /v1/documents/{id}/download` returns a download link for one document.
        - `GET /v1/users` and `GET /v1/onboarding` give the person ids.
      security:
        - bearerAuth: []
      parameters:
        - name: user_id
          in: query
          required: false
          schema: { type: integer, minimum: 1 }
          description: One person's documents. Alone, it matches the user and the onboarding record they were hired from. See `user_id_from`.
          example: 57
        - name: user_id_from
          in: query
          required: false
          schema: { type: string, enum: [users, onboarding_employees] }
          description: 'What `user_id` refers to: `users` (a user id, that user''s own documents only) or `onboarding_employees` (an onboarding id). Leave it out to match both for a user.'
        - name: source
          in: query
          required: false
          schema: { type: string, enum: [manual, esign, photo] }
          description: 'One source only: `manual` (uploads), `esign` (signed e-sign documents) or `photo` (profile photos).'
        - name: document_type_id
          in: query
          required: false
          schema: { type: integer, minimum: 1 }
          description: Upload type id, as returned in `document_type.id`. Implies `source=manual`.
        - name: updated_since
          in: query
          required: false
          schema: { type: string }
          description: Documents updated at or after this time, `YYYY-MM-DD` or `YYYY-MM-DD HH:MM:SS` in UTC (a space, no `T` or zone).
          example: "2026-07-01"
        - name: page
          in: query
          required: false
          schema: { type: integer, minimum: 1, default: 1 }
          description: Page number, starting at 1.
        - name: per_page
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
          description: Records per page. Default 50, maximum 200.
      responses:
        "200":
          description: One page of document details. An empty page is still a `200`.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      current_page:
                        type: integer
                        description: The page returned.
                      per_page:
                        type: integer
                        description: Page size used.
                      total:
                        type: integer
                        description: Number of documents that match.
                      last_page:
                        type: integer
                        description: Last page number. `0` when nothing matches.
                      filters:
                        type: object
                        nullable: true
                        description: The parameters you sent, as strings. Null when none.
                      documents:
                        type: array
                        description: Documents on this page, newest first.
                        items:
                          type: object
                          properties:
                            id:
                              type: string
                              description: Document id, for example `manual_19014`. Pass it to the download route.
                            source:
                              type: string
                              enum: [manual, esign, photo]
                              description: Where the document comes from.
                            user_id:
                              type: integer
                              description: The person's id. A user id or an onboarding id, per `user_id_from`.
                            user_id_from:
                              type: string
                              enum: [users, onboarding_employees]
                              description: What `user_id` refers to.
                            document_type:
                              type: object
                              description: '`{id, name}`. `id` is set for uploads only.'
                              properties:
                                id: { type: integer, nullable: true, description: Upload type id. Null for e-sign and photos. }
                                name: { type: string, nullable: true, description: 'Upload type, e-sign template name, or `Profile Photo`.' }
                            file_name:
                              type: string
                              description: File name only.
                            file_version:
                              type: integer
                              nullable: true
                              description: Upload version. Null for e-sign and photos.
                            signed:
                              type: integer
                              nullable: true
                              description: '`1` for signed e-sign documents, otherwise null.'
                            signed_date:
                              type: string
                              nullable: true
                              description: 'When it was signed, `YYYY-MM-DD HH:MM:SS` UTC.'
                            created_at:
                              type: string
                              description: '`YYYY-MM-DD HH:MM:SS` UTC.'
                            updated_at:
                              type: string
                              description: '`YYYY-MM-DD HH:MM:SS` UTC.'
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  current_page: 1
                  per_page: 50
                  total: 3
                  last_page: 1
                  filters:
                    user_id: "57"
                  documents:
                    - id: "manual_19014"
                      source: manual
                      user_id: 57
                      user_id_from: users
                      document_type: { id: 7, name: "Front Of Drivers License" }
                      file_name: "Front Of Drivers License_1783369551_412.jpeg"
                      file_version: 2
                      signed: null
                      signed_date: null
                      created_at: "2026-06-30 14:11:41"
                      updated_at: "2026-06-30 14:11:41"
                    - id: "esign_9101"
                      source: esign
                      user_id: 3907
                      user_id_from: onboarding_employees
                      document_type: { id: null, name: "Rep Agreement" }
                      file_name: "Sales_Rep_Agreement_1783402612_88.pdf"
                      file_version: null
                      signed: 1
                      signed_date: "2026-06-28 09:02:10"
                      created_at: "2026-06-27 16:03:10"
                      updated_at: "2026-06-28 09:02:10"
                    - id: "photo_u_57"
                      source: photo
                      user_id: 57
                      user_id_from: users
                      document_type: { id: null, name: "Profile Photo" }
                      file_name: "1783369551blob"
                      file_version: null
                      signed: null
                      signed_date: null
                      created_at: "2026-05-02 08:00:12"
                      updated_at: "2026-06-30 14:12:02"
        "400":
          description: An unknown query parameter or an invalid value. The message names the parameter.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_param:
                  summary: Unknown query parameter
                  value:
                    status: 400
                    message: "Invalid query parameter(s)"
                    data:
                      invalid_params: [type]
                      allowed_params: [user_id, user_id_from, source, document_type_id, updated_since, page, per_page]
                invalid_source:
                  summary: source is not one of the three values
                  value:
                    status: 400
                    message: "source must be one of: manual, esign, photo"
                    data: {}
        "401":
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        "403":
          description: Your company is not set up for the Documents API. Contact Sequifi support.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Documents API is not provisioned for this client"
                data: {}
        "500":
          description: Unexpected server error. Safe to retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

  /v1/documents/{id}/download:
    get:
      operationId: getDocumentDownloadUrl
      tags:
        - Documents
      summary: Get a document download link
      description: |
        Exchanges a document `id` from `GET /v1/documents` for a signed download link that works for 10 minutes. Fetch the file right away and never store the link; call again for a fresh one.

        **What happens:**

        - Checks that the document still meets the list's rules (an unsigned e-sign document or the default avatar is never downloadable) and that its file exists.
        - Returns a link that downloads the file as an attachment named `file_name`.
        - Each link issued is logged against your API credentials and the document id. There is no other side effect, so retries are safe and each call returns a new link.

        **Formats:**

        - `download_url` is an HTTPS link. A `GET` on it returns the file itself, not JSON. Do not send your API token to it.
        - `expires_at` is a UTC timestamp about 10 minutes after the call. The link can stop working a little earlier, so use it at once.

        **Errors:**

        - `400 Invalid document id`: not in the form `manual_<n>`, `esign_<n>`, `photo_u_<n>` or `photo_oe_<n>`.
        - `400 Cannot use query parameters on the download route`
        - `403 Documents API is not provisioned for this client`: contact Sequifi support.
        - `404 Document not found`: no such document, or it is not downloadable (for example an unsigned e-sign document).
        - `404 File not found in storage`: the document exists but its file is missing. Retrying does not help.
        - `500 Internal Server Error`: a storage problem on our side. Retry later.
        - A `403` from the download link itself (an XML body, not JSON) means the link expired or was changed. Request a new one.

        **Related:**

        - `GET /v1/documents` lists document ids.
      security:
        - bearerAuth: []
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, example: "manual_19014" }
          description: 'Document id from `GET /v1/documents`: `manual_<n>`, `esign_<n>`, `photo_u_<n>` or `photo_oe_<n>`.'
      responses:
        "200":
          description: A download link, valid for about 10 minutes.
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: integer
                    description: Same as the HTTP status code.
                    example: 200
                  message:
                    type: string
                    example: success
                  data:
                    type: object
                    properties:
                      requestedBy:
                        type: string
                        description: Label of the API credentials that made the call.
                      document_id:
                        type: string
                        description: The document id you sent.
                      file_name:
                        type: string
                        description: File name the download is saved as.
                      download_url:
                        type: string
                        description: Signed HTTPS link to the file. Use it at once; do not store it.
                      expires_at:
                        type: string
                        description: UTC timestamp when the link expires, about 10 minutes after the call.
              example:
                status: 200
                message: success
                data:
                  requestedBy: "acme"
                  document_id: "manual_19014"
                  file_name: "Front Of Drivers License_1783369551_412.jpeg"
                  download_url: "https://files.example.com/presigned/...?X-Amz-Expires=600&X-Amz-Signature=..."
                  expires_at: "2026-07-10T18:25:00.000Z"
        "400":
          description: The document id is invalid, or query parameters were sent.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                invalid_id:
                  summary: Not a valid document id
                  value:
                    status: 400
                    message: "Invalid document id"
                    data: {}
                query_params:
                  summary: Query parameters sent
                  value:
                    status: 400
                    message: "Cannot use query parameters on the download route"
                    data: {}
        "401":
          description: 'Missing, unknown, expired or disabled token. Sent by the gateway as `{"message":"Unauthorized"}`, without `status` or `data`.'
          content:
            application/json:
              schema:
                type: object
                properties:
                  message: { type: string, example: Unauthorized }
              example:
                message: Unauthorized
        "403":
          description: Your company is not set up for the Documents API. Contact Sequifi support.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 403
                message: "Documents API is not provisioned for this client"
                data: {}
        "404":
          description: The document does not exist or is not downloadable, or its file is missing.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              examples:
                document_not_found:
                  summary: No downloadable document with this id
                  value:
                    status: 404
                    message: "Document not found"
                    data: {}
                file_missing:
                  summary: The document exists but its file is missing
                  value:
                    status: 404
                    message: "File not found in storage"
                    data: {}
        "500":
          description: A storage problem on our side. Retry later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ApiResponse'
              example:
                status: 500
                message: "Internal Server Error"
                data: {}

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >
        An API token for one Sequifi company, sent as
        `Authorization: Bearer <token>` on every call. The token decides which
        company's data you read and write; there is no company id parameter.
        A missing, unknown, expired or disabled token gets `401`. See the
        Authentication guide for how tokens are issued and refreshed.

  schemas:
    PostSaleRecord:
      type: object
      required:
        - pid
        - customer_name
        - customer_signoff
      description: >
        One sale for `POST /v1/sales`. A new record needs `pid`,
        `customer_name`, `customer_signoff` and the fields your vertical
        requires: Solar `customer_state` and `location_code`; Turf `kw` and the
        same two (a company can be configured without state and location);
        Roofing `kw` and `gross_account_value`; Pest and Fiber
        `gross_account_value`; Mortgage `customer_state` and `location_code`
        only for companies configured to require them. An update to a sale
        Sequifi already has needs only `pid`; fields you leave out keep their
        current values. People are matched slot by
        slot (first match wins): an id field, then an email, then a flexible
        id. The product is matched by `sale_product_name` or `product_id`. See
        each field for the details.
      properties:
        pid:
          type: string
          maxLength: 255
          description: >
            Your unique id for the sale, as a string (a JSON number is
            rejected). Leading and trailing spaces are trimmed. At most 255
            characters and unique within the request. The same `pid` always
            refers to the same sale.
          example: "SALE-10482"
        customer_name:
          type: string
          minLength: 2
          maxLength: 255
          description: Customer (borrower) name, 2 to 255 characters.
          example: "Alex Morgan"
        customer_signoff:
          type: string
          format: date
          description: >
            The sale date (the closing date for Mortgage), `YYYY-MM-DD`.
            Required on every vertical. Milestone dates may not be earlier than
            this date, or processing rejects the record. Only the pattern is
            checked: an impossible date is rolled forward (`2026-02-30` is
            saved as `2026-03-02`) and a month above 12 is saved empty, so
            validate dates before sending.
          example: "2026-05-01"
          x-vertical-labels:
            solar:    "Sale Date"
            turf:     "Sale Date"
            roofing:  "Sale Date"
            pest:     "Sale Date"
            fiber:    "Sale Date"
            mortgage: "Closing Date"
        customer_email:
          type: string
          format: email
          example: "alex.morgan@example.com"
        customer_phone:
          type: string
          example: "555-010-4821"
        customer_address:
          type: string
          example: "1200 Desert Willow Rd"
        customer_address_2:
          type: string
          example: "Unit 4"
        customer_city:
          type: string
          example: "Phoenix"
        customer_state:
          type: string
          description: >
            Customer state. Required for Solar, for Turf unless your company is
            configured without it, and for Mortgage only if your company is
            configured to require it; 2 to 100 characters when required.
          example: "AZ"
        customer_zip:
          type: string
          example: "85001"
        location_code:
          type: string
          description: >
            Location (office region) code, usually the state code. Required
            under the same rules as `customer_state`, 2 to 100 characters. If
            you leave it out, Sequifi uses the state code for a full state name
            in `customer_state` (exact spelling), or `customer_state` as sent.
          example: "AZ"
        homeowner_id:
          type: string
          description: Your customer or homeowner id. Saved as sent.
          example: "HO-55120"
        sale_product_name:
          type: string
          description: >
            The product name or a product code. Matched case-insensitively but
            otherwise exactly (spaces count). Tried before `product_id`. On a
            new record, a value that matches nothing puts the sale on your
            company's default product and adds a warning to `data.warnings[]`.
          example: "Solar Rooftop"
        product_id:
          oneOf:
            - type: integer
            - type: string
          description: >
            The integer product `id` from `GET /v1/products` (a name or code
            string also works). Matching order: `sale_product_name`, or this
            value when that is absent, as a product name, then as a product
            code (any code in `product_codes` on `GET /v1/products`); then
            this value as the `id` of an active product. A number that is also
            a product code matches the code. If nothing matches, a new record
            goes to your company's default product (its lowest-numbered
            product), an update keeps the sale's current product, and either
            way `data.warnings[]` says so. Inactive products do not match by
            `id`.
          example: 12
        kw:
          type: number
          description: >
            Required for Turf and Roofing (square feet). Optional for Solar (kW):
            a solar sale without it is created with `0`, and commission
            calculates once it is sent. A number or numeric string; `$`, commas and spaces are removed. A value that
            cannot be read is saved as `0`, and so is `null` on an update.
          example: 7.2
          x-vertical-labels:
            solar:    "KW"
            turf:     "Sq Ft"
            roofing:  "Sq Ft"
            pest:     null
            fiber:    null
            mortgage: null
        gross_account_value:
          type: number
          description: >
            Required for Roofing, Pest and Fiber (the loan amount for
            Mortgage). A number or numeric string; `$`, commas and spaces are
            removed. A value that cannot be read is saved as `0`, and so is
            `null` on an update.
          example: 27720
          x-vertical-labels:
            solar:    "Gross Account Value"
            turf:     "Gross Account Value"
            roofing:  "Gross Account Value"
            pest:     "Gross Account Value"
            fiber:    "Gross Account Value"
            mortgage: "Loan Amount"
        epc:
          type: number
          description: >
            Gross price per unit (gross revenue for Mortgage). A number or
            numeric string, saved with 4 decimals.
          example: 3.85
          x-vertical-labels:
            solar:    "EPC"
            turf:     "Gross $ / Sq ft"
            roofing:  "Gross $ / Sq ft"
            pest:     null
            fiber:    null
            mortgage: "Gross Revenue"
        net_epc:
          type: number
          description: >
            Net price per unit (Solar, Turf, Roofing), saved as sent. For
            Mortgage, the fee as a fraction (`0.0325` for 3.25%); Sequifi
            multiplies it by 100 when saving. Ignored for Pest, Fiber and other
            verticals.
          example: 3.2
          x-vertical-labels:
            solar:    "Net EPC"
            turf:     "Net $ / Sq ft"
            roofing:  "Net $ / Sq ft"
            pest:     null
            fiber:    null
            mortgage: "Fee %"
        adders:
          type: number
          description: Adders total (the broker fee for Mortgage). A number or numeric string.
          example: 1100
          x-vertical-labels:
            solar:    "Adders"
            turf:     "Adders"
            roofing:  "Adders"
            pest:     null
            fiber:    null
            mortgage: "Broker Fee"
        adders_description:
          type: string
          description: Text describing the adders.
          example: "Critter guard, main panel upgrade"
        dealer_fee_amount:
          type: number
          description: Dealer fee in dollars. A number or numeric string.
          example: 4158
          x-vertical-labels:
            solar:    "Dealer Fee $"
            turf:     "Dealer Fee $"
            roofing:  "Dealer Fee $"
            pest:     null
            fiber:    null
            mortgage: "Credit Report"
        dealer_fee_percentage:
          type: number
          description: Dealer fee as a fraction. A number or numeric string.
          example: 0.15
          x-vertical-labels:
            solar:    "Dealer Fee %"
            turf:     "Dealer Fee %"
            roofing:  "Dealer Fee %"
            pest:     null
            fiber:    null
            mortgage: "Appraisal Fee"
        install_partner:
          type: string
          description: Installer, service provider or broker name. Saved as sent.
          example: "Brightline Solar"
          x-vertical-labels:
            solar:    "Installer"
            turf:     "Installer"
            roofing:  "Installer"
            pest:     "Service Provider"
            fiber:    "Service Provider"
            mortgage: "Broker"
        service_schedule:
          type: string
          description: Service schedule (loan type for Mortgage). Free text, saved as sent.
          example: "Quarterly"
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Service Schedule"
            fiber:    "Service Schedule"
            mortgage: "Loan Type"
        length_of_agreement:
          type: string
          maxLength: 255
          description: Length of the service agreement. Free text, saved as sent.
          example: "12 months"
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Length Of Agreement"
            fiber:    "Length Of Agreement"
            mortgage: null
        initial_service_cost:
          type: number
          description: Up-front service cost in dollars.
          example: 149
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Initial Service Cost"
            fiber:    "Initial Service Cost"
            mortgage: null
        subscription_payment:
          type: number
          description: Recurring subscription payment in dollars.
          example: 62.5
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Subscription Payment"
            fiber:    "Subscription Payment"
            mortgage: null
        card_on_file:
          type: boolean
          description: Whether a payment card is on file. Must be a JSON boolean.
          example: true
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Card on file"
            fiber:    "Card on file"
            mortgage: null
        auto_pay:
          type: boolean
          description: Whether autopay is on. Must be a JSON boolean.
          example: true
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Autopay"
            fiber:    "Autopay"
            mortgage: null
        service_completed:
          type: integer
          description: Number of services completed. A whole number.
          example: 1
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Services Completed"
            fiber:    "Services Completed"
            mortgage: null
        bill_status:
          type: string
          maxLength: 255
          description: Billing status label. Free text, saved as sent.
          example: "Current"
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Bill Status"
            fiber:    "Bill Status"
            mortgage: null
        balance_age:
          type: integer
          description: Age of the outstanding balance in days. A whole number.
          example: 0
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Balance Age (Days)"
            fiber:    "Balance Age (Days)"
            mortgage: null
        last_service_date:
          type: string
          format: date
          description: Date of the most recent service, `YYYY-MM-DD`.
          example: "2026-04-21"
          x-vertical-labels:
            solar:    null
            turf:     null
            roofing:  null
            pest:     "Last Service Date"
            fiber:    "Last Service Date"
            mortgage: null
        date_cancelled:
          type: string
          format: date
          description: Cancellation date, `YYYY-MM-DD`. A sale with this date reads back with `job_status` `Cancelled`.
          example: "2026-08-01"
        scheduled_install:
          type: string
          format: date
          nullable: true
          description: >
            Planned install date, `YYYY-MM-DD`. Not a milestone. On an update,
            `null` clears it; leave the field out to keep it.
          example: "2026-05-20"
        job_status:
          type: string
          maxLength: 255
          description: >
            Your status label, saved on the sale. `GET /v1/sales` does not
            return it: its `job_status` is calculated from the sale's dates.
          example: "Installed"
          x-vertical-labels:
            solar:    "Job Status"
            turf:     "Job Status"
            roofing:  "Job Status"
            pest:     "Job Status"
            fiber:    "Job Status"
            mortgage: "Status"
        external_job_status:
          type: string
          maxLength: 255
          description: Your system's status label (for example a loan status). Saved as sent.
          example: "Clear to Close"
        proposal_id:
          type: string
          maxLength: 255
          description: Your proposal id. Saved as sent.
          example: "PROP-2026-0042"
        closer1_id:
          type: integer
          description: >
            Closer 1 user id from `GET /v1/users`. Checked first for closer 1.
            Must be a whole number. Only the first id field present
            (`closer1_id`, then `rep_id`, then `sub_dealer_eid`) is tried; if it
            matches no user, matching moves to `closer_email`. A JSON number is
            matched to the user id; a numeric string is tried as an employee id
            first. Dismissed or terminated users can be matched.
          example: 4821
          x-vertical-labels:
            solar:    "Closer 1"
            turf:     "Closer 1"
            roofing:  "Closer 1"
            pest:     "Sales Rep 1"
            fiber:    "Sales Rep 1"
            mortgage: "MLO"
        rep_id:
          type: integer
          description: >
            Closer 1 user id or numeric employee id, used only when
            `closer1_id` is absent. Must be a whole number, else `400`.
          example: 4821
          x-vertical-labels:
            solar:    "Closer 1 ID"
            turf:     "Closer 1 ID"
            roofing:  "Closer 1 ID"
            pest:     "Sales Rep 1 ID"
            fiber:    "Sales Rep 1 ID"
            mortgage: "MLO ID"
        sub_dealer_eid:
          type: string
          description: >
            Closer 1 employee id (text allowed), used only when `closer1_id`
            and `rep_id` are absent.
          example: "EMP-0042"
        closer_email:
          type: string
          format: email
          description: >
            Closer 1 email, tried when no id field matched. Matched without
            regard to case against each user's primary and additional emails;
            when two users share an email, the user with the higher id is
            matched. Must be a valid email. An email that matches no user leaves
            closer 1 empty; the sale still processes and the response does not
            warn.
          example: "jordan.reyes@example.com"
        closer1_email:
          type: string
          format: email
          description: Same as `closer_email`; used only when `closer_email` is absent.
          example: "jordan.reyes@example.com"
        closer1_flexible_id:
          type: string
          maxLength: 255
          description: >
            A flexible id stored on the user's profile in Sequifi, exact match.
            Tried last for closer 1, after the id fields and the email. Useful
            when your system knows reps only by its own id.
          example: "4e62e3a9b1b74693a7c62209f35fd651"
        rep_email:
          type: string
          format: email
          description: >
            Saved as the sale's rep email. It does not assign anyone: use
            `closer_email` or `closer1_id` to set closer 1. On a new record it
            is saved only when closer 1 was matched (closer 1's email is used
            when you leave it out).
          example: "jordan.reyes@example.com"
        closer2_id:
          type: integer
          description: >
            Closer 2 user id, tried before `closer2_email` and
            `closer2_flexible_id`. Must be a whole number.
          example: 4822
          x-vertical-labels:
            solar:    "Closer 2 ID"
            turf:     "Closer 2 ID"
            roofing:  "Closer 2 ID"
            pest:     "Sales Rep 2 ID"
            fiber:    "Sales Rep 2 ID"
            mortgage: "Coordinator ID"
        closer2_email:
          type: string
          format: email
          description: >
            Closer 2 email, matched like `closer_email`. Must be a valid email.
            No match leaves closer 2 empty (unchanged on an update), without a
            warning.
          example: "avery.stone@example.com"
          x-vertical-labels:
            solar:    "Closer 2 Email"
            turf:     "Closer 2 Email"
            roofing:  "Closer 2 Email"
            pest:     "Sales Rep 2 Email"
            fiber:    "Sales Rep 2 Email"
            mortgage: "Coordinator Email"
        closer2_flexible_id:
          type: string
          maxLength: 255
          description: Closer 2 flexible id, tried after `closer2_id` and `closer2_email`.
          example: "c3a5f7b9d1e3a5c7b9d1e3a5c7b9d1e3"
        setter1_id:
          type: integer
          description: >
            Setter 1 user id, tried before `setter_email` and
            `setter1_flexible_id`. Must be a whole number.
          example: 5310
          x-vertical-labels:
            solar:    "Setter 1 ID"
            turf:     "Setter 1 ID"
            roofing:  "Setter 1 ID"
            pest:     null
            fiber:    null
            mortgage: "LOA ID"
        setter_email:
          type: string
          format: email
          description: >
            Setter 1 email, matched like `closer_email`. Must be a valid email.
            No match leaves setter 1 empty (unchanged on an update), without a
            warning.
          example: "casey.lee@example.com"
        setter1_flexible_id:
          type: string
          maxLength: 255
          description: Setter 1 flexible id, tried after `setter1_id` and `setter_email`.
          example: "8a91c5f0d2e34a1b9c3e5f7a8b1d2c4e"
        setter2_id:
          type: integer
          description: >
            Setter 2 user id, tried before `setter2_email` and
            `setter2_flexible_id`. Must be a whole number.
          example: 5311
          x-vertical-labels:
            solar:    "Setter 2 ID"
            turf:     "Setter 2 ID"
            roofing:  "Setter 2 ID"
            pest:     null
            fiber:    null
            mortgage: "Processor ID"
        setter2_email:
          type: string
          format: email
          description: Setter 2 email, matched like `closer_email`. Must be a valid email.
          example: "quinn.hall@example.com"
          x-vertical-labels:
            solar:    "Setter 2 Email"
            turf:     "Setter 2 Email"
            roofing:  "Setter 2 Email"
            pest:     null
            fiber:    null
            mortgage: "Processor Email"
        setter2_flexible_id:
          type: string
          maxLength: 255
          description: Setter 2 flexible id, tried after `setter2_id` and `setter2_email`.
          example: "b2f4d6e8a0c2e4f6a8b0c2d4e6f8a0b2"
        milestone_dates:
          type: array
          description: >
            Milestone dates for the sale's product, one entry per milestone.
            `milestone_id` is the milestone id from `GET /v1/milestones`
            (`milestones[].id`, not the schema `id`); a value that is not a
            milestone id is read as a position (1 = first milestone). Nothing
            checks that the milestone belongs to the sale's product. Sequifi
            sorts the entries into milestone order and saves them by position
            with no gaps: entry 1 becomes the first milestone, entry 2 the
            second. Sending only the third milestone saves its date as the
            first milestone and clears the rest, so send one entry for every
            milestone in the product's schema, in order, with
            `milestone_date: null` for those not reached yet. The list replaces
            the sale's milestone dates: a milestone you leave out is treated as
            removed, and removing or changing a paid milestone gets the record
            rejected during processing. On an update, `[]`, `null` or any value
            that is not a list clears every milestone date; leave the field out
            to keep them. Each entry's `product_id` is required but not used:
            the sale's product comes from `sale_product_name` or `product_id`
            on the record.
          items:
            type: object
            required: [product_id, milestone_id]
            properties:
              product_id:
                type: integer
                description: The sale's product `id`. Required, but not used.
                example: 12
              milestone_id:
                type: integer
                minimum: 1
                description: >
                  The milestone id (`milestones[].id` from `GET /v1/milestones`).
                  A value that is not a milestone id is read as a position
                  (1 = first milestone).
                example: 41
              milestone_date:
                type: string
                format: date
                nullable: true
                description: >
                  `YYYY-MM-DD`, or `null` (or `""`) for a milestone not reached
                  yet. Only the pattern is checked.
                example: "2026-05-08"
          example:
            - { product_id: 12, milestone_id: 41, milestone_date: "2026-05-08" }
            - { product_id: 12, milestone_id: 42, milestone_date: null }
        m1_date:
          type: string
          format: date
          description: >
            Legacy. The first milestone's date, `YYYY-MM-DD`, used on a new
            record only when no `milestone_dates` entry is the first milestone.
            Ignored on updates. Use `milestone_dates`.
          example: "2026-05-08"
        custom_field_values:
          type: object
          description: >
            Values for your company's sales custom fields, keyed by field `id`
            from `GET /v1/custom-fields?type=sales` (as a string key such as
            `"7"`) or by the exact field name (capitals and spaces must match).
            Prefer ids. `number` fields take a number and `date` fields take
            `YYYY-MM-DD`; on a new record, a wrong value or an unknown key
            returns `400` (or a `rejected[]` entry with `partial_success`). Text
            values are never rejected. A select field takes one option label; a
            multi-select field takes a JSON array or one string separated by
            semicolons (`"Roof; Attic"`). Values are trimmed, de-duplicated and
            given the configured option's capitals (`shingle` is saved as
            `Shingle`); a value that is not a configured option is saved as
            sent. `null` and `""` are skipped, so a value cannot be cleared
            through the API. On an update, values merge into the sale's
            existing values, and an unknown field name (dropped) or a
            wrong-typed value (saved as sent) is listed in `data.warnings[]`.
            Archived fields still accept values. Do not send values for fields
            with `is_calculated: true`.
          example:
            "7": "Shingle"
            "9": 18
            "12": ["Roof", "Attic"]
        external_workers:
          type: array
          description: >
            Extra people credited on the sale (for example a second loan
            officer or a disclosure desk). Leave the field out to keep the
            current list; `[]` removes all of them; a list replaces the people
            for each `type` it mentions and keeps the other types. Each entry
            is matched by email (primary or additional), else by exact full
            name in `first last` order (capitals and extra spaces ignored; `last
            first` does not match; when two users share a name, the lower id
            wins). An entry that matches no one is skipped without a warning.
            Checked on new records and updates; a malformed entry returns `400`.
          items:
            type: object
            required: [type]
            anyOf:
              - required: [email]
              - required: [name]
            properties:
              email:
                type: string
                format: email
                description: The person's email. Send `email`, `name` or both; email is tried first.
                example: "dana.kim@example.com"
              name:
                type: string
                maxLength: 255
                description: Full name in `first last` order.
                example: "Sam Ortiz"
              type:
                type: integer
                enum: [1, 2, 3]
                description: "1 self-gen, 2 closer, 3 setter."
                example: 2
          example:
            - { email: "dana.kim@example.com", type: 2 }
            - { name: "Sam Ortiz", type: 3 }
        data_source_type:
          type: string
          maxLength: 255
          description: >
            Leave this out. Sequifi labels sales sent through this API
            `Marketplace API`. A value you send replaces that label on this
            copy of the sale, and an empty string is rejected.
          example: "Marketplace API"

    PostSalesResult:
      type: object
      description: The `data` object returned by `POST /v1/sales` with `200` or `201`.
      properties:
        requestedBy:
          type: string
          description: Your company's Sequifi handle.
        recordsInserted:
          type: integer
          description: New sales queued. Updates to sales Sequifi already has count in `recordsPatched`.
        recordsPatched:
          type: integer
          description: Updates merged into a held copy.
        recordsProcessed:
          type: integer
          description: >
            `recordsInserted` plus `recordsPatched`. `0` means nothing was
            saved. With `partial_success`, a rejected update is still counted
            here.
        recordsRejected:
          type: integer
          description: Number of entries in `rejected`. Returned only with `partial_success`.
        rejected:
          type: array
          description: Records that failed a check. Returned only with `partial_success`.
          items:
            type: object
            properties:
              index:
                type: integer
                description: Position of the record in your `data` array, starting at 0.
              pid:
                type: string
                nullable: true
                description: The record's `pid`.
              messages:
                type: array
                description: The problems, without the `Record [i]:` prefix.
                items: { type: string }
        warnings:
          type: array
          description: >
            Returned only when not empty. Lists fields that were ignored
            (unknown top-level fields), products that matched nothing, and, on
            updates, custom field values that were dropped or saved with the
            wrong type. It does not list unmatched people.
          items: { type: string }
        sales:
          type: array
          description: >
            The latest queued copy of each `pid` in the request (rejected new
            records have none). This is the copy waiting for processing, not
            the processed sale.
          items:
            $ref: '#/components/schemas/StagedSale'

    StagedSale:
      type: object
      description: >
        The queued copy of a sale as saved by `POST /v1/sales`, with empty
        fields left out. Other internal fields with default values also appear;
        ignore fields not listed here.
      properties:
        id:
          type: integer
          description: Id of this queued copy. Not the sale `id` that `GET /v1/sales` returns.
        pid:
          type: string
          description: Your sale id.
        customer_name:
          type: string
          description: Customer name.
        customer_signoff:
          type: string
          format: date-time
          description: Sale date as a midnight UTC timestamp, for example `2026-05-01T00:00:00.000Z`.
        product_id:
          type: integer
          description: The matched product `id`. Compare it with the product you sent to catch a default-product fallback.
        product_code:
          type: string
          description: The matched product code, in lower case.
        product:
          type: string
          description: The matched product name.
        closer1_id:
          type: integer
          description: The matched closer 1 user id. Missing when no closer was matched.
        closer2_id:
          type: integer
          description: The matched closer 2 user id.
        setter1_id:
          type: integer
          description: The matched setter 1 user id. Missing when no setter was matched.
        setter2_id:
          type: integer
          description: The matched setter 2 user id.
        sales_rep_email:
          type: string
          description: The sale's rep email.
        data_source_type:
          type: string
          description: The sale's source label, normally `Marketplace API`.
        custom_field_values:
          type: object
          description: Custom field values on this copy, keyed by field name. Always present; `{}` when there are none.

    Sale:
      type: object
      description: >
        A processed sale as Sequifi holds it now, returned by `GET /v1/sales`
        and `GET /v1/sales/{pid}`. Every field is always present, with `null`
        when empty.
      properties:
        id:
          type: integer
          description: Sequifi's sale id. Not the `id` in the `POST /v1/sales` response.
        pid:
          type: string
          description: Your sale id, as sent on `POST /v1/sales`.
        customer_name:
          type: string
          description: Customer (borrower) name.
        data_source_type:
          type: string
          nullable: true
          description: Where the sale came from. `Marketplace API` for sales sent through this API.
        job_status:
          type: string
          enum: [Pending, Serviced, Cancelled, Clawback]
          description: >
            Calculated when you read it, in this order: `Clawback` when a
            clawback is shown on the sale, else `Cancelled` when
            `date_cancelled` is set, else `Serviced` when any milestone date is
            set, else `Pending`. A `job_status` you sent is not returned.
        product_id:
          type: integer
          nullable: true
          description: >
            The product `id`. When Sequifi recorded an original product for the
            sale, this and the other product fields show that original product.
        product_code:
          type: string
          nullable: true
          description: The product code.
        product_name:
          type: string
          description: >
            `Name - CODE`, or `Sale product name (Name) - CODE` when the
            product name you sent differs. Empty when the sale has no product.
        org_product_id:
          type: string
          nullable: true
          description: The product code (despite the field name).
        customer_state:
          type: string
          nullable: true
          description: Customer state.
        customer_address:
          type: string
          nullable: true
          description: Street address, as sent on `POST /v1/sales`.
        customer_address_2:
          type: string
          nullable: true
          description: Second address line, such as a unit number.
        customer_city:
          type: string
          nullable: true
          description: Customer city.
        customer_zip:
          type: string
          nullable: true
          description: Customer ZIP code.
        customer_phone:
          type: string
          nullable: true
          description: Customer phone number, as sent.
        customer_email:
          type: string
          nullable: true
          description: Customer email address.
        last_milestone:
          type: object
          nullable: true
          description: >
            The milestone line with the latest date (ties go to the larger
            amount). `null` when no milestone has a date.
          properties:
            name:
              type: string
              description: Milestone name.
            trigger:
              type: string
              description: Label of the date that triggers the milestone.
            value:
              type: number
              description: Amount of this line in dollars.
            date:
              type: string
              format: date-time
              description: Milestone date as a midnight UTC timestamp.
        last_payment:
          type: number
          description: The amount of `last_milestone`, or `0` when no milestone has a date.
        all_milestone:
          type: array
          description: >
            One entry per commission line on the sale, so the same milestone can
            appear more than once (for example once for the closer and once for
            the setter). A sale with no commission lines has none. An extra
            entry named `Recon` is added when reconciliation is on.
          items:
            $ref: '#/components/schemas/SaleMilestone'
        milestone_dates:
          type: array
          description: >
            The sale's milestone dates in the shape `POST /v1/sales` takes, one
            entry per milestone. Includes dates on sales that have no
            `all_milestone[]` entries.
          items:
            $ref: '#/components/schemas/SaleMilestoneDate'
        commission_lines:
          type: array
          description: >
            Every commission and override line on the sale, with its payroll
            status. Empty when the sale has none.
          items:
            $ref: '#/components/schemas/SaleCommissionLine'
        total_commission:
          type: string
          description: Total commission in dollars with 2 decimals, including reconciliation.
        projected_commission:
          type: integer
          description: '`1` when the commission amounts are still projected, `0` when final. A flag, not an amount.'
        total_override:
          type: string
          description: Total override in dollars.
        projected_override:
          type: integer
          description: '`1` when the override amounts are still projected, `0` when final.'
        kw:
          type: string
          nullable: true
          description: System size in kW (square feet for Turf and Roofing), as text.
        epc:
          type: string
          nullable: true
          description: Gross price per unit, as text with 4 decimals.
        net_epc:
          type: number
          nullable: true
          description: >
            Net price per unit. For Mortgage it is returned multiplied by 100,
            so it does not equal the value you sent.
        adders:
          type: string
          nullable: true
          description: Adders total, as text.
        gross_account_value:
          type: number
          nullable: true
          description: Gross account value (loan amount for Mortgage) in dollars.
        service_completed:
          type: string
          nullable: true
          description: Number of services completed, as text.
        date_cancelled:
          type: string
          format: date-time
          nullable: true
          description: Cancellation date as a midnight UTC timestamp.
        customer_signoff:
          type: string
          format: date-time
          nullable: true
          description: >
            Sale date (closing date for Mortgage) as a midnight UTC timestamp,
            for example `2026-05-01T00:00:00.000Z`. Compare the first 10
            characters with the date you sent.
        install_partner:
          type: string
          nullable: true
          description: Installer, service provider or broker.
        service_schedule:
          type: string
          nullable: true
          description: Service schedule (loan type for Mortgage).
        length_of_agreement:
          type: string
          nullable: true
          description: Length of the service agreement.
        initial_service_cost:
          type: string
          nullable: true
          description: Up-front service cost, as text.
        subscription_payment:
          type: string
          nullable: true
          description: Recurring subscription payment, as text.
        card_on_file:
          type: string
          nullable: true
          description: Whether a card is on file, as stored text.
        auto_pay:
          type: string
          nullable: true
          description: Whether autopay is on, as stored text.
        bill_status:
          type: string
          nullable: true
          description: Billing status label.
        balance_age:
          type: string
          nullable: true
          description: Age of the outstanding balance in days, as text.
        last_service_date:
          type: string
          format: date-time
          nullable: true
          description: Last service date as a midnight UTC timestamp.
        dealer_fee_amount:
          type: string
          nullable: true
          description: Dealer fee in dollars, as text.
        dealer_fee_percentage:
          type: string
          nullable: true
          description: Dealer fee as a fraction, as text.
        is_exempted:
          type: integer
          description: '`1` when the sale is exempt from clawback, else `0`.'
        sales_type:
          type: string
          description: Sale type label, for example `Sales`.
        created_at:
          type: string
          format: date-time
          description: When Sequifi created the sale (UTC).
        updated_at:
          type: string
          format: date-time
          description: When Sequifi last changed the sale (UTC). Use it with `updated_after` to poll.
        mark_account_status_name:
          type: string
          nullable: true
          enum: [Clawed Back, Paid, null]
          description: '`Clawed Back` when a clawback is shown, `Paid` when any commission on the sale has been paid, else `null`.'
        closer1_detail:
          allOf:
            - $ref: '#/components/schemas/SalePerson'
          nullable: true
          description: Closer 1, or `null`.
        closer2_detail:
          allOf:
            - $ref: '#/components/schemas/SalePerson'
          nullable: true
          description: Closer 2, or `null`.
        setter1_detail:
          allOf:
            - $ref: '#/components/schemas/SalePerson'
          nullable: true
          description: Setter 1, or `null`.
        setter2_detail:
          allOf:
            - $ref: '#/components/schemas/SalePerson'
          nullable: true
          description: Setter 2, or `null`.
        custom_field_values:
          type: object
          description: >
            The sale's current custom field values keyed by field name (as in
            `GET /v1/custom-fields?type=sales`), including edits made in the
            app. Values are returned as stored: numbers as numbers, dates as
            `YYYY-MM-DD`, multi-select values as arrays. `{}` when the sale has
            none; fields deleted from your configuration are left out.

    SalePerson:
      type: object
      description: A person on a sale.
      properties:
        id:
          type: integer
          description: User id.
        first_name:
          type: string
          description: First name.
        last_name:
          type: string
          description: Last name.
        dismiss:
          type: integer
          description: '`1` when the user is dismissed.'
        terminate:
          type: integer
          description: '`1` when the user is terminated.'
        contract_ended:
          type: integer
          description: '`1` when the user''s contract has ended.'
        stop_payroll:
          type: integer
          description: '`1` when payroll is stopped for the user.'

    SaleMilestone:
      type: object
      description: One commission line on a sale, tied to a milestone.
      properties:
        name:
          type: string
          nullable: true
          description: Milestone name, or `Recon` for the reconciliation entry.
        trigger:
          type: string
          nullable: true
          description: Label of the date that triggers the milestone. `null` for `Recon`.
        milestone_id:
          type: integer
          nullable: true
          description: The milestone's id, the same `milestone_id` you send in `milestone_dates[]`. `null` for `Recon`.
        value:
          type: number
          description: Amount of this line in dollars.
        date:
          type: string
          format: date-time
          nullable: true
          description: Milestone date as a midnight UTC timestamp, or `null` when not reached.
        is_projected:
          type: integer
          description: '`1` when the amount is projected, `0` when final.'
        status:
          type: string
          nullable: true
          enum: [paid, approved, pending, do_not_pay, projected, null]
          description: >
            Payroll status of this rep's pay for the milestone. When the rep has
            more than one line for it (for example an M2 and an M2 update), the
            least settled one wins, in this order: `pending`, `approved`, `paid`,
            `do_not_pay`. `projected` when there is no line yet and the
            milestone is projected; `null` when there is no line and the
            milestone has a date, and for `Recon`. See `SaleCommissionLine`.

    SaleMilestoneDate:
      type: object
      description: One milestone date on a sale, in the shape `POST /v1/sales` takes in `milestone_dates[]`.
      properties:
        product_id:
          type: integer
          nullable: true
          description: Product id.
        milestone_id:
          type: integer
          description: Milestone id.
        milestone_date:
          type: string
          format: date
          nullable: true
          description: '`YYYY-MM-DD`, or `null` when the milestone has no date.'

    SaleCommissionLine:
      type: object
      description: One commission or override line on a sale, with its payroll status.
      properties:
        type:
          type: string
          enum: [commission, override]
        milestone:
          type: string
          nullable: true
          description: Milestone the line pays on, such as `m1`, `m2` or `m2 update`.
        milestone_id:
          type: integer
          nullable: true
          description: Milestone id for commission lines. `null` for overrides.
        user_id:
          type: integer
          description: The user paid by this line.
        amount:
          type: number
          description: Amount in dollars. `0` when the line has no amount.
        status:
          type: string
          enum: [paid, approved, pending, do_not_pay]
          description: >
            `paid`: settled on a payroll that ran, or marked paid.
            `approved`: on a payroll that is finalized or being paid.
            `pending`: on an open payroll, or not on a payroll yet.
            `do_not_pay`: closed without paying the rep.
        pay_period_from:
          type: string
          format: date
          nullable: true
        pay_period_to:
          type: string
          format: date
          nullable: true

    MilestoneSchema:
      type: object
      description: A milestone schema (payment plan) with its milestones in order and its linked products.
      properties:
        id:
          type: integer
          description: Schema id. Use it with `GET /v1/milestones/{id}`. Do not send it as a `milestone_id`.
        prefix:
          type: string
          description: Prefix for the milestone codes.
        schema_name:
          type: string
          description: Schema name.
        schema_description:
          type: string
          nullable: true
          description: Schema description.
        status:
          type: string
          enum: ["1", "0"]
          description: '`"1"` active, `"0"` inactive. A string.'
        milestone_trigger_count:
          type: integer
          description: Number of milestones in the schema.
        products:
          type: array
          description: >
            Products linked to the schema with an effective date of today (UTC)
            or earlier, including past links. Deleted products are left out.
          items:
            type: object
            properties:
              id:
                type: integer
                description: Product `id`, the value `POST /v1/sales` accepts as `product_id`.
              name:
                type: string
                description: Product name.
        milestones:
          type: array
          description: The schema's milestones in order.
          items:
            type: object
            properties:
              id:
                type: integer
                description: Milestone id. Send it as `milestone_dates[].milestone_id` on `POST /v1/sales`.
              code:
                type: string
                description: The schema `prefix` plus `order`, for example `M1`.
              name:
                type: string
                description: Milestone name.
              trigger_date_label:
                type: string
                description: Label of the date that triggers the milestone.
              order:
                type: integer
                description: Position in the schema, starting at 1.

    Product:
      type: object
      description: A product in your company's catalog.
      properties:
        id:
          type: integer
          description: Product id. Send it as `product_id` on `POST /v1/sales`.
        product_id:
          type: string
          description: The product code (not the id).
        product_codes:
          type: array
          items: { type: string }
          description: Every code `POST /v1/sales` matches for this product, in lowercase, starting with the `product_id` code when it matches. A code two products share is listed only on the product a sale lands on. An inactive product's `product_id` code does not match and is not listed. Empty when no code matches this product.
        name:
          type: string
          description: Product name.
        description:
          type: string
          nullable: true
          description: Product description.
        effective_date:
          type: string
          format: date
          nullable: true
          description: Effective date, `YYYY-MM-DD`.
        created_date:
          type: string
          description: When the product was created, `YYYY-MM-DD HH:MM:SS` with no time zone.
        updated_date:
          type: string
          description: When the product was last changed, `YYYY-MM-DD HH:MM:SS` with no time zone.
        status:
          type: string
          enum: [active, inactive]
          description: '`active` or `inactive`. The list returns active products only.'

    SalesCustomField:
      type: object
      description: A sales custom field definition (`GET /v1/custom-fields?type=sales`).
      properties:
        id:
          type: integer
          description: Field id. Use it as the key in `custom_field_values` on `POST /v1/sales`.
        name:
          type: string
          description: Field name. `GET /v1/sales` keys values by this name.
        type:
          type: string
          enum: [text, number, date, multi_select]
          description: >
            Value type. `number` takes a number and `date` takes `YYYY-MM-DD`.
            A single-select field is a `text` field with configured options;
            the options are not returned.
        field_category:
          type: string
          description: Field category as stored, for example `custom_sales`.
        is_calculated:
          type: boolean
          description: '`true` when Sequifi calculates the value from a formula. Do not send values for it.'
        is_available_in_position:
          type: boolean
          description: '`true` when the field can be used in position commission settings.'
        formula:
          type: object
          nullable: true
          description: The formula for a calculated field, else `null`.
        visiblecustomer:
          type: boolean
          description: '`true` when the field is shown on the customer view.'
        status:
          type: boolean
          description: Always `true` here (only active fields are listed).
        sort_order:
          type: integer
          description: Display order.
        created_at:
          type: string
          format: date-time
          nullable: true
          description: When the field was created (UTC).
        updated_at:
          type: string
          format: date-time
          nullable: true
          description: When the field was last changed (UTC).
        can_archive:
          type: boolean
          description: '`false` when commission, override or upfront settings use the field.'
        usage_details:
          type: object
          description: >
            Present only when the field is in use. Depending on your company's
            settings it holds `position_commissions` (`count` and `positions`)
            or `formulas`, `commissions`, `overrides` and `upfronts` (users
            keyed by id).

    GatewayError:
      type: object
      description: >
        Returned by the API gateway (for example a `401` for a missing,
        invalid or expired token). It has only `message`, not the usual
        `status` and `data`.
      properties:
        message:
          type: string
          example: "Unauthorized"

    # ── /v1/integration-raw-data record schemas ──────────────────────────────
    # Only the natural key is required. Fixed-field types drop unknown fields.

    EncompassRawDataRecord:
      type: object
      title: encompass
      description: >
        Encompass record (`integration_type: "encompass"`). Natural key:
        `loan_id`. Send `pid` on a new record: without it the whole request
        fails with `500`.
      required:
        - loan_id
      properties:
        loan_id:
          type: string
          maxLength: 255
          description: "Required. Unique loan id. Stored as a string."
          example: "95f78daa-bcc7-4f08-88ed-eb29a811d57d"
        pid:
          type: string
          description: "The sale id you will use on `POST /v1/sales`. Needed on a new record."
          example: "LN-2026-0042"
        homeowner_id:
          type: string
          description: "Homeowner id (up to 36 characters)."
          example: "00000000-0000-0000-0000-000000000123"
        customer_name:    { type: string, example: "Morgan Ellis" }
        customer_email:   { type: string, example: "morgan.ellis@example.com" }
        customer_mobile:  { type: string, maxLength: 20, example: "5550104821" }
        customer_address1: { type: string, example: "88 Live Oak Ln" }
        customer_address2: { type: string, example: "Unit 4" }
        customer_city:    { type: string, example: "Austin" }
        customer_state:   { type: string, maxLength: 2, description: "2-letter state code.", example: "TX" }
        customer_zip:     { type: string, maxLength: 10, example: "78701" }
        base_amount:      { type: string, description: "Loan base amount, as text.", example: "350000" }
        gross_revenue:    { type: string, description: "As text.", example: "3500" }
        credit_report_fee: { type: string, description: "As text.", example: "75" }
        loan_status:      { type: string, example: "Funded" }
        sale_date:        { type: string, format: date, description: "`YYYY-MM-DD`, checked as a real date. Cannot be cleared once set: `null` or `\"\"` keeps it.", example: "2026-05-15" }
        m1_date:          { type: string, format: date, example: "2026-05-20" }
        m2_date:          { type: string, format: date, example: "2026-06-15" }
        cancel_date:      { type: string, format: date, example: "2026-06-20" }
        product_name:     { type: string, example: "Conventional" }
        initial_advance_amount: { type: string, description: "As text.", example: "100000" }
        mlo:              { type: string, description: "Loan officer name.", example: "Morgan Hayes" }
        mlo_email:        { type: string, format: email, example: "morgan.hayes@example.com" }
        loa:              { type: string, description: "Loan officer assistant name.", example: "Dana Kim" }
        loa_email:        { type: string, format: email, example: "dana.kim@example.com" }
        processor:        { type: string, example: "Sam Ortiz" }
        processor_email:  { type: string, format: email, example: "sam.ortiz@example.com" }

    EnerfloRawDataRecord:
      type: object
      title: enerflo
      description: >
        Enerflo record (`integration_type: "enerflo"`). Natural key: `pid`
        (a number or a string, stored as a string).
      required:
        - pid
      properties:
        pid:
          oneOf: [ { type: string }, { type: integer } ]
          maxLength: 255
          description: "Required. The sale id. A number or a string; stored as a string."
          example: "EF-20931"
        customer_id:
          oneOf: [ { type: string }, { type: integer } ]
          example: 67890
        proposal_id:        { type: string, example: "PROP-2026-0042" }
        product_name:       { type: string, example: "Solar Rooftop" }
        customer_name:      { type: string, example: "Alex Morgan" }
        customer_email:     { type: string, format: email, example: "alex.morgan@example.com" }
        customer_phone:     { type: string, maxLength: 20, example: "555-010-4821" }
        customer_address:   { type: string, example: "1200 Desert Willow Rd" }
        customer_city:      { type: string, example: "Phoenix" }
        customer_state:     { type: string, example: "AZ" }
        location_code:      { type: string, maxLength: 10, example: "AZ" }
        customer_zip:       { type: string, maxLength: 10, example: "85001" }
        install_partner:    { type: string, example: "Brightline Solar" }
        gross_account_value:
          type: number
          description: "A number. Display label varies by vertical."
          example: 27720
          x-vertical-labels:
            solar:    "Gross Account Value"
            solar2:   "Gross Account Value"
            turf:     "Gross Account Value"
            roofing:  "Gross Account Value"
            pest:     "Gross Account Value"
            fiber:    "Gross Account Value"
            mortgage: "Loan Amount"
        kw:
          type: number
          description: "Display label varies by vertical."
          example: 7.2
          x-vertical-labels:
            solar:    "KW"
            solar2:   "KW"
            turf:     "Sq Ft"
            roofing:  null
            pest:     null
            fiber:    null
            mortgage: null
        epc:
          type: number
          description: "Display label varies by vertical."
          example: 3.85
          x-vertical-labels:
            solar:    "EPC"
            solar2:   "EPC"
            turf:     "Gross $ / Sq ft"
            roofing:  "EPC"
            pest:     "EPC"
            fiber:    "EPC"
            mortgage: "Gross Revenue"
        net_epc:
          type: number
          description: "Display label varies by vertical."
          example: 3.2
          x-vertical-labels:
            solar:    "Net EPC"
            solar2:   "Net EPC"
            turf:     "Net $ / Sq ft"
            roofing:  "Net EPC"
            pest:     "Net EPC"
            fiber:    "Net EPC"
            mortgage: "Fee %"
        dealer_fee:         { type: number, example: 4158 }
        dealer_fee_percentage:
          type: number
          description: "Display label varies by vertical."
          example: 0.15
          x-vertical-labels:
            solar:    "Dealer Fee %"
            solar2:   "Dealer Fee %"
            turf:     "Dealer Fee %"
            roofing:  "Dealer Fee %"
            pest:     null
            fiber:    null
            mortgage: "Appraisal Fee"
        adders_total:       { type: number, example: 1100 }
        system_cost_base_adders: { type: number, example: 28820 }
        job_status:         { type: string, example: "Install Scheduled" }
        sale_date:          { type: string, format: date, description: "`YYYY-MM-DD`, checked as a real date. Cannot be cleared once set: `null` or `\"\"` keeps it.", example: "2026-05-01" }
        cancel_date:        { type: string, format: date, nullable: true, example: null }
        m1_date:            { type: string, format: date, nullable: true, example: "2026-05-08" }
        m2_date:            { type: string, format: date, nullable: true, example: null }
        m3_date:            { type: string, format: date, nullable: true, example: null }
        sales_rep_id:
          oneOf: [ { type: string }, { type: integer } ]
          example: "4521"
        sales_rep_name:     { type: string, example: "Jordan Reyes" }
        sales_rep_email:    { type: string, format: email, example: "jordan.reyes@example.com" }
        setter_id:
          oneOf: [ { type: string }, { type: integer } ]
          example: "3310"
        setter_name:        { type: string, example: "Casey Lee" }
        setter_email:       { type: string, format: email, example: "casey.lee@example.com" }

    AriveRawDataRecord:
      type: object
      title: arive
      description: >
        Arive record (`integration_type: "arive"`). Natural key:
        `arive_loan_id`, unique per company. Send `total_loan_amount`,
        `dealer_fee`, `dealer_fee_percentage` and `sow_adder_fee` on a new
        record (`"0"` when you have no value): without them the whole request
        fails with `500`.
      required:
        - arive_loan_id
      properties:
        arive_loan_id:
          type: string
          maxLength: 255
          description: "Required. Arive's loan id."
          example: "AR-2026-0001"
        lender_loan_identifier: { type: string, description: "Homeowner id.", example: "LL-001" }
        lead_provided_by:    { type: string, description: "Lead source; often mapped to the product.", example: "Direct" }
        lender_name:         { type: string, description: "Lender name (install partner).", example: "Example Lending" }
        mortgage_type:       { type: string, description: "Mortgage type (service schedule).", example: "Conventional" }
        borrower_name:       { type: string, example: "Morgan Ellis" }
        borrower_email:      { type: string, format: email, example: "morgan.ellis@example.com" }
        borrower_phone:      { type: string, example: "5550104821" }
        borrower_address:    { type: string, example: "88 Live Oak Ln" }
        borrower_state:      { type: string, example: "TX" }
        borrower_city:       { type: string, example: "Austin" }
        borrower_zip:        { type: string, example: "78701" }
        total_loan_amount:   { type: string, description: "Total loan amount in dollars, as text. Needed on a new record.", example: "350000" }
        dealer_fee:          { type: string, description: "As text. Needed on a new record.", example: "1500" }
        dealer_fee_percentage: { type: string, description: "As text. Needed on a new record.", example: "0.5" }
        sow_adder_fee:       { type: string, description: "Broker fee amount, as text. Needed on a new record.", example: "0" }
        broker_compensation: { type: string, example: "1200" }
        compensation_type:
          type: string
          nullable: true
          maxLength: 255
          description: >
            Arive's compensation type, stored as sent (for example `Broker` or
            `Lender`). Can be mapped to the product instead of
            `lead_provided_by`. Leaving it out keeps the stored value; `null`
            clears it.
          example: "Broker"
        credit_report_fee:   { type: string, example: "75" }
        tolerance_cures_fee: { type: string, example: "0" }
        verification_fee:    { type: string, example: "0" }
        reimbursements:      { type: string, description: "Reimbursed fee amount as sent by Arive (the credit report fee when it is reimbursed).", example: "0" }
        loan_status:         { type: string, example: "Funded" }
        notes:               { type: string, example: "Standard processing" }
        loan_originator_email: { type: string, format: email, description: "Closer 1.", example: "morgan.hayes@example.com" }
        loan_originator2_email: { type: string, format: email, example: "avery.stone@example.com" }
        loan_officer_assistant_email: { type: string, format: email, description: "Setter 1.", example: "dana.kim@example.com" }
        loan_processor_email: { type: string, format: email, description: "Setter 2.", example: "sam.ortiz@example.com" }
        disclosure_desk_email: { type: string, format: email, example: "quinn.hall@example.com" }
        secondary_loan_originator_email: { type: string, format: email, example: "avery.stone@example.com" }
        sale_date:           { type: string, format: date, description: "`YYYY-MM-DD`, checked as a real date. Cannot be cleared once set: `null` or `\"\"` keeps it.", example: "2026-05-15" }
        m1_date:             { type: string, format: date, example: "2026-05-20" }
        m2_date:             { type: string, format: date, example: "2026-06-01" }
        cancel_date:         { type: string, format: date, nullable: true, example: null }
        modified_date_time:
          type: string
          description: >
            Source timestamp. Send `YYYY-MM-DD HH:MM:SS`. A value with an
            offset (`2026-04-10T12:34:56-04:00`) is converted to the server's
            time zone, and a value ending in `Z` fails the whole request with
            `500`.
          example: "2026-04-10 12:34:56"
        create_date_time:
          type: string
          description: "Source timestamp. Send `YYYY-MM-DD HH:MM:SS`."
          example: "2026-04-09 08:00:00"

    ByteRawDataRecord:
      type: object
      title: byte
      description: >
        Byte (BytePro) record (`integration_type: "byte"`). Natural key:
        `byte_loan_id`, unique per company. Uses the same field names as Arive
        where the concept exists. Send `total_loan_amount` on a new record:
        without it the whole request fails with `500`.
      required:
        - byte_loan_id
      properties:
        byte_loan_id:
          type: string
          maxLength: 255
          description: "Required. Byte's file id (`FileDataID`)."
          example: "1027892"
        lender_loan_identifier: { type: string, description: "The loan number staff use.", example: "23848" }
        lender_name:         { type: string, example: "Example Lending" }
        mortgage_type:       { type: string, description: "VA, FHA, Conventional, USDA-RD or Other.", example: "VA" }
        borrower_name:       { type: string, description: "All borrower names, including a co-borrower.", example: "Drew Patel" }
        borrower_email:      { type: string, format: email, example: "drew.patel@example.com" }
        borrower_phone:      { type: string, example: "5550107733" }
        borrower_address:    { type: string, description: "Subject property address, not the mailing address.", example: "410 Cedar St" }
        borrower_city:       { type: string, example: "Salem" }
        borrower_state:      { type: string, example: "OR" }
        borrower_zip:        { type: string, example: "97301" }
        total_loan_amount:
          type: string
          description: "Base loan amount in dollars, as text. Needed on a new record."
          example: "295000.00"
        broker_compensation: { type: string, description: "Broker compensation in dollars, as text.", example: "7618.38" }
        product_name:
          type: string
          nullable: true
          description: >
            The Sequifi product name, for example `Lender` or `Borrower`.
            `POST /v1/sales` matches product names exactly apart from capitals,
            so this must equal your product's name character for character.
          example: "Lender"
        compensation_type:
          type: string
          nullable: true
          description: >
            The same value as `product_name`, kept for audit. Leaving it out
            keeps the stored value; `null` clears it.
          example: "Lender"
        credit_report_fee:   { type: string, description: "Credit report fee charged to the borrower, as text.", example: "137.50" }
        loan_status:         { type: string, example: "Funded" }
        loan_originator_email: { type: string, format: email, description: "Loan officer.", example: "morgan.hayes@example.com" }
        loan_processor_email: { type: string, format: email, description: "Loan processor.", example: "sam.ortiz@example.com" }
        loan_officer_assistant_email: { type: string, format: email, description: "Loan officer assistant.", example: "dana.kim@example.com" }
        sale_date:
          type: string
          format: date
          description: >
            `YYYY-MM-DD`, checked as a real date (usually the funding date).
            Cannot be cleared once set: `null` or `""` keeps it.
          example: "2026-06-12"
        m1_date:             { type: string, format: date, description: "Usually the funding date. `null` clears it.", example: "2026-06-12" }
        m2_date:             { type: string, format: date, description: "Second milestone date. `null` clears it.", example: "2026-06-24" }
        cancel_date:
          type: string
          format: date
          nullable: true
          description: Cancellation date, used to carry a clawback for a loan reversed after funding.
          example: null
        modified_date_time:
          type: string
          description: >
            Source timestamp. Send `YYYY-MM-DD HH:MM:SS`. A value with an
            offset is converted to the server's time zone, and a value ending
            in `Z` fails the whole request with `500`.
          example: "2026-06-24 15:10:43"
        create_date_time:
          type: string
          description: "Source timestamp. Send `YYYY-MM-DD HH:MM:SS`."
          example: "2026-05-02 12:13:05"

    JobNimbusRawDataRecord:
      type: object
      title: jobnimbus
      description: >
        JobNimbus record (`integration_type: "jobnimbus"`). Natural key:
        `jnid`, unique per company. Every date field is a Unix timestamp in
        seconds (10 digits, for example `1741017600`), not milliseconds and
        not `YYYY-MM-DD`; dates are not validated.
      required:
        - jnid
      properties:
        jnid:
          type: string
          maxLength: 255
          description: "Required. JobNimbus id."
          example: "abc123def456"
        customer_id:         { type: string, example: "cust-987" }
        customer_name:       { type: string, example: "Taylor Brooks" }
        customer_email:      { type: string, format: email, example: "taylor.brooks@example.com" }
        address_line1:       { type: string, example: "456 Maple Street" }
        address_line2:       { type: string, example: "Unit 3" }
        city:                { type: string, example: "Austin" }
        state_text:          { type: string, example: "TX" }
        zip:                 { type: string, example: "78701" }
        system_size_kw:      { type: string, description: "System size in kW, as text.", example: "8.5" }
        gross_ppw:           { type: number, format: float, description: "Gross price per watt, 2 decimals.", example: 3.92 }
        net_ppw:             { type: number, format: float, description: "Net price per watt, 2 decimals.", example: 3.40 }
        contract_price:      { type: number, format: float, description: "2 decimals.", example: 33320 }
        dealer_fee:          { type: number, format: float, description: "2 decimals.", example: 4500 }
        status:
          type: string
          description: "Your normalized job status (for example derived from JobNimbus `status_name`)."
          example: "signed"
        signed_contract_date:
          type: integer
          format: int64
          description: "Unix timestamp in seconds. `null` clears it."
          example: 1741017600
        cancel_date:
          type: integer
          format: int64
          description: "Unix timestamp in seconds."
          example: 1742918400
        m1_date:
          type: integer
          format: int64
          description: "Milestone 1 date, Unix timestamp in seconds."
          example: 1741104000
        m2_date:
          type: integer
          format: int64
          description: "Milestone 2 date, Unix timestamp in seconds."
          example: 1741190400
        m3_date:
          type: integer
          format: int64
          description: "Milestone 3 date, Unix timestamp in seconds."
          example: 1741276800
        m4_date:
          type: integer
          format: int64
          description: "Milestone 4 date, Unix timestamp in seconds."
          example: 1741363200
        sales_closer_email:  { type: string, format: email, example: "jordan.reyes@example.com" }
        sales_closer_name:   { type: string, example: "Jordan Reyes" }
        sales_setter_name:   { type: string, example: "Casey Lee" }

    PipeSolarRawDataRecord:
      type: object
      title: pipesolar
      description: >
        Pipe Solar record (`integration_type: "pipesolar"`). Natural key:
        `pid`, unique per company (a number or a string, stored as a string).
        `sale_date` cannot be cleared once set; the milestone dates clear
        normally on `null`.
      required:
        - pid
      properties:
        pid:
          type: string
          maxLength: 255
          description: "Required. The sale id."
          example: "PS-2026-0001"
        contract_sign_date:
          type: string
          format: date
          description: "Contract signature date, `YYYY-MM-DD`, checked as a real date."
          example: "2026-03-10"
        customer_name:           { type: string, example: "Jamie Carter" }
        customer_email:          { type: string, format: email, example: "jamie.carter@example.com" }
        customer_phone:          { type: string, maxLength: 20, example: "555-010-7733" }
        customer_address:        { type: string, example: "789 Sunset Drive" }
        customer_city:           { type: string, example: "Tucson" }
        customer_state:          { type: string, example: "AZ" }
        customer_zip:            { type: string, maxLength: 10, example: "85701" }
        location_code:           { type: string, maxLength: 10, example: "AZ" }
        install_partner:         { type: string, description: "Installation partner company.", example: "Brightline Solar" }
        epc:                     { type: string, description: "As text.", example: "3.85" }
        gross_account_value:     { type: string, description: "As text.", example: "30800" }
        kw:                      { type: string, description: "System size in kW, as text.", example: "8.0" }
        net_epc:                 { type: string, description: "As text, stored as sent.", example: "3.20" }
        dealer_fee:              { type: number, format: float, description: "2 decimals.", example: 4620 }
        dealer_fee_percentage:   { type: string, description: "As text.", example: "0.15" }
        adders_total:            { type: string, description: "As text.", example: "1100" }
        job_status:              { type: string, example: "Site Survey Complete" }
        sale_product_name:       { type: string, example: "Solar Rooftop" }
        sales_rep_email:         { type: string, format: email, example: "jordan.reyes@example.com" }
        sales_rep_name:          { type: string, example: "Jordan Reyes" }
        sales_setter_name:       { type: string, example: "Casey Lee" }
        setter_email:            { type: string, format: email, example: "casey.lee@example.com" }
        site_surveyor:           { type: string, example: "Drew Patel" }
        sub_contractor:          { type: string, example: "Example Electric" }
        sale_date:
          type: string
          format: date
          nullable: true
          description: >
            Sale or signature date, `YYYY-MM-DD`. Cannot be cleared once set:
            `null` or `""` keeps it. Usually sent as `customer_signoff` on
            `POST /v1/sales`.
          example: "2026-03-15"
        cancel_date:
          type: string
          format: date
          nullable: true
          description: "Cancellation date. `null` clears it."
          example: null
        m1_date:
          type: string
          format: date
          nullable: true
          description: "Milestone 1 date (for example site survey). `null` clears it."
          example: "2026-03-20"
        m2_date:
          type: string
          format: date
          nullable: true
          description: "Milestone 2 date (for example inspection). `null` clears it."
          example: "2026-04-05"
        m3_date:
          type: string
          format: date
          nullable: true
          description: "Milestone 3 date (for example install complete). `null` clears it."
          example: "2026-04-22"
        m4_date:
          type: string
          format: date
          nullable: true
          description: "Milestone 4 date (for example permission to operate). `null` clears it."
          example: null

    ProlineRawDataRecord:
      type: object
      title: proline
      description: >
        ProLine record (`integration_type: "proline"`). Natural key:
        `project_id`. Dates are not validated. `status_date_won` cannot be
        cleared once set.
      required:
        - project_id
      properties:
        project_id:
          type: string
          maxLength: 255
          description: "Required. ProLine project id."
          example: "PRJ-30217"
        project_number:           { type: string, example: "1042" }
        project_stage:            { type: string, example: "Sold" }
        project_status:           { type: string, example: "Won" }
        address1:                 { type: string, example: "77 Harbor View Dr" }
        address2:                 { type: string, example: "Unit 2" }
        city:                     { type: string, example: "Tampa" }
        state:                    { type: string, example: "FL" }
        zip:                      { type: string, example: "33602" }
        assigned_to_id:           { type: string, example: "U-118" }
        assigned_to_email:        { type: string, format: email, example: "jordan.reyes@example.com" }
        assigned_to_name:         { type: string, example: "Jordan Reyes" }
        contact_id:               { type: string, example: "C-5512" }
        contact_first_name:       { type: string, example: "Taylor" }
        contact_last_name:        { type: string, example: "Brooks" }
        contact_email:            { type: string, format: email, example: "taylor.brooks@example.com" }
        contact_phone:            { type: string, example: "555-010-2290" }
        lead_source:              { type: string, example: "Referral" }
        category:                 { type: string, example: "Roofing" }
        type:                     { type: string, example: "Replacement" }
        gross_revenue_planned:    { type: string, example: "18500" }
        gross_revenue_actual:     { type: string, example: "18750" }
        quoted_value:             { type: string, example: "18500" }
        status_date_won:          { type: string, description: "Cannot be cleared once set.", example: "2026-04-11" }
        status_date_funded:       { type: string, example: "2026-04-20" }
        status_date_complete:     { type: string, example: "2026-05-02" }
        status_date_lost:         { type: string, nullable: true, example: null }
        status_date_disqualified: { type: string, nullable: true, example: null }

    FlexibleRawDataRecord:
      type: object
      title: sonar, gaiia, subhub, hubspot, monday, gohighlevel, pocomos
      description: >
        Record for a flexible type. Every field you send is stored as sent,
        including misspelled ones. Include the type's natural key: `sonar` and
        `gaiia` `account_id`, `subhub` `pid`, `hubspot` `hs_object_id`,
        `monday` `item_id`, `gohighlevel` `opportunity_id`, `pocomos` `pcc_id`, `acculynx` `job_id`.
        Some types check date fields as `YYYY-MM-DD`. At most 400 KB per
        record.
      additionalProperties: true
      example:
        account_id: "ACC-100245"
        customer_name: "Riley Nguyen"
        plan: "fiber-1g"
        status: "active"

    OneTimePayment:
      type: object
      description: A paid one-time payment, with the totals shown on its pay stub. Field names match GET /v1/payroll-history where the two share a meaning.
      properties:
        one_time_payment_id:
          type: integer
          description: The payment's id. Its own number series, separate from `payroll_id`. Use it to save a journal entry id.
        is_onetime_payment:
          type: integer
          enum: [1]
          description: Always `1`, as on a payroll history record that came from a one-time payment.
        user_id:
          type: integer
          nullable: true
        first_name:
          type: string
          nullable: true
        last_name:
          type: string
          nullable: true
        employee_id:
          type: string
          nullable: true
        worker_type:
          type: string
          nullable: true
          description: "`1099` or `w2`, as the payment was made."
        pay_frequency:
          type: integer
          nullable: true
          description: "1 Weekly, 2 Monthly, 3 Biweekly, 4 Semimonthly, 5 Daily."
        pay_period_from:
          type: string
          format: date
          nullable: true
        pay_period_to:
          type: string
          format: date
          nullable: true
        pay_date:
          type: string
          format: date
          nullable: true
        request_number:
          type: string
          nullable: true
          description: The request number shown in the app, such as `R000014`.
        description:
          type: string
          nullable: true
        adjustment_type_id:
          type: integer
          nullable: true
        adjustment_type:
          type: string
          nullable: true
          description: Name of the request type, such as `Bonus` or `Reimbursement`.
        from_payroll:
          type: boolean
          description: "`true` when the payment paid lines from an open payroll; `false` for a standalone payment."
        commission:
          type: number
          description: Commissions, less commission clawbacks.
        override:
          type: number
          description: Overrides, less override clawbacks.
        reconciliation:
          type: number
        custom_payment:
          type: number
          description: Custom payroll field amounts.
        hourly_salary:
          type: number
        overtime:
          type: number
        adjustment:
          type: number
          description: Adjustments, less fines. Includes a standalone payment's own amount unless it is a reimbursement.
        reimbursement:
          type: number
        deduction:
          type: number
          description: Deductions and accruals, signed. Negative lowers pay.
        gross_pay:
          type: number
          description: Sum of the nine earnings, adjustment, reimbursement and deduction fields above.
        employee_tax:
          type: number
          description: Employee taxes withheld.
        state_income_tax:
          type: number
        federal_income_tax:
          type: number
        employer_tax:
          type: number
          description: Employer taxes.
        employee_benefit_deduction:
          type: number
        employer_benefit_deduction:
          type: number
        net_pay:
          type: number
          description: Take-home pay. See `net_pay_source`.
        net_pay_source:
          type: string
          enum: [provider, computed]
          description: "`provider` when the figure came from your payroll provider; `computed` when it is `amount` minus taxes."
        amount:
          type: number
          description: The payment amount as entered.
        settlement_status:
          type: string
          enum: [paid, pending]
          description: "`pending` while your payroll provider has not confirmed the payment."
        is_deposit_returned:
          type: boolean
          description: "`true` when the bank returned the deposit after payment."
        quickbooks_journal_entry_id:
          type: string
          nullable: true
          description: Journal entry id saved with PATCH /v1/one-time-payments, or null.
        created_at:
          type: string
          format: date-time
          nullable: true
        updated_at:
          type: string
          format: date-time
          nullable: true
    ApiResponse:
      type: object
      description: >
        The envelope on every response produced by the API itself. Errors from
        the gateway (such as a `401` for a bad token) use `GatewayError`
        instead.
      properties:
        status:
          type: integer
          description: The HTTP status code, repeated.
          example: 200
        message:
          type: string
          description: Short text. Wording varies by endpoint; branch on the HTTP status, not on this text.
          example: "success"
        data:
          type: object
          description: The endpoint's payload. `{}` on most errors.
