openapi: "3.0.3"
info:
  title: Navexa Tax API
  version: "1.0.0"
  description: |
    ConnectRPC-based API for tobacco and nicotine excise tax compliance.

    ## Protocol

    All endpoints use **HTTP POST** with JSON request/response bodies (ConnectRPC protocol).
    The URL pattern is `https://api-tax.navexa.co/{package}.{Service}/{Method}`.

    ```
    POST /tax.v1.ProductCatalogService/CreateProduct HTTP/1.1
    Host: api-tax.navexa.co
    Content-Type: application/json
    Authorization: Bearer txk_abc123...

    {"name": "Marlboro Red 20pk", "sku": "MARL-RED-20"}
    ```

    ## Authentication

    Every endpoint except the public Tax Rates reads requires an `Authorization: Bearer <token>` header:

    1. **Firebase ID Token** — for browser-based dashboard sessions
    2. **API Key** — for programmatic access (prefixed `txk_`)
       - Create keys in the dashboard under **Developers → API Keys** (`/settings/api-keys`). Organization admins only.
       - Each key must be granted at least one scope. A key with no scopes is denied everywhere.
       - A key can call only the endpoints its scopes cover (see below). API Keys and Team endpoints are dashboard-only.
       - Rate limits, per key over a sliding 60-second window: **Live keys** 60 requests, **Test keys** 100 requests.
         Over the limit returns `resource_exhausted` (HTTP 429) with no `Retry-After` header; back off before retrying.

    ## Environments

    Every API key is either **Live** or **Test**.

    - **Live** keys record real transactions. Only live transactions count toward filing periods and PACT reports.
    - **Test** keys are a sandbox. Their transactions are tagged `test` and never count toward filing periods or PACT reports.
      Test keys can call only tax calculation, transaction endpoints, product reads, sales tax reads,
      `GenerateTaxSummary` and `ExportTransactions`; every other endpoint returns `permission_denied`.

    ## Available Scopes

    | Scope | Endpoints |
    |-------|-----------|
    | `calc:read` | CalculateTax, CalculateOrderTax, QuoteCheckoutTax, QuoteBuyerLevies |
    | `products:read` | GetProduct, ListProducts, GetProductTaxProfile, ExportProducts |
    | `products:write` | CreateProduct, UpdateProduct, DeleteProduct, SetProductTaxProfile, BulkCreateProducts, BulkUpdateProducts |
    | `transactions:read` | GetTransaction, ListTransactions, RecomputeTransaction, ReportBuyerLevies |
    | `transactions:write` | CommitTransaction, ImportTransactions, VoidTransaction, ReverseTransaction, UpdateTransactionShipment |
    | `customers:read` | GetCustomer, ListCustomers |
    | `customers:write` | CreateCustomer, UpdateCustomer |
    | `exemptions:read` | GetExemptionCertificate, ListExemptionCertificates |
    | `exemptions:write` | CreateExemptionCertificate, UpdateExemptionCertificate, RevokeExemptionCertificate |
    | `filing:read` | ListFilingSchedules, ListFilingPeriods, GetFilingPeriod, GenerateTaxSummary, ExportTransactions, GetFilingReturn, GetFilingRun, ListFilingRuns, DownloadFilingRunArtifact, GetFilingRequirement (a state's excise return calendar: frequency, due day and form, as CreateFilingSchedule applies it) |
    | `filing:write` | CreateFilingSchedule, DeleteFilingSchedule, RecomputeFilingPeriod, AmendFilingPeriod, PrepareFilingRun, RecordFilingSubmission, FailFilingRun |
    | `filing:recompute` | RecomputeFilingPeriod only |
    | `filing:approve` | ApproveFilingRun only. An explicit grant: no other scope carries it. An approved run can be submitted to a state by the remote filer without a person, so each approval by a key emails the organization's admins |
    | `reconciliation:read` | ListPotentialDuplicates |
    | `reconciliation:write` | RecordReconciliationDecision |
    | `sales_tax:read` | GetProductSalesTaxProfile, GetJurisdictionSalesTaxConfig, ListTaxHolidays. Test API keys only outside development/test (other callers, including dashboard sessions, get FailedPrecondition) until TAX-1340 |
    | `sales_tax:write` | SetProductSalesTaxProfile. Test API keys only outside development/test (other callers, including dashboard sessions, get FailedPrecondition) until TAX-1340 |
    | `nexus:read` | GetNexusRegistration, ListNexusRegistrations, ListCoverageStatus (what the platform covers per registered state), ListEconomicNexusStatus (sales-tax economic nexus per state; `FAILED_PRECONDITION` unless tracking is enabled for the organization), ListJurisdictionLevies (the excise levies in force in a jurisdiction today and the seller roles each falls on) |
    | `nexus:write` | CreateNexusRegistration (`tax_type` `excise` with a `nexus_role`, or `sales` with a `sales_basis`), UpdateNexusRegistration, DeleteNexusRegistration |
    | `licenses:read` | GetLicense, ListLicenses, ListComplianceAlerts, ListSuretyBonds |
    | `licenses:write` | CreateLicense, UpdateLicense, DeleteLicense (closes the license; the record is kept), CreateSuretyBond, UpdateSuretyBond, DeleteSuretyBond (releases the bond; the record is kept) |
    | `compliance:read` | ListRequirements, ListTrackerRows, ListComplianceEvents, CheckEligibility, GetEntityProfile, ListOfficers, ListEntityRegistrations, ListDocuments, DownloadDocument |
    | `compliance:write` | UpsertTrackerItem, BulkUpsertTrackerItems, AddComplianceEvent, UpdateComplianceEvent, CompleteComplianceEvent, SetEntityProfile, UpsertOfficer, DeleteOfficer, UpsertEntityRegistration, DeleteEntityRegistration, UploadDocument, DeleteDocument |
    | `pact:read` | GetRegistration, ListReports, DownloadReport, ExportAgeVerificationEvidence, GetPACTCoverage |
    | `pact:write` | UpdateRegistration, GenerateReport (MarkReportFiled and RecordStateTemplateFiling are a signed-in org admin's call only, TAX-1431) |
    | `pact:generate` | GenerateReport only |
    | `webhooks:read` | ListSubscriptions, ListDeliveries, GetDelivery |
    | `webhooks:write` | CreateSubscription, DeleteSubscription, RedeliverDelivery |
    | `integrations:manage` | All IntegrationService endpoints except ListAvailableProviders (dashboard-only) |
    | `audit:read` | ListAuditLog |
    | `agecheck:verify` | AgeCheck engine (separate host): CreateVerification, GetVerification, ListVerifications, GetVerificationTimeline, AttachOrder, CreateHostedSession, SendVerificationLink, RevokeVerificationLinks, GetIntegrationInfo (OverrideVerification takes no API key: signed-in members only) |
    | `agecheck:clearance` | AgeCheck engine (separate host): GetClearance, PeekClearance, ReportShipment |

    ## Idempotency

    `CommitTransaction` accepts an optional `Idempotency-Key` header. Retrying a commit with the same key
    returns the original transaction instead of recording a duplicate. If the commit fails, the key is
    released so the same key can be retried. Keys are per environment: a live commit and a test commit
    may use the same key, and each retry replays only its own environment's transaction.

    ## Webhooks

    Subscribe an HTTPS endpoint under **Developers → Webhooks** (`/settings/webhooks`) or with
    `WebhookService/CreateSubscription`. The signing secret is returned once, at creation.

    Each delivery is an HTTP `POST` with `Content-Type: application/json`. The body is the event payload.
    The `X-Webhook-Event-Id` header identifies the event for this endpoint: it is the same on every retry
    and redelivery, so dedupe on it.
    The `X-Webhook-Timestamp` header is the attempt's send time in unix seconds (set again on every retry
    and redelivery), and `X-Webhook-Signature-V2` is the lowercase hex HMAC-SHA256 of the timestamp, a
    `.` and the raw request body (`timestamp + "." + body`), keyed with the subscription secret. Verify it
    against the raw bytes before parsing, compare in constant time, and reject a request whose timestamp
    is more than 5 minutes from your clock, so a captured request cannot be replayed later:

    ```js
    import crypto from 'node:crypto';

    function verify(rawBody, timestampHeader, signatureHeader, secret) {
      const ts = Number(timestampHeader);
      if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
      const expected = crypto.createHmac('sha256', secret).update(`${timestampHeader}.`).update(rawBody).digest('hex');
      const a = Buffer.from(expected, 'utf8');
      const b = Buffer.from(signatureHeader ?? '', 'utf8');
      return a.length === b.length && crypto.timingSafeEqual(a, b);
    }
    ```

    The older `X-Webhook-Signature` header (the hex HMAC-SHA256 of the raw body alone) is still sent, but
    it signs no time, so it cannot tell a replay from the original: verify `X-Webhook-Signature-V2`.

    Any 2xx response marks the delivery successful. Otherwise it is retried 1 minute, 5 minutes,
    30 minutes, 2 hours and 12 hours after each failed attempt, then abandoned (6 attempts in total).
    Delivery history is available from `WebhookService/ListDeliveries` (newest first; `page_size`
    defaults to 50, max 100). A delivery still being retried carries `next_retry_at`.
    `last_attempted_at`, `response_status`, `error_message` and `response_body_excerpt` (the first 2 KB
    of the response body) describe the latest attempt. `WebhookService/GetDelivery` returns one delivery
    with its event id, the exact JSON body and the request headers it is sent with (the timestamp and
    signature values are placeholders: they are set at send time and never returned).
    `WebhookService/RedeliverDelivery` queues a delivery to be sent again on the next delivery run (within
    5 minutes) with the same event id and body, signed with the endpoint's current secret; the endpoint
    must be enabled.

    Deadline and compliance payloads carry an `event` field. Transaction, PACT report and
    `tax_rule.published` payloads do not, so use a separate endpoint per event type if you need to tell
    them apart.

    AgeCheck `verification.*` payloads carry no `event` field either: their `state` names the event
    (`verification.<state>`). The body has `event_id` (unique per transition and the same on every retry,
    so dedupe on it), `organization_id`, `verification_id`, `state`, `pass_class` (passed only),
    `policy_version`, `order_external_id` (when an order is bound), `livemode` (false for a test-mode
    verification: never ship on a test event) and `occurred_at` (UTC). The exception is
    `verification.hold_stale`, which names itself in `event`: its body has `event`, `organization_id`,
    `verification_id`, `order_external_id`, `state` (the verification's current state), `livemode`,
    `pending_hours` (whole hours since the verification was created) and `occurred_at` (UTC). It is sent
    once per verification, so dedupe it on `verification_id`.

    | Event | Fires when |
    |-------|------------|
    | `transaction.committed` | A transaction is committed (API, CSV import or integration sync) |
    | `transaction.voided` | A committed transaction is voided |
    | `filing.deadline` | A filing period is due in 10, 3 or 1 days or due today (once per mark; a missed day is caught up, `days_until` the days actually left), or overdue (every day until it is filed). None while its filing run is submitted, awaiting the portal confirmation. Names it by `filing_period_id`; a period of a state that files one return per levy (California) also carries `levy` (the levy key, e.g. `ca_cecet`) and `levy_label` (e.g. `CECET`), both empty otherwise |
    | `pact.deadline` | A monthly PACT report is due soon or overdue (same schedule as filing). Names the report month by `report_period_start` and `report_period_end` |
    | `pact_report.generated` | A PACT report is generated |
    | `license.expiring` | A license is 60, 30 or 7 days from expiry, or expires (once per mark, named by `threshold_days`; a missed day is caught up, and a lapse up to 30 days old still alerts). Closed and revoked licenses never alert |
    | `customer_license.expiring` | A customer's (buyer's) license is 30 days from expiry, or expires (once per mark, named by `threshold_days`; a missed day is caught up, and a lapse up to 30 days old still alerts) |
    | `compliance_requirement.added` | A new state requirement becomes active in a state where you operate |
    | `surety_bond.expiring` | An active surety bond is about to lapse (same schedule as licenses) |
    | `compliance_event.due` | An open compliance event (a deficiency cure deadline, an agency notice awaiting a response, a checklist item) is due in 7 or 1 days, due today, or overdue up to 30 days (once per mark, named by `threshold_days`) |
    | `compliance_requirement.expiring` | A state requirement you hold is about to lapse (same schedule as licenses) |
    | `entity_registration.expiring` | An entity state registration (foreign qualification, registered agent, PACT agent for service, tax account) is about to lapse (same schedule as licenses) |
    | `entity_registration.annual_report_due` | An entity state registration's annual report is due (same schedule as licenses) |
    | `compliance_document.expiring` | An uploaded compliance document (certificate, supplier license, ...) is about to lapse (same schedule as licenses) |
    | `exemption_certificate.expiring` | An active exemption certificate's expiration date nears (same schedule as licenses); `document_on_file` says whether its signed copy is uploaded |
    | `compliance_directory.change` | The monthly state directory check (NE ENDS directory) proposes tracker changes for your SKUs: `approved` for a listed SKU not yet approved, `removed` for one the state delisted. Nothing is applied; once per distinct proposal set. Body: `state_code`, `requirement_id`, `requirement_code`, `source_url`, `snapshot_sha256`, `delisted_count`, `proposals` (`product_id`, `sku`, `name`, `current_status`, `proposed_status`, `matched_by`: `gtin` or `manufacturer_sku`) |
    | `tax_rule.published` | A new tax rate rule is published |
    | `tax_rule.upcoming` | A rate change takes effect in 30, 7 or 1 days in a state where you hold a license (once per mark, named by `threshold_days`; a missed day is caught up through the effective day, `days_until` the days actually left) |
    | `verification.passed` | An age verification passes |
    | `verification.needs_doc` | An age verification needs an ID document from the buyer |
    | `verification.held` | An age verification is held (the database check timed out or errored) |
    | `verification.failed` | An age verification fails |
    | `verification.hold_stale` | An order-bound age verification is still undecided (GetClearance answers `HOLD`) past the organization's hold alert hours (AgeCheck settings, default 72). Once per verification |

    ## Error Handling

    Errors follow ConnectRPC conventions. The response body contains:
    ```json
    {"code": "not_found", "message": "product not found"}
    ```

    | ConnectRPC Code | HTTP Status | Meaning |
    |-----------------|-------------|---------|
    | `invalid_argument` | 400 | Bad request / validation failure |
    | `unauthenticated` | 401 | Missing or invalid token |
    | `permission_denied` | 403 | Insufficient scope or role |
    | `not_found` | 404 | Resource doesn't exist |
    | `already_exists` | 409 | Duplicate resource |
    | `failed_precondition` | 412 | Business rule violation |
    | `resource_exhausted` | 429 | Per-key rate limit or a list over 500 items |
    | `internal` | 500 | Server error |

    ## Pagination

    List endpoints accept `page_size` (default 50, max 100) and `offset` (0-based).
    Responses include `total_count` for computing page counts.

servers:
  - url: https://api-tax.navexa.co
    description: Production
  - url: http://localhost:8080
    description: Local development

security:
  - bearerAuth: []

tags:
  - name: Tax Calculation
    description: Calculate excise tax for products and orders
  - name: Products
    description: Manage product catalog and tax profiles
  - name: Transactions
    description: Commit and manage tax transactions
  - name: Reconciliation
    description: Review possible duplicate transactions across channels and choose which copy counts
  - name: Filing
    description: Filing schedules, periods, and tax summaries
  - name: Exemptions
    description: Manage exemption certificates
  - name: API Keys
    description: Create and manage API keys (dashboard sessions only, organization admins)
  - name: Team
    description: Team members and invitations (dashboard sessions only)
  - name: Integrations
    description: Connect QuickBooks Online, Xero, Shopify, WooCommerce, Odoo and other systems, and map their products
  - name: Compliance
    description: State compliance requirements and sale eligibility
  - name: Tax Rates
    description: Browse jurisdictions, rules, and categories (public)

paths:
  # ── Tax Calculation ───────────────────────────────────────────
  /tax.v2.TaxCalculationService/CalculateTax:
    post:
      tags: [Tax Calculation]
      summary: Calculate tax for a single product
      description: "Scope: `calc:read`. Live and test keys."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CalculateTaxRequest'
      responses:
        '200':
          description: Tax calculation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalculateTaxResponse'

  /tax.v2.TaxCalculationService/CalculateOrderTax:
    post:
      tags: [Tax Calculation]
      summary: Calculate tax for a multi-line order
      description: "Scope: `calc:read`. Live and test keys."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CalculateOrderTaxRequest'
      responses:
        '200':
          description: Order tax calculation result
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CalculateOrderTaxResponse'

  /tax.v2.CheckoutTaxService/QuoteCheckoutTax:
    post:
      tags: [Tax Calculation]
      summary: Quote the tax a store charges on a cart
      description: "Scope: `calc:read`. Org-scoped and stateless: sales tax where the org files a location-sourced sales return (e.g. AZ TPT-2). Excise is not charged here: the excise the org owes is the seller's, except a levy the law puts on the buyer (see QuoteBuyerLevies). Shipping is not taxed."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QuoteCheckoutTaxRequest'
      responses:
        '200':
          description: Per-line taxes and the total
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QuoteCheckoutTaxResponse'

  /tax.v2.CheckoutTaxService/QuoteBuyerLevies:
    post:
      tags: [Tax Calculation]
      summary: Quote the levies the law puts on the buyer of a cart
      description: "Scope: `calc:read`. Org-scoped and stateless. Returns only levies the law puts on the buyer and the retailer collects at the sale (California's Electronic Cigarette Excise Tax, 12.5% of the retail price, first); excise the seller owes is never returned. Gated by the org's excise registrations as a commit is. Add each levy to the cart as its own fee line and record the amount under the order's metadata so ReportBuyerLevies can compare it with what is owed. WooCommerce stores can use the Navexa Excise plugin instead: https://tax.navexa.co/downloads/navexa-excise-for-woocommerce.zip."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QuoteCheckoutTaxRequest'
      responses:
        '200':
          description: Per-line buyer-borne levies and their total
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QuoteBuyerLeviesResponse'

  /tax.v2.CheckoutTaxService/ReportBuyerLevies:
    post:
      tags: [Tax Calculation]
      summary: Buyer-borne levies collected against owed, per state and month
      description: "Scope: `transactions:read`; live keys only. Compares, per state, levy and tax-point month, what checkout collected (the transaction metadata key buyer_levy_collected_<code>, e.g. buyer_levy_collected_ca_cecet) with what the engine booked for the same transactions. A positive gap is under-collection, such as a checkout that failed open; gapOrders lists the orders that differ by more than $0.02."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [fromDate, toDate]
              properties:
                fromDate: { type: string, description: "First tax-point day, YYYY-MM-DD" }
                toDate: { type: string, description: "Last tax-point day, YYYY-MM-DD, at most 366 days after fromDate" }
      responses:
        '200':
          description: Report rows and the orders with a gap
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReportBuyerLeviesResponse'

  # ── Products ──────────────────────────────────────────────────
  /tax.v1.ProductCatalogService/CreateProduct:
    post:
      tags: [Products]
      summary: Create a product
      description: "Scope: `products:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateProductRequest'
      responses:
        '200':
          description: Created product
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateProductResponse'

  /tax.v1.ProductCatalogService/GetProduct:
    post:
      tags: [Products]
      summary: Get a product with its tax profile
      description: "Scope: `products:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GetProductRequest'
      responses:
        '200':
          description: Product with tax profile
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetProductResponse'

  /tax.v1.ProductCatalogService/ListProducts:
    post:
      tags: [Products]
      summary: List products with optional filters
      description: "Scope: `products:read`. Supports search, category, and nicotine source filters."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListProductsRequest'
      responses:
        '200':
          description: Paginated product list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListProductsResponse'

  /tax.v1.ProductCatalogService/UpdateProduct:
    post:
      tags: [Products]
      summary: Update a product
      description: "Scope: `products:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateProductRequest'
      responses:
        '200':
          description: Updated product
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateProductResponse'

  /tax.v1.ProductCatalogService/DeleteProduct:
    post:
      tags: [Products]
      summary: Soft-delete a product
      description: "Scope: `products:write`. Sets active=false."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeleteProductRequest'
      responses:
        '200':
          description: Product deleted
          content:
            application/json:
              type: object

  /tax.v1.ProductCatalogService/SetProductTaxProfile:
    post:
      tags: [Products]
      summary: Create or update a product's tax profile
      description: "Scope: `products:write`. Upserts the tax profile for a product."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SetProductTaxProfileRequest'
      responses:
        '200':
          description: Updated tax profile
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SetProductTaxProfileResponse'

  /tax.v1.ProductCatalogService/GetProductTaxProfile:
    post:
      tags: [Products]
      summary: Get a product's tax profile
      description: "Scope: `products:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GetProductTaxProfileRequest'
      responses:
        '200':
          description: Tax profile
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetProductTaxProfileResponse'

  /tax.v1.ProductCatalogService/BulkCreateProducts:
    post:
      tags: [Products]
      summary: Bulk create up to 500 products
      description: "Scope: `products:write`. Each row is committed independently — one failure doesn't abort siblings."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BulkCreateProductsRequest'
      responses:
        '200':
          description: Per-row results
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BulkCreateProductsResponse'

  /tax.v1.ProductCatalogService/BulkUpdateProducts:
    post:
      tags: [Products]
      summary: Bulk update up to 500 products
      description: "Scope: `products:write`. Only provided fields are updated (COALESCE). Each row independent."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BulkUpdateProductsRequest'
      responses:
        '200':
          description: Per-row results
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BulkUpdateProductsResponse'

  /tax.v1.ProductCatalogService/ExportProducts:
    post:
      tags: [Products]
      summary: Export products as CSV or JSON
      description: "Scope: `products:read`. Pass product_ids to export a subset, or empty for all."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExportProductsRequest'
      responses:
        '200':
          description: Export data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExportProductsResponse'

  # ── Transactions ──────────────────────────────────────────────
  /tax.v2.TransactionService/CommitTransaction:
    post:
      tags: [Transactions]
      summary: Commit a tax transaction
      description: "Scope: `transactions:write`. Geocodes the address, calculates tax, and records the transaction. Excise is computed only where the organization holds an active excise registration (NexusService): a destination state without one is skipped with excise_skipped_no_nexus:<STATE>, and an organization with no active excise registration at all books no excise and gets excise_no_registration (add the registrations first). State compliance requirements in force at the ship-to (directory listings, product registrations, prohibitions such as flavor or delivery-sale bans) add compliance_unregistered / compliance_prohibited:<STATE>:<requirement_code>:<sku> warnings, and a state license or permit the organization has not recorded as satisfied on its compliance tracker adds compliance_unregistered:<STATE>:<requirement_code> (no SKU; not raised alongside excise_no_registration). Applying the excise of a state the platform does not monitor yet adds coverage_pending:<STATE>. A requirement scoped to a sale channel reads it from the customerRefId's trade role (retailer, wholesaler, distributor, manufacturer: B2B; consumer: a delivery sale); a commit with no customer, or a customer with no trade role, matches every channel. An inline_product line is judged by its tax category and nicotine source with its flavor unknown; its warning names the line (items[i]) in place of the SKU, and product registrations, tracked per catalog product, do not apply to it. A prohibition an operator has set to hard-block refuses the commit with InvalidArgument on the line (items[i].product_id or items[i].inline_product) instead of warning; connector syncs and CSV imports, which record sales already made, are booked with the warning."
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          description: Makes the commit safe to retry. A retry with the same key returns the original transaction instead of recording a duplicate; the key is released if the commit fails. Keys are per environment: the same key used by a live and a test commit records one transaction in each, and each retry replays only its own.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CommitTransactionRequest'
      responses:
        '200':
          description: Committed transaction with tax details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CommitTransactionResponse'

  /tax.v2.TransactionService/GetTransaction:
    post:
      tags: [Transactions]
      summary: Get a transaction by ID
      description: "Scope: `transactions:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GetTransactionRequest'
      responses:
        '200':
          description: Transaction details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetTransactionResponse'

  /tax.v2.TransactionService/ListTransactions:
    post:
      tags: [Transactions]
      summary: List transactions
      description: "Scope: `transactions:read`. Filter by environment, status and registry customer, newest first."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListTransactionsRequest'
      responses:
        '200':
          description: Paginated transactions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListTransactionsResponse'

  /tax.v2.TransactionService/VoidTransaction:
    post:
      tags: [Transactions]
      summary: Void a transaction
      description: |
        Scope: `transactions:write`

        A live transaction a filed return or filed PACT report counted (its tax point in that
        period or month, committed before the filing) is refused (`invalid_argument` on `id`):
        voiding it would change what was filed. Reverse it instead. One committed into a filed
        period after the filing still voids, since the filing never counted it.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VoidTransactionRequest'
      responses:
        '200':
          description: Voided transaction
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VoidTransactionResponse'

  /tax.v2.TransactionService/ReverseTransaction:
    post:
      tags: [Transactions]
      summary: Reverse a transaction (refund or cancellation)
      description: |
        Scope: `transactions:write`

        Posts a negative-tax transaction mirroring the original, dated by `eventDate` (unset: now):
        it nets the sale out in that day's period and PACT month, while the original stays in its
        own. Calling it again returns the existing reversal.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ReverseTransactionRequest'
      responses:
        '200':
          description: The reversal
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ReverseTransactionResponse'

  /tax.v2.TransactionService/UpdateTransactionShipment:
    post:
      tags: [Transactions]
      summary: Record a committed sale's shipment
      description: "Scope: `transactions:write`. For shipping software that learns the ship date, carrier and tracking after the sale was committed. Name the transaction by transactionId, or by the source and externalId its commit carried in metadata (a connector's provider and order id, or a commit's externalId under source `api`). Each field sent replaces the stored value and an empty string clears it; a field left out is kept. A call that changes nothing records nothing. On a connector's sale, a field set here stands until the store itself changes that field (a later revision repeating the store's earlier value leaves it). The ship date is the sale's tax point (else its invoice date, else its commit day), so a new one can move the sale to another PACT report month and filing period; the tax already booked is not recalculated (RecomputeTransaction re-rates). Refused with invalid_argument: a voided or reversed transaction, a reversal, or a source and externalId matching several committed transactions. On a live transaction, refused with failed_precondition: a change to a sale a filed PACT report counted, a move out of a filed filing period that counted it (committed before the filing), or a move into another month with a filed filing period or PACT report."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateTransactionShipmentRequest'
      responses:
        '200':
          description: The transaction with its shipment
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateTransactionShipmentResponse'

  # ── Reconciliation ────────────────────────────────────────────
  /tax.v1.ReconciliationService/ListPotentialDuplicates:
    post:
      tags: [Reconciliation]
      summary: List potential duplicate transactions
      description: |
        Scope: `reconciliation:read`

        Clusters of transactions that share a customer email, order date and amount,
        newest first, while any member has no decision pairing it with another member. A
        transaction joining a decided cluster brings it back. `totalCount` counts every pending
        cluster, whatever the page.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListPotentialDuplicatesRequest'
      responses:
        '200':
          description: Pending duplicate clusters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListPotentialDuplicatesResponse'

  /tax.v1.ReconciliationService/RecordReconciliationDecision:
    post:
      tags: [Reconciliation]
      summary: Record a decision on a pair of potential duplicates
      description: |
        Scope: `reconciliation:write`

        One decision per pair, in either order; a later decision on the same pair replaces it.
        `RECONCILIATION_DECISION_KIND_MARK_DUPLICATE` leaves `excludedTransactionId` out of filing
        periods, PACT reports and compliance footprint, and the other transaction counts. Omit
        `excludedTransactionId` to exclude the greater ID. Changing the excluded side flags the open
        and closed filing periods of both transactions for recompute.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RecordReconciliationDecisionRequest'
      responses:
        '200':
          description: Recorded decision
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecordReconciliationDecisionResponse'

  # ── Filing ────────────────────────────────────────────────────
  /tax.v1.FilingService/CreateFilingSchedule:
    post:
      tags: [Filing]
      summary: Create a filing schedule
      description: "Scope: `filing:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateFilingScheduleRequest'
      responses:
        '200':
          description: Created schedule
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateFilingScheduleResponse'

  /tax.v1.FilingService/ListFilingSchedules:
    post:
      tags: [Filing]
      summary: List filing schedules
      description: "Scope: `filing:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Filing schedules
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListFilingSchedulesResponse'

  /tax.v1.FilingService/DeleteFilingSchedule:
    post:
      tags: [Filing]
      summary: Delete a filing schedule
      description: "Scope: `filing:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeleteFilingScheduleRequest'
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              type: object

  /tax.v1.FilingService/ListFilingPeriods:
    post:
      tags: [Filing]
      summary: List filing periods
      description: "Scope: `filing:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListFilingPeriodsRequest'
      responses:
        '200':
          description: Paginated filing periods
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListFilingPeriodsResponse'

  /tax.v1.FilingService/GetFilingPeriod:
    post:
      tags: [Filing]
      summary: Get a filing period
      description: "Scope: `filing:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Filing period with line summaries
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetFilingPeriodResponse'

  /tax.v1.FilingService/RecomputeFilingPeriod:
    post:
      tags: [Filing]
      summary: Recompute a filing period's totals
      description: "Scope: `filing:write` or `filing:recompute`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Recomputed filing period
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetFilingPeriodResponse'

  /tax.v1.FilingService/AmendFilingPeriod:
    post:
      tags: [Filing]
      summary: Amend a filed period
      description: "Scope: `filing:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Amended period
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetFilingPeriodResponse'

  /tax.v1.FilingService/GenerateTaxSummary:
    post:
      tags: [Filing]
      summary: Generate tax summary across jurisdictions
      description: "Scope: `filing:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GenerateTaxSummaryRequest'
      responses:
        '200':
          description: Tax summary
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GenerateTaxSummaryResponse'

  /tax.v1.FilingService/ExportTransactions:
    post:
      tags: [Filing]
      summary: Export transactions for a date range
      description: "Scope: `filing:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExportTransactionsRequest'
      responses:
        '200':
          description: Export file
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExportTransactionsResponse'

  /tax.v1.FilingService/GetFilingReturn:
    post:
      tags: [Filing]
      summary: Get the state return for a filing period
      description: |
        Scope: `filing:read` (live keys only)

        The line-by-line state return the platform computes for a filing period
        from its live committed transactions, keyed by form (`formId`, e.g.
        `LA/R-1029`). Values are decimal strings with two decimals; transmit them
        as they are. `valuesHash` is the lowercase hex SHA-256 of
        `canonicalJson`. Fails with `invalid_argument` when a line cannot be
        computed (for example a sale with no recorded price, or a late return).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GetFilingReturnRequest'
      responses:
        '200':
          description: Filing return
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetFilingReturnResponse'

  /tax.v1.FilingService/PrepareFilingRun:
    post:
      tags: [Filing]
      summary: Prepare a filing run for approval
      description: |
        Scope: `filing:write` (live keys only)

        Opens a filing run bound to the `valuesHash` of the `GetFilingReturn`
        payload the caller holds, with optional evidence `artifacts`. The period
        must be closed and the hash must be the period's return as of now
        (`invalid_argument` "stale payload" otherwise). Preparing the same hash
        again returns the run in flight; a new hash fails the prepared or
        approved run it supersedes. An org admin approves the run in the app
        (`filing:write` cannot approve; a key holding `filing:approve` can, see
        `ApproveFilingRun`).

        A PACT report's run (TAX-1431) passes `pactReportId` instead of
        `filingPeriodId`, with `valuesHash` the SHA-256 of the report's stored
        CSV (`PACTReport.contentSha256`). The report must be the month's newest,
        generated, for an ended month with no filed report, carry no blocking
        warning, and its stored CSV must still be what the live shipments
        render to. Approval and the submitting marker re-check the same and fail
        the run when it no longer holds; the confirmation files the report.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PrepareFilingRunRequest'
      responses:
        '200':
          description: Filing run
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingRunResponse'

  /tax.v1.FilingService/ApproveFilingRun:
    post:
      tags: [Filing]
      summary: Approve a prepared filing run
      description: |
        Scope: `filing:approve` (live keys only), or a signed-in org admin
        session.

        Approves a prepared run (a PACT report's included) for exactly the
        `valuesHash` the approver was shown; the run's must still be the
        period's current return, else the run fails ("prepare again"). The
        approver is recorded as `approvedBy` (a user) or, for a key,
        `approvedByApiKeyId` and `approvedByApiKeyName`, and the organization's
        admins are emailed "Filing run approved by API key <name>". `filing:write`
        does not approve, and a key of another organization cannot.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ApproveFilingRunRequest'
      responses:
        '200':
          description: Filing run
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingRunResponse'

  /tax.v1.FilingService/RecordFilingSubmission:
    post:
      tags: [Filing]
      summary: Record a filing run's portal submission
      description: |
        Scope: `filing:write` (live keys only)

        With no `confirmationNumber`, the submitting marker written immediately
        before the portal's Submit is clicked: an approved run moves to
        `SUBMITTED` exactly once, and only while the period's return is still the
        approved payload. With one, the run is confirmed and the period is marked
        filed (method `portal`) in the same transaction. `valuesHash` must be the
        run's.

        With `filedOutsideRun` the return was already filed in the state's
        portal: a prepared run is confirmed with no approval, and the period
        is filed as a confirmation does (the org's admins are emailed "Filing
        recorded as already filed (no approval)"). It needs a
        `confirmationNumber`, the run's `valuesHash` and at least one
        artifact (a portal screenshot or PDF showing the return filed), and
        is for an org admin or a key holding `filing:write`. Any other run
        status is refused (a confirmed run recorded again with the same
        confirmation is returned as it is). Never set it for a return the
        filer itself submits.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RecordFilingSubmissionRequest'
      responses:
        '200':
          description: Filing run
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingRunResponse'

  /tax.v1.FilingService/FailFilingRun:
    post:
      tags: [Filing]
      summary: Fail a filing run
      description: |
        Scope: `filing:write` (live keys only)

        Ends a prepared, approved or submitted run with a reason (at most 2000
        characters) and optional evidence. Confirmed and failed runs are final.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/FailFilingRunRequest'
      responses:
        '200':
          description: Filing run
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingRunResponse'

  /tax.v1.FilingService/GetFilingRun:
    post:
      tags: [Filing]
      summary: Get a filing run
      description: "Scope: `filing:read` (live keys only)"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id: { type: string }
      responses:
        '200':
          description: Filing run
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/FilingRunResponse'

  /tax.v1.FilingService/ListFilingRuns:
    post:
      tags: [Filing]
      summary: List a period's filing runs
      description: "Scope: `filing:read` (live keys only). Newest first."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [filingPeriodId]
              properties:
                filingPeriodId: { type: string }
      responses:
        '200':
          description: Filing runs
          content:
            application/json:
              schema:
                type: object
                properties:
                  runs: { type: array, items: { $ref: '#/components/schemas/FilingRun' } }

  /tax.v1.FilingService/GetFilingRequirement:
    post:
      tags: [Filing]
      summary: Get a state's excise return calendar
      description: |
        Scope: `filing:read`

        The platform's filing calendar entry for a state and tax type: the frequency, the due day (days after the period end), the first month of the cycle, the state's return form and the entry's source. It is what CreateFilingSchedule applies when sent no frequency. `requirement` is unset for a sales return, a county or city jurisdiction, or a state the calendar lacks. Not counsel-certified: check the frequency and due day with the state.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [jurisdictionId]
              properties:
                jurisdictionId:
                  type: string
                taxType:
                  type: string
                  enum: [excise, sales]
      responses:
        '200':
          description: The calendar entry, if any
          content:
            application/json:
              schema:
                type: object
                properties:
                  requirement:
                    type: object
                    properties:
                      stateCode:
                        type: string
                      frequency:
                        type: string
                        example: FILING_FREQUENCY_MONTHLY
                      dueDayOffset:
                        type: integer
                      anchorMonth:
                        type: integer
                      formRef:
                        type: string
                      citation:
                        type: string

  /tax.v1.FilingService/DownloadFilingRunArtifact:
    post:
      tags: [Filing]
      summary: Download a filing run's artifact
      description: "Scope: `filing:read` (live keys only)"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id, name]
              properties:
                id: { type: string }
                name: { type: string }
      responses:
        '200':
          description: Artifact bytes
          content:
            application/json:
              schema:
                type: object
                properties:
                  contentType: { type: string }
                  data: { type: string, format: byte }

  # ── Exemptions ────────────────────────────────────────────────
  /tax.v1.ExemptionService/CreateExemptionCertificate:
    post:
      tags: [Exemptions]
      summary: Create an exemption certificate
      description: "Scope: `exemptions:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateExemptionCertificateRequest'
      responses:
        '200':
          description: Created certificate
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateExemptionCertificateResponse'

  /tax.v1.ExemptionService/GetExemptionCertificate:
    post:
      tags: [Exemptions]
      summary: Get an exemption certificate
      description: "Scope: `exemptions:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Certificate details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetExemptionCertificateResponse'

  /tax.v1.ExemptionService/ListExemptionCertificates:
    post:
      tags: [Exemptions]
      summary: List exemption certificates
      description: "Scope: `exemptions:read`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListExemptionCertificatesRequest'
      responses:
        '200':
          description: Paginated certificates
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListExemptionCertificatesResponse'

  /tax.v1.ExemptionService/UpdateExemptionCertificate:
    post:
      tags: [Exemptions]
      summary: Update an exemption certificate
      description: "Scope: `exemptions:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateExemptionCertificateRequest'
      responses:
        '200':
          description: Updated certificate
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateExemptionCertificateResponse'

  /tax.v1.ExemptionService/RevokeExemptionCertificate:
    post:
      tags: [Exemptions]
      summary: Revoke an exemption certificate
      description: "Scope: `exemptions:write`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Revoked certificate
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RevokeExemptionCertificateResponse'

  # ── API Keys ──────────────────────────────────────────────────
  /tax.v1.ApiKeyService/CreateApiKey:
    post:
      tags: [API Keys]
      summary: Create an API key
      description: Returns the raw key exactly once. Store it securely.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateApiKeyRequest'
      responses:
        '200':
          description: Created key with raw value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateApiKeyResponse'

  /tax.v1.ApiKeyService/ListApiKeys:
    post:
      tags: [API Keys]
      summary: List API keys for your organization
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: API keys
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListApiKeysResponse'

  /tax.v1.ApiKeyService/RevokeApiKey:
    post:
      tags: [API Keys]
      summary: Revoke an API key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RevokeApiKeyRequest'
      responses:
        '200':
          description: Revoked key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RevokeApiKeyResponse'

  /tax.v1.ApiKeyService/UpdateApiKey:
    post:
      tags: [API Keys]
      summary: Update an API key
      description: >-
        Replaces the key's name, scopes, and expiry (full replace; send all three). Environment is fixed at creation. Changes apply to the next request made with the key. Revoked keys cannot be edited (failed_precondition). Admin users only.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateApiKeyRequest'
      responses:
        '200':
          description: Updated key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateApiKeyResponse'

  /tax.v1.ApiKeyService/RollApiKey:
    post:
      tags: [API Keys]
      summary: Roll an API key
      description: >-
        Issues a new key (new id and secret) with the same name, scopes, environment, and expiry, and retires the old key. gracePeriodHours 0 revokes the old key immediately; otherwise the old key keeps working until the grace period ends (or its existing expiry, if sooner), max 168 (7 days). Expired or revoked keys cannot be rolled (failed_precondition). The new raw key is returned once. Admin users only.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RollApiKeyRequest'
      responses:
        '200':
          description: Replacement key with raw value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RollApiKeyResponse'

  # ── Team ──────────────────────────────────────────────────────
  /tax.v1.AuthService/ListMembers:
    post:
      tags: [Team]
      summary: List organization members
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Members list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListMembersResponse'

  /tax.v1.AuthService/InviteMember:
    post:
      tags: [Team]
      summary: Invite a team member (admin only)
      description: Sends a 7-day invitation. Invitee accepts during onboarding.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InviteMemberRequest'
      responses:
        '200':
          description: Created invitation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InviteMemberResponse'

  /tax.v1.AuthService/ListInvitations:
    post:
      tags: [Team]
      summary: List pending invitations
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Invitations list
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListInvitationsResponse'

  /tax.v1.AuthService/RemoveMember:
    post:
      tags: [Team]
      summary: Remove a member (admin only)
      description: Cannot remove yourself or the last admin.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RemoveMemberRequest'
      responses:
        '200':
          description: Member removed
          content:
            application/json:
              type: object

  /tax.v1.AuthService/UpdateMemberRole:
    post:
      tags: [Team]
      summary: Change a member's role (admin only)
      description: Cannot demote the last admin.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpdateMemberRoleRequest'
      responses:
        '200':
          description: Updated member
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UpdateMemberRoleResponse'

  /tax.v1.AuthService/CancelInvitation:
    post:
      tags: [Team]
      summary: Cancel a pending invitation (admin only)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CancelInvitationRequest'
      responses:
        '200':
          description: Invitation cancelled
          content:
            application/json:
              type: object

  # ── Integrations ──────────────────────────────────────────────
  /tax.v1.IntegrationService/InitiateOAuth:
    post:
      tags: [Integrations]
      summary: Start OAuth flow for a provider
      description: "Scope: `integrations:manage`. Returns an authorization URL to redirect the user to."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/InitiateOAuthRequest'
      responses:
        '200':
          description: OAuth authorization URL
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/InitiateOAuthResponse'

  /tax.v1.IntegrationService/ListConnections:
    post:
      tags: [Integrations]
      summary: List integration connections
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Connections
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListConnectionsResponse'

  /tax.v1.IntegrationService/GetConnection:
    post:
      tags: [Integrations]
      summary: Get a connection by provider
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GetConnectionRequest'
      responses:
        '200':
          description: Connection details
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetConnectionResponse'

  /tax.v1.IntegrationService/Disconnect:
    post:
      tags: [Integrations]
      summary: Disconnect an integration
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connectionId]
              properties:
                connectionId:
                  type: string
      responses:
        '200':
          description: Disconnected
          content:
            application/json:
              type: object

  /tax.v1.IntegrationService/ListProviderItems:
    post:
      tags: [Integrations]
      summary: List items from a connected provider
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connectionId]
              properties:
                connectionId:
                  type: string
      responses:
        '200':
          description: Provider items
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListProviderItemsResponse'

  /tax.v1.IntegrationService/SetProductMapping:
    post:
      tags: [Integrations]
      summary: Map a provider item to a catalog product
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SetProductMappingRequest'
      responses:
        '200':
          description: Created mapping
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SetProductMappingResponse'

  /tax.v1.IntegrationService/DeleteProductMapping:
    post:
      tags: [Integrations]
      summary: Remove a product mapping
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connectionId, providerItemId]
              properties:
                connectionId:
                  type: string
                providerItemId:
                  type: string
      responses:
        '200':
          description: Mapping deleted
          content:
            application/json:
              type: object

  /tax.v1.IntegrationService/ListProductMappings:
    post:
      tags: [Integrations]
      summary: List product mappings for a connection
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [connectionId]
              properties:
                connectionId:
                  type: string
      responses:
        '200':
          description: Product mappings
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListProductMappingsResponse'

  /tax.v1.IntegrationService/ListSyncEvents:
    post:
      tags: [Integrations]
      summary: List sync events for a connection
      description: "Scope: `integrations:manage`"
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListSyncEventsRequest'
      responses:
        '200':
          description: Sync events
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListSyncEventsResponse'

  /tax.v1.IntegrationService/ListHeldObjects:
    post:
      tags: [Integrations]
      summary: List a connection's held orders
      description: >-
        Scope: `integrations:manage`. The connection's orders held for review or failed, oldest first, at most 500:
        each blocks the org's returns and PACT reports of the periods it could belong to. An org admin redrives or
        acknowledges one in the app (RedriveHeldObject, AcknowledgeHeldObject: signed-in admins only, never a key).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListHeldObjectsRequest'
      responses:
        '200':
          description: Held orders
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListHeldObjectsResponse'

  # ── Compliance ────────────────────────────────────────────────
  /tax.v1.ComplianceTrackerService/CheckEligibility:
    post:
      tags: [Compliance]
      summary: Check whether products may be sold into a destination
      description: >-
        Scope: `compliance:read`. Live keys and dashboard members, viewers included. Judges each line
        against the state compliance requirements active at the destination on the sale date (flavor and
        delivery-sale bans, directory listings, product registrations) and returns a per-line verdict
        with the requirements behind it: prohibited, needs_registration, unknown or allowed. The order
        verdict is the worst line (prohibited > needs_registration > unknown > allowed). Absence reads
        unknown, never allowed: a destination with no US state (no_state), a product the catalog does
        not know (unknown_product) or with no tax profile (no_category), or a state with no active
        state-level requirement reaching the line's category on the channel (no_coverage; a city or
        county row adds findings but is not the state's coverage). A requirement that matched only
        because product data (flavor status, nicotine source) or the channel is unknown reads unknown
        on its reason, except a hard-block prohibition, which reads prohibited because a commit
        refuses it either way. Read-only.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CheckEligibilityRequest'
      responses:
        '200':
          description: Eligibility verdict per line and for the order
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CheckEligibilityResponse'

  # ── Tax Rates (Public) ────────────────────────────────────────
  /tax.v1.TaxRateService/ListJurisdictions:
    post:
      tags: [Tax Rates]
      summary: List jurisdictions
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListJurisdictionsRequest'
      responses:
        '200':
          description: Jurisdictions
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListJurisdictionsResponse'

  /tax.v1.TaxRateService/GetJurisdiction:
    post:
      tags: [Tax Rates]
      summary: Get jurisdiction with parent chain
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Jurisdiction with hierarchy
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetJurisdictionResponse'

  /tax.v1.TaxRateService/ListActiveRules:
    post:
      tags: [Tax Rates]
      summary: List active tax rules
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ListActiveRulesRequest'
      responses:
        '200':
          description: Active rules
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListActiveRulesResponse'

  /tax.v1.TaxRateService/GetRule:
    post:
      tags: [Tax Rates]
      summary: Get a tax rule
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                id:
                  type: string
      responses:
        '200':
          description: Tax rule with components and evidence
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/GetRuleResponse'

  /tax.v1.TaxRateService/ListTaxCategories:
    post:
      tags: [Tax Rates]
      summary: List all tax categories
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
      responses:
        '200':
          description: Tax categories
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ListTaxCategoriesResponse'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Firebase ID token or API key (txk_* prefix)

  schemas:
    # ── Shared Types ────────────────────────────────────────────
    Timestamp:
      type: string
      format: date-time
      description: RFC 3339 timestamp

    # ── Enums ───────────────────────────────────────────────────
    UserRole:
      type: string
      enum: [USER_ROLE_UNSPECIFIED, USER_ROLE_ADMIN, USER_ROLE_MEMBER]

    ApiKeyEnvironment:
      type: string
      enum: [API_KEY_ENVIRONMENT_UNSPECIFIED, API_KEY_ENVIRONMENT_LIVE, API_KEY_ENVIRONMENT_TEST]

    TransactionStatus:
      type: string
      enum: [TRANSACTION_STATUS_UNSPECIFIED, TRANSACTION_STATUS_COMMITTED, TRANSACTION_STATUS_VOIDED]

    TaxEventKind:
      type: string
      description: "The taxable event a calculation or transaction represents. Federal excise is gated by event kind (e.g. SALE excludes it; REMOVAL/IMPORT/FLOOR_STOCK include it). Required on CalculateTax, CalculateOrderTax, and CommitTransaction."
      enum: [TAX_EVENT_KIND_UNSPECIFIED, TAX_EVENT_KIND_SALE, TAX_EVENT_KIND_PURCHASE, TAX_EVENT_KIND_IMPORT, TAX_EVENT_KIND_REMOVAL, TAX_EVENT_KIND_FIRST_POSSESSION, TAX_EVENT_KIND_DISTRIBUTION, TAX_EVENT_KIND_DELIVERY, TAX_EVENT_KIND_RETURN, TAX_EVENT_KIND_REFUND, TAX_EVENT_KIND_EXPORT, TAX_EVENT_KIND_FLOOR_STOCK]

    FilingFrequency:
      type: string
      enum: [FILING_FREQUENCY_UNSPECIFIED, FILING_FREQUENCY_MONTHLY, FILING_FREQUENCY_QUARTERLY, FILING_FREQUENCY_ANNUAL]

    FilingPeriodStatus:
      type: string
      enum: [FILING_PERIOD_STATUS_UNSPECIFIED, FILING_PERIOD_STATUS_OPEN, FILING_PERIOD_STATUS_CLOSED, FILING_PERIOD_STATUS_FILED, FILING_PERIOD_STATUS_AMENDED]

    ExportFormat:
      type: string
      enum: [EXPORT_FORMAT_UNSPECIFIED, EXPORT_FORMAT_CSV, EXPORT_FORMAT_JSON]

    ExemptionType:
      type: string
      enum: [EXEMPTION_TYPE_UNSPECIFIED, EXEMPTION_TYPE_TRIBAL, EXEMPTION_TYPE_MILITARY, EXEMPTION_TYPE_RESALE, EXEMPTION_TYPE_GOVERNMENT, EXEMPTION_TYPE_MANUFACTURER]

    ExemptionStatus:
      type: string
      enum: [EXEMPTION_STATUS_UNSPECIFIED, EXEMPTION_STATUS_ACTIVE, EXEMPTION_STATUS_EXPIRED, EXEMPTION_STATUS_REVOKED]

    ReconciliationDecisionKind:
      type: string
      enum: [RECONCILIATION_DECISION_KIND_UNSPECIFIED, RECONCILIATION_DECISION_KIND_KEEP_SEPARATE, RECONCILIATION_DECISION_KIND_MARK_DUPLICATE]

    IntegrationProvider:
      type: string
      enum: [INTEGRATION_PROVIDER_UNSPECIFIED, INTEGRATION_PROVIDER_QUICKBOOKS, INTEGRATION_PROVIDER_XERO, INTEGRATION_PROVIDER_SHOPIFY]

    IntegrationConnectionStatus:
      type: string
      enum: [INTEGRATION_CONNECTION_STATUS_UNSPECIFIED, INTEGRATION_CONNECTION_STATUS_ACTIVE, INTEGRATION_CONNECTION_STATUS_DISCONNECTED, INTEGRATION_CONNECTION_STATUS_ERROR]

    # ── Entity Models ───────────────────────────────────────────
    User:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        firebaseUid: { type: string }
        email: { type: string }
        name: { type: string }
        role: { $ref: '#/components/schemas/UserRole' }
        avatarUrl: { type: string }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }

    Organization:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        slug: { type: string }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }

    Invitation:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        organizationName: { type: string }
        email: { type: string }
        role: { $ref: '#/components/schemas/UserRole' }
        expiresAt: { $ref: '#/components/schemas/Timestamp' }
        createdAt: { $ref: '#/components/schemas/Timestamp' }

    ApiKey:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        name: { type: string }
        keyPrefix: { type: string, description: "First 8 chars for display" }
        scopes: { type: array, items: { type: string } }
        environment: { $ref: '#/components/schemas/ApiKeyEnvironment' }
        expiresAt: { $ref: '#/components/schemas/Timestamp' }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        revoked: { type: boolean }
        lastUsedAt: { $ref: '#/components/schemas/Timestamp' }

    CatalogProduct:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        sku: { type: string }
        description: { type: string }
        active: { type: boolean }
        isGlobal: { type: boolean }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        productType: { type: string, description: "PACT product classification (e.g. e-liquid, disposable, closed pod, device); distinct from the tax profile's taxCategoryCode" }
        regulatory: { $ref: '#/components/schemas/ProductRegulatory' }

    ProductRegulatory:
      type: object
      description: "Regulatory identity for state directory and flavor-restriction compliance. Empty enum strings read as unknown."
      properties:
        manufacturerName: { type: string }
        brandName: { type: string }
        productLine: { type: string, description: "Model (NE ENDS directory) or brand style (CA Unflavored Tobacco List)" }
        flavorName: { type: string }
        selfManufactured: { type: boolean, description: "The org manufactures (or is the certifying importer of) this product" }
        characterizingFlavor: { type: string, enum: [unknown, "yes", "no"] }
        fdaStatus: { type: string, enum: [unknown, marketing_granted, pmta_pending, pmta_denied, denial_stayed, not_submitted] }
        fdaStn: { type: string, description: "FDA submission tracking number (PMTA STN)" }
        gtin: { type: string, description: "GTIN of the SKU (UPC-A 12, EAN-13, EAN-8 or ITF-14 digits, GS1 check digit verified), for state directory listings; empty = unknown. Catalog sync fills an empty one from the mapped store item's barcode" }
        tnBrandId: { type: string, description: "Tennessee PACT brand ID (TN file column V): the ID TN's brand list gives the product's brand family, or -1 when the brand is not on the list (column W then carries brandName). Read on cigarette, roll-your-own and smokeless rows; ENDS rows are always -1. Empty = not recorded (a blocking gap on those rows). At most 9 characters, no comma or whitespace" }

    ProductTaxProfileMsg:
      type: object
      properties:
        id: { type: string }
        catalogProductId: { type: string }
        taxCategoryCode: { type: string }
        unitCount: { type: integer, nullable: true }
        weightGrams: { type: string, nullable: true }
        volumeMl: { type: string, nullable: true, description: "Per device for ecig_* / eliquid_bottled" }
        nicotineMgTotal: { type: string, nullable: true, description: "One device's mg for ecig_* / eliquid_bottled, one can's for nicotine_pouch (packageCount = cans in the SKU), else the whole product's" }
        nicotineMgPerMl: { type: string, nullable: true, description: "Basis for per-mg nicotine rates when nicotineMgTotal is unset (x volumeMl)" }
        wholesalePrice: { type: string, nullable: true }
        wholesalePurchasePrice: { type: string, nullable: true, description: "WPP (seller cost), distinct from wholesalePrice" }
        retailPrice: { type: string, nullable: true }
        manufacturerPrice: { type: string, nullable: true }
        nicotineSource: { type: string, description: "tobacco_derived | synthetic | none" }
        containsTobacco: { type: boolean }
        attributeTags: { type: array, items: { type: string } }
        syntheticNicotine: { type: boolean }
        closedSystem: { type: boolean }
        disposable: { type: boolean }
        packageCount: { type: integer, nullable: true, description: "Packaging geometry (replaces packCount). For ecig_* / eliquid_bottled, per-mL and per-mg levies apply to packageCount x unitsPerPackage devices" }
        unitsPerPackage: { type: integer, nullable: true, description: "Devices per package for ecig_* / eliquid_bottled" }
        sticksPerUnit: { type: integer, nullable: true }

    TaxProduct:
      type: object
      properties:
        taxCategoryCode: { type: string }
        unitCount: { type: integer, nullable: true, description: "Taxable units in the whole SKU; for ecig_* / eliquid_bottled at least packageCount x unitsPerPackage. Not read for a stick product (sticksPerUnit > 0), whose per-unit levies count its sticks" }
        weightGrams: { type: string, nullable: true }
        volumeMl: { type: string, nullable: true, description: "Per device for ecig_* / eliquid_bottled" }
        nicotineMgTotal: { type: string, nullable: true, description: "One device's mg for ecig_* / eliquid_bottled, one can's for nicotine_pouch (packageCount = cans in the SKU), else the whole product's" }
        nicotineMgPerMl: { type: string, nullable: true, description: "Basis for per-mg nicotine rates when nicotineMgTotal is unset (x volumeMl)" }
        wholesalePrice: { type: string, nullable: true }
        retailPrice: { type: string, nullable: true }
        manufacturerPrice: { type: string, nullable: true }
        nicotineSource: { type: string }
        containsTobacco: { type: boolean }
        attributeTags: { type: array, items: { type: string } }
        wholesalePurchasePrice: { type: string, nullable: true, description: "WPP (seller cost), distinct from wholesalePrice" }
        packageCount: { type: integer, nullable: true, description: "Packaging geometry (replaces packCount). For ecig_* / eliquid_bottled, per-mL and per-mg levies apply to packageCount x unitsPerPackage devices" }
        unitsPerPackage: { type: integer, nullable: true, description: "Devices per package for ecig_* / eliquid_bottled" }
        sticksPerUnit: { type: integer, nullable: true }

    Transaction:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        address: { type: string }
        matchedAddress: { type: string }
        jurisdictionId: { type: string }
        environment: { $ref: '#/components/schemas/ApiKeyEnvironment' }
        status: { $ref: '#/components/schemas/TransactionStatus' }
        totalTax: { type: string }
        currency: { type: string }
        committedAt: { $ref: '#/components/schemas/Timestamp' }
        voidedAt: { $ref: '#/components/schemas/Timestamp' }
        lineItems: { type: array, items: { $ref: '#/components/schemas/TransactionLineItem' } }
        exemptionCertificateId: { type: string }
        customerRefId: { type: string, description: "Registry customer the transaction is attached to; empty when none." }
        invoiceNumber: { type: string, description: "Source order/invoice number (a connector's order number, or a CSV import's invoice_number column); empty when the source gave none." }

    TransactionLineItem:
      type: object
      properties:
        id: { type: string }
        lineNumber: { type: integer }
        productId: { type: string }
        taxCategoryCode: { type: string }
        quantity: { type: integer }
        perUnitTax: { type: string }
        lineTotalTax: { type: string }
        taxDetails: { type: array, items: { $ref: '#/components/schemas/TransactionTaxDetail' } }

    TransactionTaxDetail:
      type: object
      properties:
        id: { type: string }
        jurisdictionId: { type: string }
        jurisdictionCode: { type: string }
        jurisdictionName: { type: string }
        ruleId: { type: string }
        componentKind: { type: string }
        unitCode: { type: string }
        rate: { type: string }
        amount: { type: string }

    BulkProductResult:
      type: object
      properties:
        rowIndex: { type: integer }
        success: { type: boolean }
        productId: { type: string }
        error: { type: string }

    # ── Request/Response Schemas ────────────────────────────────

    # Tax Calculation
    CalculateTaxRequest:
      type: object
      required: [eventKind]
      properties:
        address: { type: string, description: "Street address for jurisdiction matching" }
        productId: { type: string, description: "Existing catalog product ID" }
        inlineProduct: { $ref: '#/components/schemas/TaxProduct', description: "Or provide product details inline" }
        asOfDate: { type: string, description: "YYYY-MM-DD, defaults to today" }
        eventKind: { $ref: '#/components/schemas/TaxEventKind', description: "The taxable event this calculation represents. Federal excise is gated by event kind (e.g. SALE excludes federal; REMOVAL/IMPORT/FLOOR_STOCK include it)." }
        taxTypes:
          type: array
          items: { type: string }
          description: "Optional tax types the caller wants, e.g. [\"excise\"]. The quote computes excise only; this field decides only the sales_tax_not_computed marker in warnings: an org in the compute sales-tax mode that sends tax types naming \"excise\" but not \"sales\" (case-insensitive) gets no marker. Other values are ignored, so a list of only unknown values gets the marker as an empty one does."
        applyRegistrations: { type: boolean, description: "Gate the quote by the organization's active excise registrations, as a commit is: only the states it is registered in (excise_skipped_no_nexus:<STATE> for the others), only the levies its role there owes (role_not_taxable warnings for the others), federal by its federal role. Default false: every role's levies show. An organization with no active excise registration gets the ungated quote and excise_no_registration either way." }

    CalculateTaxResponse:
      type: object
      properties:
        jurisdictions: { type: array, items: { $ref: '#/components/schemas/TaxBreakdownJurisdiction' } }
        totalTax: { type: string }
        matchedAddress: { type: string }
        jurisdictionId: { type: string }
        warnings:
          type: array
          items: { type: string }
          description: "Soft warnings. The quote never computes sales tax and says so with exactly one sales_tax_not_computed:<reason> entry: <reason> is the org's sales-tax mode for the ship-to state (off, the default; shadow; record_collected), or quote_excise_only when that mode is compute. It is left out only when the mode is compute and taxTypes names excise but not sales. Commit warnings of the form sales_tax_not_computed:<JUR>:<category> (two segments) name one jurisdiction; agents can match the shared sales_tax_not_computed prefix. coverage_pending:<STATE> (quotes and commits) says the excise of a state the platform does not monitor yet was applied: its published rates are served but not watched for changes. excise_no_registration says the organization holds no active excise registration: the quote still shows the excise, but a commit computes none until the registrations are added."
        registrationsApplied: { type: boolean, description: "True when the quote was gated by the organization's excise registrations (applyRegistrations, and it holds at least one)." }

    TaxBreakdownJurisdiction:
      type: object
      properties:
        jurisdictionId: { type: string }
        jurisdictionCode: { type: string }
        jurisdictionName: { type: string }
        jurisdictionType: { type: string }
        components: { type: array, items: { $ref: '#/components/schemas/TaxBreakdownComponent' } }
        subtotal: { type: string }

    TaxBreakdownComponent:
      type: object
      properties:
        ruleId: { type: string }
        componentKind: { type: string }
        unitCode: { type: string }
        rate: { type: string }
        amount: { type: string }
        taxableRoles:
          type: array
          items: { type: string }
          description: "The seller roles the levy falls on (manufacturer, importer, distributor, wholesaler, retailer, remote_seller): a commit applies the component only for an organization registered in the state in one of them. A commit gates on the component's roles and its rule's, so this is their overlap (either alone when the other names none), and for a federal levy only manufacturer and importer. Empty means every role; \"(none)\" alone means no role owes it."

    OrderLineItem:
      type: object
      properties:
        productId: { type: string }
        inlineProduct: { $ref: '#/components/schemas/TaxProduct' }
        quantity: { type: integer }

    CalculateOrderTaxRequest:
      type: object
      required: [eventKind]
      properties:
        address: { type: string }
        items: { type: array, items: { $ref: '#/components/schemas/OrderLineItem' } }
        asOfDate: { type: string }
        eventKind: { $ref: '#/components/schemas/TaxEventKind', description: "The taxable event this calculation represents." }
        taxTypes:
          type: array
          items: { type: string }
          description: "As on CalculateTaxRequest: decides only the sales_tax_not_computed marker."
        applyRegistrations: { type: boolean, description: "As on CalculateTaxRequest." }

    CalculateOrderTaxResponse:
      type: object
      properties:
        lineItems: { type: array, items: { $ref: '#/components/schemas/OrderLineItemTax' } }
        totalTax: { type: string }
        matchedAddress: { type: string }
        jurisdictionId: { type: string }
        warnings:
          type: array
          items: { type: string }
          description: "Soft warnings for the whole order, with the same single sales_tax_not_computed:<reason> marker as CalculateTaxResponse.warnings."
        registrationsApplied: { type: boolean, description: "As on CalculateTaxResponse." }

    QuoteCheckoutTaxRequest:
      type: object
      required: [shipTo, lines]
      properties:
        shipTo:
          type: object
          required: [state, postalCode, country]
          properties:
            line1: { type: string }
            line2: { type: string }
            city: { type: string }
            state: { type: string, description: "USPS code" }
            postalCode: { type: string }
            country: { type: string, description: "ISO 3166-1 alpha-2" }
        lines:
          type: array
          minItems: 1
          maxItems: 200
          items:
            type: object
            required: [lineId, sku, quantity, unitPrice]
            properties:
              lineId: { type: string }
              sku: { type: string }
              quantity: { type: integer }
              unitPrice: { type: string, description: "Decimal dollars per unit" }
              discount: { type: string, description: "Line total discount, decimal dollars" }
        asOfDate: { type: string, description: "YYYY-MM-DD; default today" }

    QuoteCheckoutTaxResponse:
      type: object
      properties:
        lines:
          type: array
          items:
            type: object
            properties:
              lineId: { type: string }
              taxable: { type: string }
              taxes:
                type: array
                items:
                  type: object
                  properties:
                    code: { type: string }
                    name: { type: string }
                    taxType: { type: string, description: "Always sales" }
                    rate: { type: string, description: "Percent of the line's taxable amount" }
                    amount: { type: string, description: "Dollars, to the cent" }
        totalTax: { type: string }

    QuoteBuyerLeviesResponse:
      type: object
      properties:
        lines:
          type: array
          description: "One per request line, in order; a line with no buyer-borne levy lists none"
          items:
            type: object
            properties:
              lineId: { type: string }
              taxable: { type: string }
              levies:
                type: array
                items:
                  type: object
                  properties:
                    code: { type: string, description: "e.g. CA-CECET" }
                    name: { type: string, description: "e.g. California Electronic Cigarette Excise Tax" }
                    jurisdiction: { type: string, description: "USPS state code" }
                    rate: { type: string, description: "Percent of the line's taxable amount" }
                    amount: { type: string, description: "Dollars, to the cent" }
        total: { type: string }

    ReportBuyerLeviesResponse:
      type: object
      properties:
        rows:
          type: array
          items:
            type: object
            properties:
              jurisdiction: { type: string }
              code: { type: string }
              month: { type: string, description: "Tax-point month, YYYY-MM" }
              orders: { type: integer }
              collected: { type: string }
              owed: { type: string }
              gap: { type: string, description: "owed - collected; positive is under-collected" }
        gapOrders:
          type: array
          items:
            type: object
            properties:
              transactionId: { type: string }
              externalId: { type: string }
              jurisdiction: { type: string }
              code: { type: string }
              month: { type: string, description: "Tax-point month, YYYY-MM" }
              collected: { type: string }
              owed: { type: string }

    OrderLineItemTax:
      type: object
      properties:
        lineNumber: { type: integer }
        taxCategoryCode: { type: string }
        quantity: { type: integer }
        perUnitTax: { type: string }
        lineTotalTax: { type: string }
        jurisdictions: { type: array, items: { $ref: '#/components/schemas/TaxBreakdownJurisdiction' } }

    # Products
    CreateProductRequest:
      type: object
      required: [name]
      properties:
        name: { type: string, minLength: 1 }
        sku: { type: string }
        description: { type: string }
        productType: { type: string, description: "PACT product classification (e.g. e-liquid, disposable, closed pod, device)" }
        regulatory: { $ref: '#/components/schemas/ProductRegulatory', description: "Unset creates the product with an all-unknown regulatory record" }

    CreateProductResponse:
      type: object
      properties:
        product: { $ref: '#/components/schemas/CatalogProduct' }

    GetProductRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    GetProductResponse:
      type: object
      properties:
        product: { $ref: '#/components/schemas/CatalogProduct' }
        taxProfile: { $ref: '#/components/schemas/ProductTaxProfileMsg' }

    ListProductsRequest:
      type: object
      properties:
        pageSize: { type: integer, default: 50, maximum: 100 }
        offset: { type: integer, default: 0 }
        search: { type: string, description: "Search by name or SKU (case insensitive)" }
        taxCategoryCode: { type: string }
        nicotineSource: { type: string }
        activeOnly: { type: boolean }

    ListProductsResponse:
      type: object
      properties:
        products: { type: array, items: { $ref: '#/components/schemas/CatalogProduct' } }
        totalCount: { type: integer }

    UpdateProductRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }
        name: { type: string }
        sku: { type: string }
        description: { type: string }
        active: { type: boolean }
        productType: { type: string, description: "PACT product classification (e.g. e-liquid, disposable, closed pod, device)" }
        regulatory: { $ref: '#/components/schemas/ProductRegulatory', description: "Unset leaves the stored regulatory record unchanged; set replaces it" }

    UpdateProductResponse:
      type: object
      properties:
        product: { $ref: '#/components/schemas/CatalogProduct' }

    DeleteProductRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    SetProductTaxProfileRequest:
      type: object
      required: [productId, taxCategoryCode]
      properties:
        productId: { type: string }
        taxCategoryCode: { type: string }
        unitCount: { type: integer }
        weightGrams: { type: string }
        volumeMl: { type: string, description: "Per device for ecig_* / eliquid_bottled" }
        nicotineMgTotal: { type: string, description: "One device's mg for ecig_* / eliquid_bottled, one can's for nicotine_pouch (packageCount = cans in the SKU), else the whole product's" }
        nicotineMgPerMl: { type: string, description: "Basis for per-mg nicotine rates when nicotineMgTotal is unset (x volumeMl)" }
        wholesalePrice: { type: string }
        wholesalePurchasePrice: { type: string, description: "WPP (seller cost), distinct from wholesalePrice" }
        retailPrice: { type: string }
        manufacturerPrice: { type: string }
        nicotineSource: { type: string }
        containsTobacco: { type: boolean }
        attributeTags: { type: array, items: { type: string } }
        packageCount: { type: integer, description: "Packaging geometry (replaces packCount). For ecig_* / eliquid_bottled, per-mL and per-mg levies apply to packageCount x unitsPerPackage devices" }
        unitsPerPackage: { type: integer, description: "Devices per package for ecig_* / eliquid_bottled" }
        sticksPerUnit: { type: integer }

    SetProductTaxProfileResponse:
      type: object
      properties:
        taxProfile: { $ref: '#/components/schemas/ProductTaxProfileMsg' }

    GetProductTaxProfileRequest:
      type: object
      required: [productId]
      properties:
        productId: { type: string }

    GetProductTaxProfileResponse:
      type: object
      properties:
        taxProfile: { $ref: '#/components/schemas/ProductTaxProfileMsg' }

    BulkCreateProductsRequest:
      type: object
      required: [products]
      properties:
        products:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: object
            required: [name, taxCategoryCode]
            properties:
              name: { type: string, minLength: 1 }
              sku: { type: string }
              description: { type: string }
              taxCategoryCode: { type: string, minLength: 1 }
              unitCount: { type: integer }
              weightGrams: { type: string }
              volumeMl: { type: string, description: "Per device for ecig_* / eliquid_bottled" }
              wholesalePrice: { type: string }
              wholesalePurchasePrice: { type: string, description: "WPP (seller cost), distinct from wholesalePrice" }
              retailPrice: { type: string }
              manufacturerPrice: { type: string }
              nicotineSource: { type: string }
              containsTobacco: { type: boolean }
              attributeTags: { type: array, items: { type: string } }
              packageCount: { type: integer, description: "Packaging geometry (replaces packCount). For ecig_* / eliquid_bottled, per-mL and per-mg levies apply to packageCount x unitsPerPackage devices" }
              unitsPerPackage: { type: integer, description: "Devices per package for ecig_* / eliquid_bottled" }
              sticksPerUnit: { type: integer }
              productType: { type: string }
              regulatory: { $ref: '#/components/schemas/ProductRegulatory', description: "Unset imports the product with an all-unknown regulatory record" }

    BulkCreateProductsResponse:
      type: object
      properties:
        results: { type: array, items: { $ref: '#/components/schemas/BulkProductResult' } }
        createdCount: { type: integer }
        errorCount: { type: integer }

    BulkUpdateProductsRequest:
      type: object
      required: [products]
      properties:
        products:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: object
            required: [productId]
            properties:
              productId: { type: string }
              name: { type: string }
              sku: { type: string }
              description: { type: string }
              productType: { type: string }
              taxCategoryCode: { type: string }
              nicotineSource: { type: string }
              containsTobacco: { type: boolean }
              unitCount: { type: integer }
              volumeMl: { type: string, description: "Per device for ecig_* / eliquid_bottled" }
              weightGrams: { type: string }
              wholesalePrice: { type: string }
              wholesalePurchasePrice: { type: string, description: "WPP (seller cost), distinct from wholesalePrice" }
              retailPrice: { type: string }
              manufacturerPrice: { type: string }
              attributeTags: { type: array, items: { type: string } }
              syntheticNicotine: { type: boolean }
              closedSystem: { type: boolean }
              disposable: { type: boolean }
              packageCount: { type: integer, description: "Packaging geometry (replaces packCount). For ecig_* / eliquid_bottled, per-mL and per-mg levies apply to packageCount x unitsPerPackage devices" }
              unitsPerPackage: { type: integer, description: "Devices per package for ecig_* / eliquid_bottled" }
              sticksPerUnit: { type: integer }
              nicotineMgPerMl: { type: string, description: "Basis for per-mg nicotine rates when nicotineMgTotal is unset (x volumeMl)" }
              nicotineMgTotal: { type: string, description: "One device's mg for ecig_* / eliquid_bottled, one can's for nicotine_pouch (packageCount = cans in the SKU), else the whole product's" }
              manufacturerName: { type: string, description: "Regulatory fields: each one sent replaces the stored value; omitted ones are kept" }
              brandName: { type: string }
              productLine: { type: string }
              flavorName: { type: string }
              selfManufactured: { type: boolean }
              characterizingFlavor: { type: string, enum: [unknown, "yes", "no"] }
              fdaStatus: { type: string, enum: [unknown, marketing_granted, pmta_pending, pmta_denied, denial_stayed, not_submitted] }
              fdaStn: { type: string }
              gtin: { type: string, description: "GTIN (8, 12, 13 or 14 digits with a valid GS1 check digit); an empty string clears it" }
              tnBrandId: { type: string, description: "Tennessee PACT brand ID (see ProductRegulatory.tnBrandId); an empty string clears it" }

    BulkUpdateProductsResponse:
      type: object
      properties:
        results: { type: array, items: { $ref: '#/components/schemas/BulkProductResult' } }
        updatedCount: { type: integer }
        errorCount: { type: integer }

    ExportProductsRequest:
      type: object
      properties:
        productIds: { type: array, items: { type: string }, description: "Empty = export all" }
        format: { type: string, description: "csv or json, default csv" }

    ExportProductsResponse:
      type: object
      properties:
        data: { type: string, format: byte }
        filename: { type: string }
        contentType: { type: string }

    # Transactions
    CommitTransactionRequest:
      type: object
      required: [address, items, eventKind]
      properties:
        address: { type: string }
        items: { type: array, items: { $ref: '#/components/schemas/OrderLineItem' } }
        asOfDate: { type: string }
        metadata: { type: object, additionalProperties: { type: string } }
        exemptionCertificateId: { type: string, description: "Certificate to apply. When omitted on a commit with a customerRefId, the customer's active st_resale certificate covering the ship-to state (if any) is applied, and recorded on the transaction if it exempts a line." }
        customerRefId: { type: string, description: "Registry customer the sale is to; validated against the caller's organization. Its trade role sets the sale channel for channel-scoped compliance requirements." }
        eventKind: { $ref: '#/components/schemas/TaxEventKind', description: "The taxable event this transaction records (one per transaction). Required — gates federal excise." }
        recipientName: { type: string, description: "PACT shipment fields, all optional: the recipient, as reported on PACT reports" }
        recipientAddress: { type: string, description: "The combined ship-to line" }
        recipientCity: { type: string }
        recipientState: { type: string }
        recipientZip: { type: string }
        recipientPhone: { type: string }
        recipientAgeVerified: { type: boolean }
        deliveryCarrierName: { type: string }
        deliveryCarrierAddress: { type: string }
        shipDate: { type: string, description: "RFC 3339. The sale's tax point (the day that places it in its PACT month and filing period) when set" }
        trackingNumber: { type: string }
        packageWeightOz: { type: string, description: "Decimal ounces" }
        invoiceNumber: { type: string }
        invoiceDate: { type: string, description: "YYYY-MM-DD. The tax point when shipDate is unset" }
        externalId: { type: string, description: "Your durable key for the sale (its order or invoice id), stored as metadata external_id, under metadata source `api` when metadata names no source. A commit naming an externalId already committed in the same environment under the same source returns that transaction instead of booking another, however long after (an Idempotency-Key lasts 24 hours); a voided or reversed one does not count, so a commit after ReverseTransaction re-sells the order. UpdateTransactionShipment finds the sale by the same source and externalId." }

    CommitTransactionResponse:
      type: object
      properties:
        transaction: { $ref: '#/components/schemas/Transaction' }

    GetTransactionRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    GetTransactionResponse:
      type: object
      properties:
        transaction: { $ref: '#/components/schemas/Transaction' }

    ListTransactionsRequest:
      type: object
      properties:
        pageSize: { type: integer }
        offset: { type: integer }
        environment: { $ref: '#/components/schemas/ApiKeyEnvironment' }
        status: { $ref: '#/components/schemas/TransactionStatus' }
        customerRefId: { type: string, description: "Only transactions attached to this registry customer (the customerRefId sent at commit). Empty = no filter; another organization's customer matches nothing." }

    ListTransactionsResponse:
      type: object
      properties:
        transactions: { type: array, items: { $ref: '#/components/schemas/Transaction' } }
        totalCount: { type: integer }

    VoidTransactionRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    VoidTransactionResponse:
      type: object
      properties:
        transaction: { $ref: '#/components/schemas/Transaction' }

    ReverseTransactionRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }
        reason: { type: string, maxLength: 500, description: "Why the sale is reversed; recorded on the reversal." }
        eventDate: { $ref: '#/components/schemas/Timestamp' }

    ReverseTransactionResponse:
      type: object
      properties:
        transaction: { $ref: '#/components/schemas/Transaction' }

    UpdateTransactionShipmentRequest:
      type: object
      description: "transactionId, or source and externalId. Each other field is optional: sent, it replaces the stored value (an empty string clears it); left out, it is kept."
      properties:
        transactionId: { type: string }
        source: { type: string, description: "The metadata source of the commit: a connector's provider (shopify, woocommerce, ...) or api" }
        externalId: { type: string, description: "The commit's metadata external_id: a connector's order id, or the commit's externalId" }
        shipDate: { type: string, description: "RFC 3339; its calendar day in its own offset is the tax point" }
        trackingNumber: { type: string }
        packageWeightOz: { type: string, description: "Decimal ounces" }
        deliveryCarrierName: { type: string }
        deliveryCarrierAddress: { type: string }

    UpdateTransactionShipmentResponse:
      type: object
      properties:
        transaction: { $ref: '#/components/schemas/Transaction' }

    # Reconciliation
    PotentialDuplicateMember:
      type: object
      properties:
        transactionId: { type: string }
        channel: { type: string, description: 'Integration source, e.g. shopify, medusa, api' }
        externalId: { type: string, description: "The source system's order/invoice ID; empty when it reported none" }

    PotentialDuplicate:
      type: object
      properties:
        customerEmail: { type: string }
        orderDate: { type: string, format: date, description: YYYY-MM-DD }
        amountCents: { type: string, description: 'int64, JSON-encoded as a string' }
        transactionIds: { type: array, items: { type: string } }
        members:
          type: array
          description: Each transaction's source, in transactionIds order
          items: { $ref: '#/components/schemas/PotentialDuplicateMember' }

    CheckEligibilityRequest:
      type: object
      required: [lines]
      properties:
        address: { type: string, description: "Ship-to street address, geocoded like a commit's (an address that does not geocode is InvalidArgument on address). Exactly one of address or stateCode." }
        stateCode: { type: string, description: "USPS state code, e.g. NE. A code naming no US state reads unknown (no_state)." }
        lines:
          type: array
          minItems: 1
          maxItems: 100
          items:
            type: object
            description: Exactly one of productId or sku.
            properties:
              productId: { type: string, description: "Catalog product id (the org's own, or a global product)." }
              sku: { type: string, description: "Active catalog SKU; the org's own product wins over a global one." }
        channel:
          type: string
          enum: ['', consumer_delivery, b2b]
          description: "The sale's channel. Empty is unknown: it matches every requirement channel, and a requirement matched only that way reads unknown (a hard-block prohibition prohibited)."
        asOf: { type: string, format: date, description: "Sale date requirements are judged on; default today." }

    CheckEligibilityResponse:
      type: object
      properties:
        verdict: { type: string, enum: [allowed, unknown, needs_registration, prohibited] }
        stateCode: { type: string, description: "Destination state; empty when none." }
        matchedAddress: { type: string }
        channel: { type: string }
        lines:
          type: array
          items:
            type: object
            properties:
              lineNumber: { type: integer, description: "1-based, in request order." }
              productId: { type: string }
              sku: { type: string }
              verdict: { type: string, enum: [allowed, unknown, needs_registration, prohibited] }
              unknownCauses: { type: array, items: { type: string, enum: [no_state, unknown_product, no_category, no_coverage] } }
              reasons:
                type: array
                items:
                  type: object
                  properties:
                    requirementId: { type: string }
                    code: { type: string }
                    name: { type: string }
                    stateCode: { type: string }
                    localityCode: { type: string, description: "The city or county of a local prohibition (e.g. CA-SAN-FRANCISCO), which applies only to a ship-to address inside it; empty for a state row. A stateCode request sees state rows only." }
                    localityName: { type: string }
                    effect: { type: string, enum: [registration, prohibition] }
                    verdict: { type: string, enum: [prohibited, needs_registration, unknown] }
                    hardBlock: { type: boolean, description: "An API commit this prohibition matches is refused (InvalidArgument) instead of warned; connector syncs and CSV imports are booked with the warning." }
                    citationUrl: { type: string }
                    effectiveDate: { type: string, format: date }
                    productDataUnknown: { type: boolean }
                    channelUnknown: { type: boolean }
                    channel: { type: string, enum: [any, consumer_delivery, b2b] }

    ListPotentialDuplicatesRequest:
      type: object
      properties:
        pageSize: { type: integer, description: 'Default 20, max 100' }
        offset: { type: integer }

    ListPotentialDuplicatesResponse:
      type: object
      properties:
        duplicates: { type: array, items: { $ref: '#/components/schemas/PotentialDuplicate' } }
        totalCount: { type: string, description: 'int64, JSON-encoded as a string' }

    RecordReconciliationDecisionRequest:
      type: object
      required: [transactionIdA, transactionIdB, decision]
      properties:
        transactionIdA: { type: string }
        transactionIdB: { type: string }
        decision: { $ref: '#/components/schemas/ReconciliationDecisionKind' }
        notes: { type: string }
        excludedTransactionId:
          type: string
          description: >-
            MARK_DUPLICATE only: transactionIdA or transactionIdB, the copy left out of totals.
            Omitted, the greater ID is excluded. Must be omitted for KEEP_SEPARATE.

    RecordReconciliationDecisionResponse:
      type: object
      properties:
        decisionId: { type: string }
        decidedAt: { $ref: '#/components/schemas/Timestamp' }
        excludedTransactionId: { type: string, description: 'The excluded transaction; empty for KEEP_SEPARATE' }

    # Filing
    CreateFilingScheduleRequest:
      type: object
      required: [jurisdictionId, taxType]
      properties:
        jurisdictionId: { type: string }
        frequency: { $ref: '#/components/schemas/FilingFrequency' }
        anchorMonth: { type: integer }
        dueDayOffset: { type: integer }
        notes: { type: string }
        taxType: { type: string, enum: [excise, sales], description: 'The return this schedule files. Required: an empty value is refused (invalid_argument on tax_type), never defaulted.' }
        accountNumber: { type: string, description: "The state's account number for this return" }
        formParams:
          type: object
          additionalProperties: { type: string }
          description: >-
            The return form's per-schedule parameters beyond the account number, validated by the form
            (Arizona TPT-2 sales: region_code, city_code, business_code). Must be empty when the form takes none.
        firstPeriodStart:
          type: string
          format: date
          description: >-
            Optional YYYY-MM-DD in the org's timezone, not after today and at most 24 months back: periods are
            generated from the one containing it rather than today's, so a schedule created after a period ended
            still gets that period. Empty starts at today's period.

    CreateFilingScheduleResponse:
      type: object
      properties:
        schedule: { $ref: '#/components/schemas/FilingSchedule' }

    FilingSchedule:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        jurisdictionId: { type: string }
        frequency: { $ref: '#/components/schemas/FilingFrequency' }
        anchorMonth: { type: integer }
        dueDayOffset: { type: integer }
        notes: { type: string }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        taxType: { type: string, enum: [excise, sales] }
        accountNumber: { type: string }
        endedOn:
          type: string
          format: date
          description: >-
            The last day the schedule covers (YYYY-MM-DD), empty while it is open-ended. No period starts after it,
            and it stops counting toward the organization's active states once the day and the period holding it
            have passed (that period is kept and still due). An org admin ends or reopens a schedule from the
            dashboard; API keys cannot.

    ListFilingSchedulesResponse:
      type: object
      properties:
        schedules: { type: array, items: { $ref: '#/components/schemas/FilingSchedule' } }

    DeleteFilingScheduleRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    ListFilingPeriodsRequest:
      type: object
      properties:
        pageSize: { type: integer }
        offset: { type: integer }
        jurisdictionId: { type: string }
        status: { $ref: '#/components/schemas/FilingPeriodStatus' }
        fromDate: { type: string }
        toDate: { type: string }

    ListFilingPeriodsResponse:
      type: object
      properties:
        periods: { type: array, items: { $ref: '#/components/schemas/FilingPeriod' } }
        totalCount: { type: integer }

    FilingPeriod:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        jurisdictionId: { type: string }
        filingScheduleId: { type: string }
        periodStart: { type: string }
        periodEnd: { type: string }
        dueDate: { type: string }
        status: { $ref: '#/components/schemas/FilingPeriodStatus' }
        needsRecompute: { type: boolean }
        totalTax: { type: string }
        totalTransactions: { type: integer }
        totalUnits: { type: integer }
        filedAt: { $ref: '#/components/schemas/Timestamp' }
        amendedAt: { $ref: '#/components/schemas/Timestamp' }
        notes: { type: string }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        taxType: { type: string, enum: [excise, sales] }

    GetFilingPeriodResponse:
      type: object
      properties:
        period: { $ref: '#/components/schemas/FilingPeriod' }
        stateFormAvailable:
          type: boolean
          description: >-
            GetFilingPeriod only: ExportTransactions with EXPORT_FORMAT_STATE_FORM works for this period (an excise
            period on a state whose excise worksheet is supported).

    GenerateTaxSummaryRequest:
      type: object
      required: [fromDate, toDate]
      properties:
        fromDate: { type: string }
        toDate: { type: string }
        jurisdictionId: { type: string }

    GenerateTaxSummaryResponse:
      type: object
      properties:
        lines: { type: array, items: { $ref: '#/components/schemas/JurisdictionSummaryLine' } }
        grandTotal: { type: string }

    JurisdictionSummaryLine:
      type: object
      properties:
        jurisdictionId: { type: string }
        taxCategoryCode: { type: string }
        componentKind: { type: string }
        unitCode: { type: string }
        totalQuantity: { type: integer }
        totalTax: { type: string }
        transactionCount: { type: integer }

    ExportTransactionsRequest:
      type: object
      required: [fromDate, toDate]
      properties:
        fromDate: { type: string }
        toDate: { type: string }
        jurisdictionId: { type: string }
        format: { $ref: '#/components/schemas/ExportFormat' }

    ExportTransactionsResponse:
      type: object
      properties:
        content: { type: string, format: byte }
        contentType: { type: string }
        filename: { type: string }

    GetFilingReturnRequest:
      type: object
      required: [filingPeriodId]
      properties:
        filingPeriodId: { type: string }

    GetFilingReturnResponse:
      type: object
      properties:
        filingReturn: { $ref: '#/components/schemas/FilingReturn' }

    FilingReturn:
      type: object
      properties:
        formId: { type: string, example: LA/R-1029 }
        formRevision: { type: string }
        taxType: { type: string, enum: [excise, sales] }
        accountNumber: { type: string }
        filingPeriodId: { type: string }
        periodStart: { type: string, format: date }
        periodEnd: { type: string, format: date }
        dueDate: { type: string, format: date }
        lines: { type: array, items: { $ref: '#/components/schemas/FilingReturnLine' }, description: 'In form order' }
        totalDue: { type: string, example: '119.00' }
        valuesHash: { type: string, description: 'Lowercase hex SHA-256 of canonicalJson' }
        canonicalJson: { type: string }

    FilingReturnLine:
      type: object
      properties:
        lineCode: { type: string, example: gross_sales }
        formLine: { type: string, example: '1' }
        label: { type: string }
        value: { type: string, example: '6447.00' }
        keys:
          type: object
          additionalProperties: { type: string }
          example: { region_code: MAR, business_code: '017' }
          description: |
            The line's row on a row-based return, where a line code repeats once
            per row. Absent on a form of fixed lines (LA/R-1029). `lineCode` and
            `keys` together are unique within a return.

    FilingRunArtifactUpload:
      type: object
      description: |
        At most 10 per call holding at most 5 MiB in all (about 6.7 MiB once
        base64-encoded). Names match ^[A-Za-z0-9._-]{1,100}$ and are unique per
        run; re-sending identical bytes under a stored name is a no-op.
      properties:
        name: { type: string, example: readback.png }
        contentType: { type: string, enum: [image/png, image/jpeg, application/pdf, application/json, text/plain] }
        data: { type: string, format: byte }

    FilingRunArtifact:
      type: object
      properties:
        name: { type: string }
        contentType: { type: string }
        sizeBytes: { type: string, description: 'int64, JSON-encoded as a string' }
        sha256: { type: string }

    FilingRun:
      type: object
      properties:
        id: { type: string }
        filingPeriodId: { type: string }
        formId: { type: string, example: LA/R-1029 }
        valuesHash: { type: string }
        status: { type: string, enum: [FILING_RUN_STATUS_PREPARED, FILING_RUN_STATUS_APPROVED, FILING_RUN_STATUS_SUBMITTED, FILING_RUN_STATUS_CONFIRMED, FILING_RUN_STATUS_FAILED] }
        approvedBy: { type: string, description: "The approving user's id" }
        approvedByApiKeyId: { type: string, description: 'Set instead of approvedBy when an API key holding filing:approve approved the run' }
        approvedByApiKeyName: { type: string, description: "That key's name" }
        filedOutsideRun: { type: boolean, description: 'Recorded as already filed in the portal, with no approval' }
        approvedAt: { $ref: '#/components/schemas/Timestamp' }
        submittedAt: { $ref: '#/components/schemas/Timestamp' }
        confirmationNumber: { type: string }
        artifacts: { type: array, items: { $ref: '#/components/schemas/FilingRunArtifact' } }
        error: { type: string }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        lines: { type: array, items: { $ref: '#/components/schemas/FilingReturnLine' }, description: 'The payload as prepared' }

    FilingRunResponse:
      type: object
      properties:
        run: { $ref: '#/components/schemas/FilingRun' }

    PrepareFilingRunRequest:
      type: object
      required: [valuesHash]
      properties:
        filingPeriodId: { type: string, description: 'Exactly one of filingPeriodId and pactReportId' }
        pactReportId: { type: string, description: 'A PACT report run (TAX-1431); valuesHash is its CSV SHA-256' }
        valuesHash: { type: string }
        artifacts: { type: array, items: { $ref: '#/components/schemas/FilingRunArtifactUpload' } }

    RecordFilingSubmissionRequest:
      type: object
      required: [id, valuesHash]
      properties:
        id: { type: string }
        valuesHash: { type: string }
        confirmationNumber: { type: string, description: 'Empty for the submitting marker' }
        artifacts: { type: array, items: { $ref: '#/components/schemas/FilingRunArtifactUpload' } }
        filedOutsideRun: { type: boolean, description: 'Record a return already filed in the portal on a prepared run, with no approval; needs confirmationNumber and an artifact' }

    ApproveFilingRunRequest:
      type: object
      required: [id, valuesHash]
      properties:
        id: { type: string }
        valuesHash: { type: string, description: 'The hash the approver was shown' }

    FailFilingRunRequest:
      type: object
      required: [id, error]
      properties:
        id: { type: string }
        error: { type: string, maxLength: 2000 }
        artifacts: { type: array, items: { $ref: '#/components/schemas/FilingRunArtifactUpload' } }

    # Exemptions
    ExemptionCertificate:
      type: object
      properties:
        id: { type: string }
        organizationId: { type: string }
        customerId: { type: string }
        customerName: { type: string }
        exemptionType: { $ref: '#/components/schemas/ExemptionType' }
        status: { $ref: '#/components/schemas/ExemptionStatus' }
        certificateNumber: { type: string }
        jurisdictionIds: { type: array, items: { type: string } }
        categories: { type: array, items: { type: string } }
        effectiveDate: { type: string }
        expirationDate: { type: string }
        notes: { type: string }
        exemptionPercentage: { type: integer, format: int32, minimum: 0, maximum: 100, description: "Percent of tax exempted; 0 and 100 mean full exemption, while 1 through 99 mean a partial exemption." }
        createdAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        revokedAt: { $ref: '#/components/schemas/Timestamp' }

    CreateExemptionCertificateRequest:
      type: object
      required: [customerId, effectiveDate]
      properties:
        customerId: { type: string }
        customerName: { type: string }
        exemptionType: { $ref: '#/components/schemas/ExemptionType' }
        certificateNumber: { type: string }
        jurisdictionIds: { type: array, minItems: 1, items: { type: string } }
        categories: { type: array, minItems: 1, items: { type: string } }
        effectiveDate: { type: string }
        expirationDate: { type: string }
        notes: { type: string }
        exemptionPercentage: { type: integer, format: int32, minimum: 0, maximum: 100, description: "Percent of tax exempted; 0 and 100 mean full exemption, while 1 through 99 mean a partial exemption." }

    CreateExemptionCertificateResponse:
      type: object
      properties:
        certificate: { $ref: '#/components/schemas/ExemptionCertificate' }

    GetExemptionCertificateResponse:
      type: object
      properties:
        certificate: { $ref: '#/components/schemas/ExemptionCertificate' }

    ListExemptionCertificatesRequest:
      type: object
      properties:
        pageSize: { type: integer }
        offset: { type: integer }
        status: { $ref: '#/components/schemas/ExemptionStatus' }
        customerId: { type: string, description: "Matches the certificate's free-text customerId." }
        customerRefId: { type: string, description: "Matches the registry customer linked to the certificate (customerRefId)." }

    ListExemptionCertificatesResponse:
      type: object
      properties:
        certificates: { type: array, items: { $ref: '#/components/schemas/ExemptionCertificate' } }
        totalCount: { type: integer }

    UpdateExemptionCertificateRequest:
      type: object
      description: Replaces the certificate's fields, so it carries the same rules as create.
      required: [id, customerId, effectiveDate]
      properties:
        id: { type: string }
        customerId: { type: string }
        customerName: { type: string }
        exemptionType: { $ref: '#/components/schemas/ExemptionType' }
        certificateNumber: { type: string }
        jurisdictionIds: { type: array, minItems: 1, items: { type: string } }
        categories: { type: array, minItems: 1, items: { type: string } }
        effectiveDate: { type: string }
        expirationDate: { type: string }
        notes: { type: string }
        exemptionPercentage: { type: integer, format: int32, minimum: 0, maximum: 100, description: "Percent of tax exempted; 0 and 100 mean full exemption, while 1 through 99 mean a partial exemption. Omit this field to preserve the current value." }

    UpdateExemptionCertificateResponse:
      type: object
      properties:
        certificate: { $ref: '#/components/schemas/ExemptionCertificate' }

    RevokeExemptionCertificateResponse:
      type: object
      properties:
        certificate: { $ref: '#/components/schemas/ExemptionCertificate' }

    # API Keys
    CreateApiKeyRequest:
      type: object
      required: [name]
      properties:
        name: { type: string, minLength: 1 }
        environment: { $ref: '#/components/schemas/ApiKeyEnvironment' }
        scopes: { type: array, items: { type: string }, minItems: 1, description: "At least one scope required; unscoped keys are rejected" }
        expiresAt: { $ref: '#/components/schemas/Timestamp' }

    CreateApiKeyResponse:
      type: object
      properties:
        apiKey: { $ref: '#/components/schemas/ApiKey' }
        rawKey: { type: string, description: "Full key value. Only shown once — store securely." }
        availableScopes: { type: array, items: { type: string } }

    ListApiKeysResponse:
      type: object
      properties:
        apiKeys: { type: array, items: { $ref: '#/components/schemas/ApiKey' } }

    RevokeApiKeyRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }

    RevokeApiKeyResponse:
      type: object
      properties:
        apiKey: { $ref: '#/components/schemas/ApiKey' }

    UpdateApiKeyRequest:
      type: object
      required: [id, name, scopes]
      properties:
        id: { type: string }
        name: { type: string, minLength: 1 }
        scopes: { type: array, minItems: 1, items: { type: string }, description: "At least one scope required" }
        expiresAt: { $ref: '#/components/schemas/Timestamp' }

    UpdateApiKeyResponse:
      type: object
      properties:
        apiKey: { $ref: '#/components/schemas/ApiKey' }

    RollApiKeyRequest:
      type: object
      required: [id]
      properties:
        id: { type: string }
        gracePeriodHours: { type: integer, format: uint32, minimum: 0, maximum: 168, default: 0 }

    RollApiKeyResponse:
      type: object
      properties:
        apiKey: { $ref: '#/components/schemas/ApiKey' }
        rawKey: { type: string, description: "Full key value. Only shown once — store securely." }
        previousApiKey: { $ref: '#/components/schemas/ApiKey' }

    # Team
    ListMembersResponse:
      type: object
      properties:
        members: { type: array, items: { $ref: '#/components/schemas/User' } }

    InviteMemberRequest:
      type: object
      required: [email]
      properties:
        email: { type: string, format: email }
        role: { $ref: '#/components/schemas/UserRole' }

    InviteMemberResponse:
      type: object
      properties:
        invitation: { $ref: '#/components/schemas/Invitation' }

    ListInvitationsResponse:
      type: object
      properties:
        invitations: { type: array, items: { $ref: '#/components/schemas/Invitation' } }

    RemoveMemberRequest:
      type: object
      required: [userId]
      properties:
        userId: { type: string }

    UpdateMemberRoleRequest:
      type: object
      required: [userId]
      properties:
        userId: { type: string }
        role: { $ref: '#/components/schemas/UserRole' }

    UpdateMemberRoleResponse:
      type: object
      properties:
        user: { $ref: '#/components/schemas/User' }

    CancelInvitationRequest:
      type: object
      required: [invitationId]
      properties:
        invitationId: { type: string }

    # Integrations
    IntegrationConnection:
      type: object
      properties:
        id: { type: string }
        provider: { $ref: '#/components/schemas/IntegrationProvider' }
        status: { $ref: '#/components/schemas/IntegrationConnectionStatus' }
        environment: { type: string }
        providerOrgId: { type: string, description: "The provider's account id (shop domain, realm, merchant). Empty for Odoo: its webhook URL carries the delivery token and is shown only once, by ConnectOdoo." }
        displayName: { type: string }
        tokenExpiry: { $ref: '#/components/schemas/Timestamp' }
        connectedAt: { $ref: '#/components/schemas/Timestamp' }
        updatedAt: { $ref: '#/components/schemas/Timestamp' }
        lastError: { type: string }
        capabilities:
          type: object
          description: Which per-connection settings the connection's connector reads.
          properties:
            catalogSync: { type: boolean, description: "Catalog rules and SyncProviderCatalog apply" }
            orderRules: { type: boolean, description: "Orders are routed by the order rules (SetOrderRules); with no rule none is ingested" }
        pollHealth:
          type: object
          description: Scheduled-poll health (15-minute polls and the nightly sweep). Absent when the connector does not poll.
          properties:
            dryRun: { type: boolean, description: "Polls report what they would book and book nothing" }
            lastSuccessAt: { $ref: '#/components/schemas/Timestamp' }
            lastFailureAt: { $ref: '#/components/schemas/Timestamp' }
            lastError: { type: string, description: "The latest failure's error while polls are failing; a success clears it" }
            consecutiveFailures: { type: integer }
            lastSweepAt: { $ref: '#/components/schemas/Timestamp' }
            lastSweepFailureAt: { $ref: '#/components/schemas/Timestamp' }
            sweepLastError: { type: string }
            sweepConsecutiveFailures: { type: integer }
        historyImport:
          type: object
          description: >-
            The latest order-history import: the orders from before automatic polling starts booking, which an org
            admin imports in the app (ImportOrderHistory: signed-in admins only, never a key). It covers [from, to),
            to being where automatic polling starts booking; nextFrom is the start of the first day not imported yet,
            where a retry resumes. Absent when none ran or the connector does not poll.
          properties:
            from: { $ref: '#/components/schemas/Timestamp' }
            to: { $ref: '#/components/schemas/Timestamp' }
            status: { type: string, enum: [running, succeeded, failed] }
            nextFrom: { $ref: '#/components/schemas/Timestamp' }
            windows: { type: integer, description: "Days imported" }
            events: { type: integer, description: "Store orders read" }
            received: { type: integer, description: "Orders new to the platform" }
            duplicates: { type: integer, description: "Orders it already had" }
            error: { type: string, description: "The latest attempt's error; a running import retries" }
            startedAt: { $ref: '#/components/schemas/Timestamp' }
            finishedAt: { $ref: '#/components/schemas/Timestamp' }
            dryRun:
              type: boolean
              description: >-
                A dry run: the connection's commit_mode is dry_run, so the import books nothing (received and
                duplicates stay 0) and stores report rows only.

    InitiateOAuthRequest:
      type: object
      required: [provider]
      properties:
        provider: { $ref: '#/components/schemas/IntegrationProvider' }
        shopDomain: { type: string, description: "Required for Shopify" }

    InitiateOAuthResponse:
      type: object
      properties:
        authorizationUrl: { type: string }
        state: { type: string }

    ListConnectionsResponse:
      type: object
      properties:
        connections: { type: array, items: { $ref: '#/components/schemas/IntegrationConnection' } }

    GetConnectionRequest:
      type: object
      properties:
        provider: { $ref: '#/components/schemas/IntegrationProvider' }

    GetConnectionResponse:
      type: object
      properties:
        connection: { $ref: '#/components/schemas/IntegrationConnection' }

    ListProviderItemsResponse:
      type: object
      properties:
        items:
          type: array
          items:
            type: object
            properties:
              providerItemId: { type: string }
              name: { type: string }
              sku: { type: string }
              description: { type: string }
              suggestedProductId:
                type: string
                description: The catalog product with this item's SKU ('' for none).
              mappedProductId:
                type: string
                description: The catalog product this connection already maps the item to ('' when unmapped). The import skips a mapped item.

    SetProductMappingRequest:
      type: object
      required: [connectionId, providerItemId, catalogProductId]
      properties:
        connectionId: { type: string }
        providerItemId: { type: string }
        providerItemName: { type: string }
        catalogProductId: { type: string }

    SetProductMappingResponse:
      type: object
      properties:
        mapping:
          type: object
          properties:
            id: { type: string }
            connectionId: { type: string }
            providerItemId: { type: string }
            providerItemName: { type: string }
            catalogProductId: { type: string }
            catalogProductName: { type: string }
            autoMatched: { type: boolean }
            createdAt: { $ref: '#/components/schemas/Timestamp' }

    ListProductMappingsResponse:
      type: object
      properties:
        mappings: { type: array, items: { $ref: '#/components/schemas/SetProductMappingResponse/properties/mapping' } }

    ListSyncEventsRequest:
      type: object
      required: [connectionId]
      properties:
        connectionId: { type: string }
        pageSize: { type: integer }
        offset: { type: integer }

    ListSyncEventsResponse:
      type: object
      properties:
        events:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              connectionId: { type: string }
              providerInvoiceId: { type: string }
              transactionId: { type: string }
              status: { type: string }
              message: { type: string }
              occurredAt: { $ref: '#/components/schemas/Timestamp' }
        totalCount: { type: integer }

    ListHeldObjectsRequest:
      type: object
      required: [connectionId]
      properties:
        connectionId: { type: string }

    ListHeldObjectsResponse:
      type: object
      properties:
        objects:
          type: array
          items:
            type: object
            properties:
              objectId: { type: string }
              reason: { type: string }
              topic: { type: string }
              taxPointDate: { type: string, description: "YYYY-MM-DD; empty when unknown (it then blocks every period)" }
              firstHeldAt: { $ref: '#/components/schemas/Timestamp' }

    # Tax Rates
    Jurisdiction:
      type: object
      properties:
        id: { type: string }
        code: { type: string }
        name: { type: string }
        countryCode: { type: string }
        jurisdictionType: { type: string }
        parentId: { type: string }
        fipsCode: { type: string }

    ListJurisdictionsRequest:
      type: object
      properties:
        jurisdictionType: { type: string }
        parentId: { type: string }
        countryCode: { type: string }

    ListJurisdictionsResponse:
      type: object
      properties:
        jurisdictions: { type: array, items: { $ref: '#/components/schemas/Jurisdiction' } }

    GetJurisdictionResponse:
      type: object
      properties:
        jurisdiction: { $ref: '#/components/schemas/Jurisdiction' }
        chain: { type: array, items: { $ref: '#/components/schemas/Jurisdiction' } }

    ListActiveRulesRequest:
      type: object
      properties:
        jurisdictionId: { type: string }
        taxCategoryCode: { type: string }

    ListActiveRulesResponse:
      type: object
      properties:
        rules: { type: array, items: { $ref: '#/components/schemas/TaxRule' } }

    TaxRule:
      type: object
      properties:
        id: { type: string }
        jurisdictionId: { type: string }
        jurisdictionCode: { type: string }
        jurisdictionName: { type: string }
        taxCategoryCode: { type: string }
        effectiveStartDate: { $ref: '#/components/schemas/Timestamp' }
        effectiveEndDate: { $ref: '#/components/schemas/Timestamp' }
        status: { type: string }
        applicabilityJson: { type: string }
        components: { type: array, items: { $ref: '#/components/schemas/TaxRuleComponent' } }

    TaxRuleComponent:
      type: object
      properties:
        id: { type: string }
        componentKind: { type: string }
        unitCode: { type: string }
        amount: { type: string }
        percent: { type: string }
        minimumAmount: { type: string }
        maximumAmount: { type: string }
        componentOrder: { type: integer }
        taxableRoles:
          type: array
          description: Seller roles this component is levied on (manufacturer, importer, distributor, wholesaler, retailer, remote_seller). Empty means every role.
          items: { type: string }

    GetRuleResponse:
      type: object
      properties:
        rule: { $ref: '#/components/schemas/TaxRule' }

    ListTaxCategoriesResponse:
      type: object
      properties:
        categories:
          type: array
          items:
            type: object
            properties:
              code: { type: string }
              label: { type: string }
              description: { type: string }
              parentCode: { type: string }
              sortOrder: { type: integer }
