openapi: 3.1.0
info:
  title: OpSite API
  version: "1.0.0"
  summary: Construction project management for contractors. REST + JSON.
  description: |
    OpSite is a construction project management platform. This document describes the
    stable API surface available to AI agents and external integrations.

    ## Versioning

    All endpoints documented here are reachable under both `/api/` (legacy, used by
    OpSite's own browser and iOS clients) and `/api/v1/` (stable contract surface
    for external clients). External clients SHOULD use `/api/v1/` so we can ship
    breaking changes under `/api/v2/` later without disturbing your integration.

    ## Authentication

    Today the API authenticates session cookies (NextAuth). API-key auth with
    scopes ships in Phase 2 of the agent-readiness roadmap; once available, send
    `Authorization: Bearer opsk_…`.

    ## Idempotency

    Mutating requests (POST/PUT/PATCH/DELETE) accept an optional `Idempotency-Key`
    header. The same key + same body returns the cached response for 24 hours.
    Different body with same key returns 422. See `Idempotency-Key` parameter below.

    ## Rate limiting

    All responses include `X-RateLimit-Limit`, `X-RateLimit-Remaining`,
    `X-RateLimit-Reset`. 429 responses include `Retry-After` (seconds).

    ## Correlation

    Every response includes `X-Request-Id`. Include this in error reports for fast
    log lookup.

  contact:
    name: OpSite
    url: https://app.useopsite.com
    email: support@useopsite.com
  license:
    name: Proprietary

servers:
  - url: https://app.useopsite.com/api/v1
    description: Production (versioned, recommended for external clients)
  - url: https://app.useopsite.com/api
    description: Production (legacy unversioned, used by OpSite's own clients)

tags:
  - name: Resources
    description: Generic CRUD over OpSite's domain tables (Jobs, Invoices, Leads, etc.).
  - name: Clients
    description: Customer / homeowner records.
  - name: Employees
    description: Contractor team members.
  - name: Payments
    description: Payment records associated with invoices.
  - name: Proposals
    description: Token-based public proposal viewing and acceptance.
  - name: Bids
    description: Bid request and submission flow.

security:
  - sessionCookie: []
  - apiKey: []

paths:
  /airtable:
    get:
      tags: [Resources]
      summary: List or read records from a domain table
      description: |
        Generic resource endpoint. Use `?table=Jobs` to list jobs, add `&recordId=`
        to read a single record. The result is automatically scoped to the caller's
        contractor(s) so you only see your own data.

        Supported tables: see the `TableName` enum.
      operationId: listOrGetRecord
      parameters:
        - $ref: "#/components/parameters/TableName"
        - name: recordId
          in: query
          required: false
          description: When present, returns a single record instead of a list.
          schema:
            type: string
        - name: filter
          in: query
          required: false
          description: Server-side filter (Airtable formula syntax — see lib/airtable for the dialect).
          schema:
            type: string
        - $ref: "#/components/parameters/RequestId"
      responses:
        "200":
          description: Records
          headers:
            X-RateLimit-Remaining:
              $ref: "#/components/headers/RateLimitRemaining"
            X-Request-Id:
              $ref: "#/components/headers/RequestId"
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    properties:
                      records:
                        type: array
                        items:
                          $ref: "#/components/schemas/AirtableRecord"
                  - $ref: "#/components/schemas/AirtableRecord"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/RateLimited"
    post:
      tags: [Resources]
      summary: Create a record
      operationId: createRecord
      parameters:
        - $ref: "#/components/parameters/TableName"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [fields]
              properties:
                fields:
                  type: object
                  description: Field-name → value map. Field names are table-specific.
                  additionalProperties: true
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AirtableRecord"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "422":
          $ref: "#/components/responses/IdempotencyConflict"
        "429":
          $ref: "#/components/responses/RateLimited"
    patch:
      tags: [Resources]
      summary: Update a record
      operationId: updateRecord
      parameters:
        - $ref: "#/components/parameters/TableName"
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [recordId, fields]
              properties:
                recordId:
                  type: string
                fields:
                  type: object
                  additionalProperties: true
      responses:
        "200":
          description: Updated record
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AirtableRecord"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/RateLimited"
    delete:
      tags: [Resources]
      summary: Delete a record
      operationId: deleteRecord
      parameters:
        - $ref: "#/components/parameters/TableName"
        - name: recordId
          in: query
          required: true
          schema:
            type: string
        - $ref: "#/components/parameters/IdempotencyKey"
      responses:
        "200":
          description: Deleted
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"

  /clients:
    get:
      tags: [Clients]
      summary: List clients
      operationId: listClients
      responses:
        "200":
          description: Clients
          content:
            application/json:
              schema:
                type: object
                properties:
                  clients:
                    type: array
                    items:
                      $ref: "#/components/schemas/Client"
        "401":
          $ref: "#/components/responses/Unauthorized"
    post:
      tags: [Clients]
      summary: Create a client
      operationId: createClient
      parameters:
        - $ref: "#/components/parameters/IdempotencyKey"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [company_name]
              properties:
                company_name: { type: string }
                primary_contact_name: { type: string }
                primary_contact_email: { type: string, format: email }
                primary_contact_phone: { type: string }
                billing_address: { type: string }
                notes: { type: string }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Client"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /employees:
    get:
      tags: [Employees]
      summary: List employees
      operationId: listEmployees
      responses:
        "200":
          description: Employees
          content:
            application/json:
              schema:
                type: object
                properties:
                  employees:
                    type: array
                    items:
                      $ref: "#/components/schemas/Employee"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /payments:
    get:
      tags: [Payments]
      summary: List payments
      operationId: listPayments
      responses:
        "200":
          description: Payments
          content:
            application/json:
              schema:
                type: object
                properties:
                  payments:
                    type: array
                    items:
                      $ref: "#/components/schemas/Payment"
        "401":
          $ref: "#/components/responses/Unauthorized"

  /proposal/{token}:
    get:
      tags: [Proposals]
      summary: Read a proposal by public token
      description: |
        Token-based public access. The `token` is generated when a contractor
        sends a proposal; the recipient does not need to be authenticated.
      operationId: getProposalByToken
      security: []
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Proposal
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Proposal"
        "404":
          $ref: "#/components/responses/NotFound"

  /bids:
    get:
      tags: [Bids]
      summary: List bid requests
      operationId: listBids
      responses:
        "200":
          description: Bid requests
        "401":
          $ref: "#/components/responses/Unauthorized"

components:
  parameters:
    TableName:
      name: table
      in: query
      required: true
      description: Domain table to operate on.
      schema:
        $ref: "#/components/schemas/TableName"
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: |
        Opt-in idempotency header. If present, the same key + same body returns
        the cached 2xx/4xx response for 24 hours. Different body with same key
        returns 422. Use a unique value (UUID) per logical operation. Replays
        carry an `X-Idempotent-Replay: true` header.
      schema:
        type: string
        maxLength: 255
        pattern: "^[A-Za-z0-9._~-]+$"
    RequestId:
      name: X-Request-Id
      in: header
      required: false
      description: Optional upstream-provided correlation id. If absent, the server generates one.
      schema:
        type: string

  headers:
    RequestId:
      description: End-to-end correlation id for this response.
      schema:
        type: string
    RateLimitLimit:
      description: Maximum requests in the current window.
      schema:
        type: integer
    RateLimitRemaining:
      description: Requests remaining in the current window.
      schema:
        type: integer
    RateLimitReset:
      description: Unix-ms timestamp when the current window resets.
      schema:
        type: integer
    RetryAfter:
      description: Seconds until the rate-limit window resets.
      schema:
        type: integer

  responses:
    Unauthorized:
      description: Missing or invalid credentials.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    NotFound:
      description: Resource not found or not visible to this caller.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    RateLimited:
      description: Too many requests.
      headers:
        Retry-After:
          $ref: "#/components/headers/RetryAfter"
        X-RateLimit-Remaining:
          $ref: "#/components/headers/RateLimitRemaining"
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
    IdempotencyConflict:
      description: |
        Same Idempotency-Key was used previously with a different request body.
        Use a new key for new requests.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"

  schemas:
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: Short error label.
        message:
          type: string
          description: Human-readable explanation.
        code:
          type: string
          description: Stable machine-readable code, e.g. `IDEMPOTENCY_KEY_CONFLICT`.

    AirtableRecord:
      type: object
      description: Generic record. The shape of `fields` is table-specific.
      required: [id, fields]
      properties:
        id:
          type: string
          description: UUID for the record.
        fields:
          type: object
          additionalProperties: true
        createdTime:
          type: string
          format: date-time

    TableName:
      type: string
      description: |
        Domain table. The full list lives in `src/lib/types.ts`. Most agent traffic
        will touch Jobs, Invoices, Leads, Opportunities, Proposals, Subs, Draws,
        Actions, Sub Payments, Purchase Orders, Change Orders, Expenses,
        Permits, Daily Logs, Comments.
      enum:
        - Contractors
        - Jobs
        - Invoices
        - Leads
        - Opportunities
        - Proposals
        - Subs
        - Draws
        - Actions
        - Messages
        - Sub Payments
        - Purchase Orders
        - Change Orders
        - Client Portal Settings
        - Sub Portal Settings
        - Job Documents
        - Expenses
        - Job Inspections
        - Lien Waivers
        - Lead Questionnaires
        - Proposal Templates
        - Users
        - Job Materials
        - Suppliers
        - Job Subtasks
        - PO Amendments
        - Audit Logs
        - Permits
        - Submittals
        - Corrections
        - Comments
        - Daily Logs
        - Weekly Updates
        - Checklists
        - Product Catalog
        - Company Compliance Documents
        - Contract Templates
        - Contracts
        - Contractor Cost Codes
        - Branches
        - Website Intakes
        - Employees
        - Time Entries
        - Bid Requests
        - Bids

    Client:
      type: object
      properties:
        id: { type: string }
        contractor_id: { type: string }
        company_name: { type: string }
        primary_contact_name: { type: string }
        primary_contact_email: { type: string, format: email }
        primary_contact_phone: { type: string }
        billing_address: { type: string }
        notes: { type: string }
        archived: { type: boolean }

    Employee:
      type: object
      properties:
        id: { type: string }
        contractor_id: { type: string }
        name: { type: string }
        email: { type: string, format: email }
        role: { type: string }
        active: { type: boolean }

    Payment:
      type: object
      properties:
        id: { type: string }
        invoice_id: { type: string }
        amount: { type: number }
        method: { type: string, description: "Cash, Check, ACH, Card, etc." }
        paid_at: { type: string, format: date-time }
        notes: { type: string }

    Proposal:
      type: object
      properties:
        id: { type: string }
        token: { type: string }
        contractor_id: { type: string }
        client_id: { type: string }
        status: { type: string, enum: [draft, sent, viewed, accepted, declined, expired] }
        total: { type: number }
        sections:
          type: array
          items:
            type: object

  securitySchemes:
    sessionCookie:
      type: apiKey
      in: cookie
      name: __Secure-next-auth.session-token
      description: NextAuth session cookie. Used by OpSite's own browser and iOS clients.
    apiKey:
      type: http
      scheme: bearer
      bearerFormat: opsk_…
      description: |
        API-key auth (Phase 2 of the agent-readiness roadmap — not yet live).
        When available, send `Authorization: Bearer opsk_…`. Each key has a
        scope list (e.g. `jobs:read`, `invoices:write`) and a per-key rate limit.
