Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

55.1 KB
Raw Blame
import type {
  AuthProvidersResponse,
  ListParams,
  PaginatedResponse,
  PreferenceSchema,
  RequestFn,
  RequestOptions,
  UploadFileOptions,
} from '@spree/sdk-core'
import { transformListParams, uploadFile } from '@spree/sdk-core'
import type {
  Account,
  AuthTokens,
  Balance,
  Claim,
  Country,
  Delivery,
  DeliveryMethod,
  DeliveryProfile,
  DeliveryZone,
  DigitalAsset,
  Exchange,
  Export,
  FileUpload,
  Fulfillment,
  Import,
  ImportFilters,
  ImportRow,
  ImportRowFilters,
  ImportRowSort,
  ImportSort,
  Invitation,
  InvitationAcceptanceLink,
  Order,
  PackageType,
  Payout,
  Policy,
  Product,
  ProductType,
  Profile,
  Reason,
  RequirementStatus,
  RequirementSubmission,
  Return,
  SellerSummary,
  ShippingLabel,
  StockLocation,
  Store,
  TaxIdentifier,
  TeamMember,
  Transfer,
} from './types'
import type {
  DeliveryMethodFilters,
  DeliveryMethodSort,
  DeliveryProfileFilters,
  DeliveryProfileSort,
  DigitalAssetFilters,
  DigitalAssetSort,
  OrderFilters,
  OrderSort,
  PackageTypeFilters,
  PackageTypeSort,
  PolicyFilters,
  PolicySort,
  ProductFilters,
  ProductSort,
  ProductTypeFilters,
  ProductTypeSort,
  SellerPayoutFilters,
  SellerPayoutSort,
  SellerTransferFilters,
  SellerTransferSort,
  StockLocationFilters,
  StockLocationSort,
} from './types/filters.generated'
import type {
  AccountUpdateParams,
  ClaimCancelParams,
  ClaimCreateParams,
  ClaimDenyParams,
  ClaimResolveParams,
  DeliveryCreateParams,
  DeliveryMethodCreateParams,
  DeliveryMethodUpdateParams,
  DeliveryUpdateParams,
  DigitalAssetCreateParams,
  DigitalAssetUpdateParams,
  ExchangeCancelParams,
  ExchangeCreateParams,
  ExchangeFulfillParams,
  ExchangeReceiveParams,
  FileUploadCreateParams,
  FulfillmentFulfillParams,
  FulfillmentSplitParams,
  FulfillmentUpdateParams,
  ImportCompleteMappingParams,
  ImportCreateParams,
  InvitationAcceptParams,
  LoginParams,
  OnboardingPayoutAccountParams,
  OrderAddressCorrectionParams,
  OrderCancelParams,
  OrderNotesParams,
  PackageTypeCreateParams,
  PackageTypeUpdateParams,
  PasswordResetCreateParams,
  PasswordResetUpdateParams,
  PolicyCreateParams,
  PolicyUpdateParams,
  ProductBulkDestroyParams,
  ProductBulkStatusParams,
  ProductBulkSubmitParams,
  ProductCreateParams,
  ProductUpdateParams,
  ProductVariantParams,
  ProfileUpdateParams,
  RequirementSubmissionParams,
  ReturnCancelParams,
  ReturnCreateParams,
  ReturnReceiveParams,
  ReturnRefundParams,
  SellerExportCreateParams,
  SellerTaxIdentifierCreateParams,
  SellerTaxIdentifierUpdateParams,
  ShippingLabelCreateParams,
  StockLocationCreateParams,
  StockLocationUpdateParams,
  TeamMemberCreateParams,
} from './types/params'

export type * from './types/params'

/** @deprecated Renamed to `ProductVariantParams`. */
export type SellerProductVariantParams = ProductVariantParams

/**
 * Resource methods for the Spree Seller API — the marketplace seller panel.
 *
 * Every path is relative to `/api/v3/seller` and is scoped server-side to the
 * seller named in `X-Spree-Seller-Id`, so nothing here takes a seller id: a
 * seller acts as one seller at a time, chosen from the list `me()` returns.
 */
export class SellerClient {
  constructor(private readonly request: RequestFn) {}

  readonly auth = {
    /**
     * Signs a seller in. Fails for a store staff member who runs no seller —
     * authenticating is not enough, since staff share the same user class.
     */
    login: (params: LoginParams, options?: RequestOptions): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', '/auth/login', { ...options, body: params }),

    /** Exchanges the refresh cookie for a fresh access token. */
    refresh: (options?: RequestOptions): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', '/auth/refresh', options),

    /** Clears the session server-side and drops the refresh cookie. */
    logout: (options?: RequestOptions): Promise<void> =>
      this.request<void>('POST', '/auth/logout', options),

    /** Sign-in methods this marketplace offers sellers, for the login page. */
    providers: (options?: RequestOptions): Promise<AuthProvidersResponse> =>
      this.request<AuthProvidersResponse>('GET', '/auth/providers', options),

    /**
     * Reads an invitation from the emailed link, before anyone signs in — the
     * page needs the invited address to decide whether it is asking someone to
     * set a password or to confirm the one they already have.
     */
    lookupInvitation: (
      invitationId: string,
      token: string,
      options?: RequestOptions,
    ): Promise<Invitation> =>
      this.request<Invitation>('GET', `/auth/invitations/${invitationId}/lookup`, {
        ...options,
        params: { token },
      }),

    /**
     * Accepts the invitation and returns a signed-in seller session, so the
     * new member lands in the panel rather than on a login form.
     */
    acceptInvitation: (
      invitationId: string,
      token: string,
      params: InvitationAcceptParams,
      options?: RequestOptions,
    ): Promise<AuthTokens> =>
      this.request<AuthTokens>('POST', `/auth/invitations/${invitationId}/accept`, {
        ...options,
        params: { token },
        body: params,
      }),

    /**
     * Asks for a password reset email. Always resolves (202) whether or not the
     * address matches a seller, so this cannot be used to discover which
     * accounts exist. The emailed link opens the seller panel — `redirect_url`
     * when it passes the store's allowed-origin check, otherwise the panel
     * origin the server resolves for itself.
     */
    requestPasswordReset: (
      params: PasswordResetCreateParams,
      options?: RequestOptions,
    ): Promise<void> =>
      this.request<void>('POST', '/auth/password_resets', { ...options, body: params }),

    /**
     * Spends a reset token: sets the new password and returns a signed-in
     * seller session, so they land in the panel rather than on a login form.
     * The token is single-use, and resetting revokes every other session the
     * account holds.
     */
    resetPassword: (
      token: string,
      params: PasswordResetUpdateParams,
      options?: RequestOptions,
    ): Promise<AuthTokens> =>
      this.request<AuthTokens>('PATCH', `/auth/password_resets/${encodeURIComponent(token)}`, {
        ...options,
        body: params,
      }),
  }

  /**
   * The signed-in person: who they are, which sellers they may act for, and
   * what they may do on the selected one.
   *
   * `permission_keys` is empty until a seller is named — capability is per
   * seller, so there is no answer spanning all of them.
   *
   * Read it with `me.get()` and edit it with `me.update()`. Calling `me()`
   * directly still works for code written against 1.0.0-beta.1/beta.2, but is
   * deprecated and warns once per client.
   */
  readonly me: MeResource = Object.assign(
    (options?: RequestOptions): Promise<MeResponse> => {
      if (!this.meCallDeprecationWarned) {
        this.meCallDeprecationWarned = true
        console.warn(
          '[@spree/seller-sdk] `client.me()` is deprecated; use `client.me.get()` instead.',
        )
      }
      return this.me.get(options)
    },
    {
      get: (options?: RequestOptions): Promise<MeResponse> =>
        this.request<MeResponse>('GET', '/me', options),

      update: (params: AccountUpdateParams, options?: RequestOptions): Promise<MeResponse> =>
        this.request<MeResponse>('PATCH', '/me', { ...options, body: params }),
    },
  )

  private meCallDeprecationWarned = false

  /** The seller's own record, as they maintain it. */
  readonly profile = {
    get: (options?: RequestOptions): Promise<Profile> =>
      this.request<Profile>('GET', '/profile', options),

    /**
     * Edits presentation, contact details and addresses. `status`, the
     * settlement terms and `slug` are readable but not writable — the
     * lifecycle belongs to the marketplace operator.
     */
    update: (params: ProfileUpdateParams, options?: RequestOptions): Promise<Profile> =>
      this.request<Profile>('PATCH', '/profile', { ...options, body: params }),
  }

  /**
   * The seller's own tax registrations — the numbers the marketplace's
   * commission invoice is made out to. A collection, like a company's: a
   * business trading in several regimes holds a registration in each.
   */
  readonly taxIdentifiers = {
    list: (options?: RequestOptions): Promise<{ data: TaxIdentifier[] }> =>
      this.request<{ data: TaxIdentifier[] }>('GET', '/tax_identifiers', options),

    create: (
      params: SellerTaxIdentifierCreateParams,
      options?: RequestOptions,
    ): Promise<TaxIdentifier> =>
      this.request<TaxIdentifier>('POST', '/tax_identifiers', { ...options, body: params }),

    update: (
      id: string,
      params: SellerTaxIdentifierUpdateParams,
      options?: RequestOptions,
    ): Promise<TaxIdentifier> =>
      this.request<TaxIdentifier>('PATCH', `/tax_identifiers/${id}`, {
        ...options,
        body: params,
      }),

    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/tax_identifiers/${id}`, options),

    /**
     * Asks the registry whether the number is still registered. A verdict
     * answers "valid now", so a number verified last year may have lapsed.
     */
    validate: (id: string, options?: RequestOptions): Promise<TaxIdentifier> =>
      this.request<TaxIdentifier>('POST', `/tax_identifiers/${id}/validate`, options),
  }

  /** Who runs this seller. */
  readonly team = {
    list: (options?: RequestOptions): Promise<{ data: TeamMember[] }> =>
      this.request<{ data: TeamMember[] }>('GET', '/team', options),

    /**
     * Invites a colleague. They join when they accept; the seller's own
     * lifecycle is untouched, since hiring is not a transition.
     */
    invite: (params: TeamMemberCreateParams, options?: RequestOptions): Promise<Invitation> =>
      this.request<Invitation>('POST', '/team', { ...options, body: params }),

    /** Revokes a member's access. The last remaining member cannot be removed. */
    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/team/${id}`, options),
  }

  /**
   * Countries for the panel's address forms — public reference data, the same
   * list the storefront serves.
   */
  readonly countries = {
    list: (options?: RequestOptions): Promise<{ data: SellerCountry[] }> =>
      this.request<{ data: SellerCountry[] }>('GET', '/countries', options),
  }

  /**
   * What the marketplace asks of this seller before it will admit them.
   *
   * Singular: the checklist is always the acting seller's. Every answer is
   * computed server-side by the one evaluator the operator's view also uses,
   * so the panel and the operator cannot show different progress.
   */
  readonly onboarding = {
    get: (options?: RequestOptions): Promise<OnboardingResponse> =>
      this.request<OnboardingResponse>('GET', '/onboarding', options),

    /**
     * Says the seller is ready. Refused with the blocking requirements named
     * when something required is still outstanding.
     */
    submitForReview: (options?: RequestOptions): Promise<OnboardingResponse> =>
      this.request<OnboardingResponse>('POST', '/onboarding/submit_for_review', options),

    /**
     * A fresh link to wherever the marketplace's payout provider collects
     * what it needs before it will pay this seller.
     *
     * Asked for at the moment the seller acts, never rendered with the
     * checklist: these links are short-lived and single-use, so one made
     * while drawing a page is often dead before it is clicked. Answers
     * `{ url: null }` when the provider hosts no onboarding — a marketplace
     * paying by hand collects those details itself.
     */
    payoutAccount: (
      data: OnboardingPayoutAccountParams,
      options?: RequestOptions,
    ): Promise<PayoutAccountLink> =>
      this.request<PayoutAccountLink>('POST', '/onboarding/payout_account', {
        ...options,
        body: data,
      }),
  }

  /**
   * What the seller submits about one requirement: an attestation they tick,
   * a document they upload, a reference they paste.
   *
   * Create only — a submission records what was said and when, so the seller
   * submits again rather than editing, and the latest one counts.
   */
  readonly requirementSubmissions = {
    create: (
      requirementId: string,
      params: RequirementSubmissionParams,
      options?: RequestOptions,
    ): Promise<RequirementSubmission> =>
      this.request<RequirementSubmission>('POST', `/requirements/${requirementId}/submissions`, {
        ...options,
        body: params,
      }),
  }

  /**
   * Offers nobody has accepted yet.
   *
   * Sending one lives on `team` — that is hiring — while chasing or
   * withdrawing one is bookkeeping on the offer itself.
   */
  readonly invitations = {
    /** Pending only; an accepted invitation is a team member. */
    list: (options?: RequestOptions): Promise<{ data: Invitation[] }> =>
      this.request<{ data: Invitation[] }>('GET', '/invitations', options),

    /** Sends the email again, for a colleague who never got the first one. */
    resend: (id: string, options?: RequestOptions): Promise<Invitation> =>
      this.request<Invitation>('PATCH', `/invitations/${id}/resend`, options),

    /** Withdraws an offer that has not been accepted. */
    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/invitations/${id}`, options),

    /** The link a colleague opens to join; it carries the invitation's token. */
    acceptanceLink: (id: string, options?: RequestOptions): Promise<InvitationAcceptanceLink> =>
      this.request<InvitationAcceptanceLink>('GET', `/invitations/${id}/acceptance_link`, options),
  }

  /**
   * The seller's own catalog — products they own outright. Every call is
   * rooted in the seller server-side, so an id belonging to another seller
   * is a 404. Variants listed against shared master-catalog products are a
   * separate surface.
   */
  readonly products = {
    list: (
      params?: ListParams<ProductFilters, ProductSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Product>> =>
      this.request<PaginatedResponse<Product>>('GET', '/products', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    /**
     * @param expand associations to include — the product form asks for
     *   nested variant prices and stock levels (e.g.
     *   `variants.prices,variants.stock_levels`) alongside
     *   `variants,media,default_variant,submission`.
     */
    get: (id: string, expand?: string, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('GET', `/products/${id}`, {
        ...options,
        params: expand ? { expand } : undefined,
      }),

    create: (params: ProductCreateParams, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('POST', '/products', { ...options, body: params }),

    update: (id: string, params: ProductUpdateParams, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('PATCH', `/products/${id}`, { ...options, body: params }),

    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/products/${id}`, options),

    /**
     * Ask the marketplace to put this product on sale.
     *
     * Status is not an attribute a seller can send: whether a listing goes
     * live is the operator's decision, so it moves through these actions.
     */
    submit: (id: string, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('PATCH', `/products/${id}/submit`, options),

    /** Take a listing back down. Withdrawing your own needs nobody's approval. */
    draft: (id: string, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('PATCH', `/products/${id}/draft`, options),

    archive: (id: string, options?: RequestOptions): Promise<Product> =>
      this.request<Product>('PATCH', `/products/${id}/archive`, options),

    /**
     * Submit a selection for review.
     *
     * Only a draft or a rejected listing can be submitted, so a mixed
     * selection moves what it can: `product_count` is what was submitted and
     * `skipped_count` — present only when something was skipped — is what was
     * already on sale, already in review, or archived.
     */
    bulkSubmit: (
      params: ProductBulkSubmitParams,
      options?: RequestOptions,
    ): Promise<BulkProductResult> =>
      this.request('POST', '/products/bulk_submit', { ...options, body: params }),

    /**
     * Move a selection to `draft` or `archived`.
     *
     * There is no bulk route onto `active`: a listing goes on sale when the
     * marketplace approves it, one at a time.
     */
    bulkStatusUpdate: (
      params: ProductBulkStatusParams,
      options?: RequestOptions,
    ): Promise<BulkProductResult> =>
      this.request('POST', '/products/bulk_status_update', { ...options, body: params }),

    /** Delete a selection. Ids outside this seller's catalog are ignored. */
    bulkDestroy: (
      params: ProductBulkDestroyParams,
      options?: RequestOptions,
    ): Promise<BulkProductResult> =>
      this.request('DELETE', '/products/bulk_destroy', { ...options, body: params }),

    /**
     * The downloadable files on one of this seller's products. Upload a file
     * with `files.upload(file, { visibility: 'private' })` first and send its
     * `signed_id`.
     */
    digitalAssets: {
      list: (
        productId: string,
        params?: ListParams<DigitalAssetFilters, DigitalAssetSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<DigitalAsset>> =>
        this.request<PaginatedResponse<DigitalAsset>>(
          'GET',
          `/products/${productId}/digital_assets`,
          {
            ...options,
            params: params ? transformListParams(params) : undefined,
          },
        ),

      get: (productId: string, id: string, options?: RequestOptions): Promise<DigitalAsset> =>
        this.request<DigitalAsset>('GET', `/products/${productId}/digital_assets/${id}`, options),

      create: (
        productId: string,
        params: DigitalAssetCreateParams,
        options?: RequestOptions,
      ): Promise<DigitalAsset> =>
        this.request<DigitalAsset>('POST', `/products/${productId}/digital_assets`, {
          ...options,
          body: params,
        }),

      update: (
        productId: string,
        id: string,
        params: DigitalAssetUpdateParams,
        options?: RequestOptions,
      ): Promise<DigitalAsset> =>
        this.request<DigitalAsset>('PATCH', `/products/${productId}/digital_assets/${id}`, {
          ...options,
          body: params,
        }),

      delete: (productId: string, id: string, options?: RequestOptions): Promise<void> =>
        this.request<void>('DELETE', `/products/${productId}/digital_assets/${id}`, options),
    },
  }

  /**
   * What this seller has sold. A basket spanning several sellers is split
   * into one order each, so these are the seller's own orders rather than a
   * filtered view of somebody else's.
   */
  readonly orders = {
    list: (
      params?: ListParams<OrderFilters, OrderSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Order>> =>
      this.request<PaginatedResponse<Order>>('GET', '/orders', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    /**
     * One of this seller's orders.
     *
     * Takes `(id, params, options)` like every other expandable `get` in the
     * Spree SDKs, so the second argument is the query rather than request
     * options — pass `undefined` for it when only options are wanted.
     *
     * @param params `expand: ['payment_splits']` adds this order's share of
     *   the payment the buyer made for the whole basket. A basket placed with
     *   one seller only does not split and has no shares.
     */
    get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Order> =>
      this.request<Order>('GET', `/orders/${id}`, {
        ...options,
        params: params?.expand?.length ? { expand: params.expand.join(',') } : undefined,
      }),

    /**
     * Withdraws from an order this seller cannot fulfil.
     *
     * `refund_payments` hands back what the buyer paid for these goods — a
     * seller is merchant of record for their own child order, and on a split
     * checkout only that order's share is settled. There is no
     * `refund_amount`: withdrawing from the whole order returns what that
     * order was paid, and a partial figure is a return.
     */
    cancel: (id: string, params?: OrderCancelParams, options?: RequestOptions): Promise<Order> =>
      this.request<Order>('PATCH', `/orders/${id}/cancel`, { ...options, body: params }),

    /**
     * Corrects where the goods go or who the invoice names.
     *
     * Send only the lines that change: the rest of the address is carried
     * over. Nothing else about the order is writable here.
     */
    address: (
      id: string,
      params: OrderAddressCorrectionParams,
      options?: RequestOptions,
    ): Promise<Order> =>
      this.request<Order>('PATCH', `/orders/${id}/address`, { ...options, body: params }),

    /**
     * The notes on an order: the instructions the buyer left, and the
     * seller's own working note.
     *
     * A marketplace basket splits into one order per seller, so the internal
     * note here is the seller's alone.
     */
    notes: {
      get: (orderId: string, options?: RequestOptions): Promise<Order> =>
        this.request<Order>('GET', `/orders/${orderId}/notes`, options),

      /**
       * Send only the note that changes: an absent key leaves the other
       * alone, while an empty string clears it. `internal_note` takes HTML
       * and is sanitized on save — `internal_note_html` reads it back.
       */
      update: (
        orderId: string,
        params: OrderNotesParams,
        options?: RequestOptions,
      ): Promise<Order> =>
        this.request<Order>('PATCH', `/orders/${orderId}/notes`, { ...options, body: params }),
    },

    /** The parcels owed on one order. */
    fulfillments: {
      list: (orderId: string, options?: RequestOptions): Promise<{ data: Fulfillment[] }> =>
        this.request<{ data: Fulfillment[] }>('GET', `/orders/${orderId}/fulfillments`, options),

      get: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
        this.request<Fulfillment>('GET', `/orders/${orderId}/fulfillments/${id}`, options),

      /**
       * Ships the parcel. `items` narrows it to part of what the fulfillment
       * holds, which splits the rest onto a new one.
       */
      fulfill: (
        orderId: string,
        id: string,
        params?: FulfillmentFulfillParams,
        options?: RequestOptions,
      ): Promise<Fulfillment> =>
        this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/fulfill`, {
          ...options,
          body: params,
        }),

      /**
       * The tracking pair, where the parcel ships from, and which quoted
       * service carries it.
       */
      update: (
        orderId: string,
        id: string,
        params: FulfillmentUpdateParams,
        options?: RequestOptions,
      ): Promise<Fulfillment> =>
        this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}`, {
          ...options,
          body: params,
        }),

      /** A parcel this seller is not going to send after all. */
      cancel: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
        this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/cancel`, options),

      /**
       * Moves part of what this parcel holds onto one of its own, for goods
       * leaving separately. Answers with every fulfillment on the order, since
       * splitting rewrites more than one.
       */
      split: (
        orderId: string,
        id: string,
        params: FulfillmentSplitParams,
        options?: RequestOptions,
      ): Promise<{ data: Fulfillment[] }> =>
        this.request<{ data: Fulfillment[] }>(
          'PATCH',
          `/orders/${orderId}/fulfillments/${id}/split`,
          { ...options, body: params },
        ),

      /**
       * The tracked consignments of one of the seller's parcels. A seller
       * ships on manual methods, so tracking numbers are entered here by hand.
       */
      deliveries: {
        list: (
          orderId: string,
          fulfillmentId: string,
          options?: RequestOptions,
        ): Promise<{ data: Delivery[] }> =>
          this.request<{ data: Delivery[] }>(
            'GET',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/deliveries`,
            options,
          ),

        get: (
          orderId: string,
          fulfillmentId: string,
          id: string,
          options?: RequestOptions,
        ): Promise<Delivery> =>
          this.request<Delivery>(
            'GET',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/deliveries/${id}`,
            options,
          ),

        create: (
          orderId: string,
          fulfillmentId: string,
          params: DeliveryCreateParams,
          options?: RequestOptions,
        ): Promise<Delivery> =>
          this.request<Delivery>(
            'POST',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/deliveries`,
            { ...options, body: params },
          ),

        update: (
          orderId: string,
          fulfillmentId: string,
          id: string,
          params: DeliveryUpdateParams,
          options?: RequestOptions,
        ): Promise<Delivery> =>
          this.request<Delivery>(
            'PATCH',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/deliveries/${id}`,
            { ...options, body: params },
          ),

        delete: (
          orderId: string,
          fulfillmentId: string,
          id: string,
          options?: RequestOptions,
        ): Promise<void> =>
          this.request<void>(
            'DELETE',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/deliveries/${id}`,
            options,
          ),
      },

      /**
       * Labels on the seller's own parcels. Sellers upload postage they bought
       * elsewhere and print it back; buying and refunding need the operator's
       * carrier account, so neither is offered here.
       *
       * Upload the file with `files.upload()` and pass the returned
       * `signed_id` as `file_signed_id`.
       */
      labels: {
        list: (
          orderId: string,
          fulfillmentId: string,
          options?: RequestOptions,
        ): Promise<{ data: ShippingLabel[] }> =>
          this.request<{ data: ShippingLabel[] }>(
            'GET',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/labels`,
            options,
          ),

        get: (
          orderId: string,
          fulfillmentId: string,
          id: string,
          options?: RequestOptions,
        ): Promise<ShippingLabel> =>
          this.request<ShippingLabel>(
            'GET',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/labels/${id}`,
            options,
          ),

        create: (
          orderId: string,
          fulfillmentId: string,
          params: ShippingLabelCreateParams,
          options?: RequestOptions,
        ): Promise<ShippingLabel> =>
          this.request<ShippingLabel>(
            'POST',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/labels`,
            { ...options, body: params },
          ),

        delete: (
          orderId: string,
          fulfillmentId: string,
          id: string,
          options?: RequestOptions,
        ): Promise<void> =>
          this.request<void>(
            'DELETE',
            `/orders/${orderId}/fulfillments/${fulfillmentId}/labels/${id}`,
            options,
          ),
      },
    },

    /**
     * Goods coming back. The seller is merchant of record for their own
     * child order, so approving, receiving and refunding are all theirs.
     */
    returns: {
      list: (orderId: string, options?: RequestOptions): Promise<{ data: Return[] }> =>
        this.request<{ data: Return[] }>('GET', `/orders/${orderId}/returns`, {
          ...options,
          // The nested collections are expand-gated server-side, so a bare
          // list answers with the record and none of its contents.
          params: { expand: 'return_line_items,return_line_items.variant,reason' },
        }),

      get: (orderId: string, id: string, options?: RequestOptions): Promise<Return> =>
        this.request<Return>('GET', `/orders/${orderId}/returns/${id}`, {
          ...options,
          params: { expand: 'return_line_items,return_line_items.variant,reason' },
        }),

      create: (
        orderId: string,
        params: ReturnCreateParams,
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('POST', `/orders/${orderId}/returns`, { ...options, body: params }),

      approve: (orderId: string, id: string, options?: RequestOptions): Promise<Return> =>
        this.request<Return>('PATCH', `/orders/${orderId}/returns/${id}/approve`, options),

      /** `items` carries what actually arrived; omit it to receive it all. */
      receive: (
        orderId: string,
        id: string,
        params?: ReturnReceiveParams,
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('PATCH', `/orders/${orderId}/returns/${id}/receive`, {
          ...options,
          body: params,
        }),

      /** Bounded by the return, and by this order's share of a split payment. */
      refund: (
        orderId: string,
        id: string,
        params?: ReturnRefundParams,
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('PATCH', `/orders/${orderId}/returns/${id}/refund`, {
          ...options,
          body: params,
        }),

      cancel: (
        orderId: string,
        id: string,
        params?: ReturnCancelParams,
        options?: RequestOptions,
      ): Promise<Return> =>
        this.request<Return>('PATCH', `/orders/${orderId}/returns/${id}/cancel`, {
          ...options,
          body: params,
        }),
    },

    /** Goods swapped for different ones. */
    exchanges: {
      list: (orderId: string, options?: RequestOptions): Promise<{ data: Exchange[] }> =>
        this.request<{ data: Exchange[] }>('GET', `/orders/${orderId}/exchanges`, {
          ...options,
          // The nested collections are expand-gated server-side, so a bare
          // list answers with the record and none of its contents.
          params: {
            expand:
              'exchange_line_items,exchange_line_items.original_variant,exchange_line_items.new_variant,reason',
          },
        }),

      get: (orderId: string, id: string, options?: RequestOptions): Promise<Exchange> =>
        this.request<Exchange>('GET', `/orders/${orderId}/exchanges/${id}`, {
          ...options,
          params: {
            expand:
              'exchange_line_items,exchange_line_items.original_variant,exchange_line_items.new_variant,reason',
          },
        }),

      create: (
        orderId: string,
        params: ExchangeCreateParams,
        options?: RequestOptions,
      ): Promise<Exchange> =>
        this.request<Exchange>('POST', `/orders/${orderId}/exchanges`, {
          ...options,
          body: params,
        }),

      approve: (orderId: string, id: string, options?: RequestOptions): Promise<Exchange> =>
        this.request<Exchange>('PATCH', `/orders/${orderId}/exchanges/${id}/approve`, options),

      receive: (
        orderId: string,
        id: string,
        params?: ExchangeReceiveParams,
        options?: RequestOptions,
      ): Promise<Exchange> =>
        this.request<Exchange>('PATCH', `/orders/${orderId}/exchanges/${id}/receive`, {
          ...options,
          body: params,
        }),

      /** Sends the replacement, settling any price difference. */
      fulfill: (
        orderId: string,
        id: string,
        params?: ExchangeFulfillParams,
        options?: RequestOptions,
      ): Promise<Exchange> =>
        this.request<Exchange>('PATCH', `/orders/${orderId}/exchanges/${id}/fulfill`, {
          ...options,
          body: params,
        }),

      cancel: (
        orderId: string,
        id: string,
        params?: ExchangeCancelParams,
        options?: RequestOptions,
      ): Promise<Exchange> =>
        this.request<Exchange>('PATCH', `/orders/${orderId}/exchanges/${id}/cancel`, {
          ...options,
          body: params,
        }),
    },

    /**
     * Something went wrong with a delivery, put right without necessarily
     * asking for the goods back.
     */
    claims: {
      list: (orderId: string, options?: RequestOptions): Promise<{ data: Claim[] }> =>
        this.request<{ data: Claim[] }>('GET', `/orders/${orderId}/claims`, {
          ...options,
          // The nested collections are expand-gated server-side, so a bare
          // list answers with the record and none of its contents.
          params: { expand: 'claim_line_items,claim_line_items.variant,reason' },
        }),

      get: (orderId: string, id: string, options?: RequestOptions): Promise<Claim> =>
        this.request<Claim>('GET', `/orders/${orderId}/claims/${id}`, {
          ...options,
          params: { expand: 'claim_line_items,claim_line_items.variant,reason' },
        }),

      create: (
        orderId: string,
        params: ClaimCreateParams,
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('POST', `/orders/${orderId}/claims`, { ...options, body: params }),

      approve: (orderId: string, id: string, options?: RequestOptions): Promise<Claim> =>
        this.request<Claim>('PATCH', `/orders/${orderId}/claims/${id}/approve`, options),

      /** Money back, a replacement shipment, or both. */
      resolve: (
        orderId: string,
        id: string,
        params: ClaimResolveParams,
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('PATCH', `/orders/${orderId}/claims/${id}/resolve`, {
          ...options,
          body: params,
        }),

      deny: (
        orderId: string,
        id: string,
        params?: ClaimDenyParams,
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('PATCH', `/orders/${orderId}/claims/${id}/deny`, {
          ...options,
          body: params,
        }),

      cancel: (
        orderId: string,
        id: string,
        params?: ClaimCancelParams,
        options?: RequestOptions,
      ): Promise<Claim> =>
        this.request<Claim>('PATCH', `/orders/${orderId}/claims/${id}/cancel`, {
          ...options,
          body: params,
        }),
    },
  }

  /**
   * The marketplace's own vocabularies, and the carrier registry. Read-only:
   * a seller picks from these, the operator decides what is in them.
   */
  readonly returnReasons = {
    list: (options?: RequestOptions): Promise<{ data: Reason[] }> =>
      this.request<{ data: Reason[] }>('GET', '/return_reasons', options),
  }

  readonly claimReasons = {
    list: (options?: RequestOptions): Promise<{ data: Reason[] }> =>
      this.request<{ data: Reason[] }>('GET', '/claim_reasons', options),
  }

  readonly orderCancellationReasons = {
    list: (options?: RequestOptions): Promise<{ data: Reason[] }> =>
      this.request<{ data: Reason[] }>('GET', '/order_cancellation_reasons', options),
  }

  readonly trackingCarriers = {
    list: (options?: RequestOptions): Promise<{ data: Array<{ id: string; name: string }> }> =>
      this.request<{ data: Array<{ id: string; name: string }> }>(
        'GET',
        '/tracking_carriers',
        options,
      ),
  }

  /**
   * Uploading the files a profile, a requirement submission or an import
   * uses. Each upload returns a `signed_id`: pass it unchanged as the
   * submission's `file_signed_id`, the profile's `logo_signed_id`, and so on,
   * within a day, after which it expires.
   */
  readonly files = {
    /**
     * Creates an upload. JSON metadata returns `upload`, the storage target to
     * send the bytes to; a `FormData` body with a `file` part stores the bytes
     * directly and returns `upload: null`. `upload()` does both steps for you.
     */
    create: (
      params: FileUploadCreateParams | FormData,
      options?: RequestOptions,
    ): Promise<FileUpload> =>
      this.request<FileUpload>('POST', '/files', { ...options, body: params }),

    /** Uploads a file and resolves to the response, whose `signed_id` the endpoint using the file takes. */
    upload: (
      file: Blob,
      options: UploadFileOptions = {},
      requestOptions?: RequestOptions,
    ): Promise<FileUpload> =>
      uploadFile((body) => this.files.create(body, requestOptions), file, options),
  }

  /**
   * CSV of this seller's own records — what they sold, or their catalogue.
   *
   * Created, polled until `done`, then downloaded. There is no list: a seller
   * has no export history page, and no delete: how long a file is kept is the
   * marketplace's business.
   *
   * Scoped server-side to the acting seller, so an export can only ever
   * contain their own rows however the request is filtered.
   */
  readonly exports = {
    create: (params: SellerExportCreateParams, options?: RequestOptions): Promise<Export> =>
      this.request<Export>('POST', '/exports', { ...options, body: params }),

    get: (id: string, options?: RequestOptions): Promise<Export> =>
      this.request<Export>('GET', `/exports/${id}`, options),
  }

  /**
   * The types a seller may list a product against. Read only — defining a
   * type is the operator's. A seller picks one because it is the template
   * that hands their product its option types and delivery profile.
   */
  readonly productTypes = {
    list: (
      params?: ListParams<ProductTypeFilters, ProductTypeSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<ProductType>> =>
      this.request<PaginatedResponse<ProductType>>('GET', '/product_types', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<ProductType> =>
      this.request<ProductType>('GET', `/product_types/${id}`, options),
  }

  /**
   * The marketplace's delivery profiles — what kind of goods a product is
   * (parcel, digital, pallet). Read only: a seller assigns one to their
   * product and never defines one.
   */
  readonly deliveryProfiles = {
    list: (
      params?: ListParams<DeliveryProfileFilters, DeliveryProfileSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<DeliveryProfile>> =>
      this.request<PaginatedResponse<DeliveryProfile>>('GET', '/delivery_profiles', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),
  }

  /**
   * The marketplace's delivery zones — where its methods may ship to.
   *
   * Read only, like profiles. Pass `delivery_profile_id` to list only the
   * zones under one profile, which is what the method form's picker asks for.
   */
  readonly deliveryZones = {
    list: (
      params?: DeliveryZoneListParams,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<DeliveryZone>> => {
      // `delivery_profile_id` is sent alongside the Ransack query rather than
      // through it: the endpoint reads it as a plain parameter, and
      // `transformListParams` would wrap it into `q[...]` where the filter is
      // silently ignored — leaving the picker offering every zone in the store.
      const { delivery_profile_id: deliveryProfileId, ...listParams } = params ?? {}

      return this.request<PaginatedResponse<DeliveryZone>>('GET', '/delivery_zones', {
        ...options,
        params: {
          ...transformListParams(listParams),
          ...(deliveryProfileId ? { delivery_profile_id: deliveryProfileId } : {}),
        },
      })
    },
  }

  /**
   * How this seller ships.
   *
   * `list()` carries the seller's own methods alongside the marketplace ones
   * the operator shares with sellers; a shared row comes back with
   * `editable: false` and every write against it is a 404.
   *
   * Neither the rate provider nor the fulfillment provider is settable — a
   * seller prices their own rates and enters tracking numbers by hand,
   * because carrier accounts belong to the marketplace.
   */
  readonly deliveryMethods = {
    list: (
      params?: ListParams<DeliveryMethodFilters, DeliveryMethodSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<DeliveryMethod>> =>
      this.request<PaginatedResponse<DeliveryMethod>>('GET', '/delivery_methods', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<DeliveryMethod> =>
      this.request<DeliveryMethod>('GET', `/delivery_methods/${id}`, options),

    create: (
      params: DeliveryMethodCreateParams,
      options?: RequestOptions,
    ): Promise<DeliveryMethod> =>
      this.request<DeliveryMethod>('POST', '/delivery_methods', { ...options, body: params }),

    update: (
      id: string,
      params: DeliveryMethodUpdateParams,
      options?: RequestOptions,
    ): Promise<DeliveryMethod> =>
      this.request<DeliveryMethod>('PATCH', `/delivery_methods/${id}`, {
        ...options,
        body: params,
      }),

    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/delivery_methods/${id}`, options),

    /** The ways a method can be priced, with each one's preference schema. */
    calculators: (options?: RequestOptions): Promise<{ data: DeliveryCalculatorType[] }> =>
      this.request<{ data: DeliveryCalculatorType[] }>(
        'GET',
        '/delivery_methods/calculators',
        options,
      ),

    /** The conditions a seller may put on their own method. */
    ruleTypes: (options?: RequestOptions): Promise<{ data: DeliveryMethodRuleType[] }> =>
      this.request<{ data: DeliveryMethodRuleType[] }>(
        'GET',
        '/delivery_methods/rule_types',
        options,
      ),
  }

  /**
   * Where this seller keeps stock, and so where their returns are sent.
   *
   * No delete: a location holds stock levels and is named on historical
   * fulfillments, so a seller retires one by setting `active` to false.
   */
  readonly stockLocations = {
    list: (
      params?: ListParams<StockLocationFilters, StockLocationSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<StockLocation>> =>
      this.request<PaginatedResponse<StockLocation>>('GET', '/stock_locations', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<StockLocation> =>
      this.request<StockLocation>('GET', `/stock_locations/${id}`, options),

    create: (params: StockLocationCreateParams, options?: RequestOptions): Promise<StockLocation> =>
      this.request<StockLocation>('POST', '/stock_locations', { ...options, body: params }),

    update: (
      id: string,
      params: StockLocationUpdateParams,
      options?: RequestOptions,
    ): Promise<StockLocation> =>
      this.request<StockLocation>('PATCH', `/stock_locations/${id}`, {
        ...options,
        body: params,
      }),
  }

  /**
   * What this seller packs their goods into: the boxes their parcels ship in,
   * the cartons their products are packed into, the pallets a wholesale order
   * leaves on.
   *
   * The listing carries the marketplace's own packaging alongside the
   * seller's, so a seller can pack into the operator's standard cartons
   * rather than re-measuring them. Those rows report `editable: false` and
   * are refused by every write.
   */
  readonly packageTypes = {
    list: (
      params?: ListParams<PackageTypeFilters, PackageTypeSort> & { owner?: 'mine' },
      options?: RequestOptions,
    ): Promise<PaginatedResponse<PackageType>> => {
      // `owner` is a plain query param the controller reads directly, so it
      // is lifted out before the Ransack transform, which would otherwise
      // send it as `q[owner]` and the filter would silently do nothing.
      const { owner, ...listParams } = params ?? {}

      return this.request<PaginatedResponse<PackageType>>('GET', '/package_types', {
        ...options,
        params: {
          ...(params ? transformListParams(listParams) : {}),
          ...(owner ? { owner } : {}),
        },
      })
    },

    get: (id: string, options?: RequestOptions): Promise<PackageType> =>
      this.request<PackageType>('GET', `/package_types/${id}`, options),

    create: (params: PackageTypeCreateParams, options?: RequestOptions): Promise<PackageType> =>
      this.request<PackageType>('POST', '/package_types', { ...options, body: params }),

    update: (
      id: string,
      params: PackageTypeUpdateParams,
      options?: RequestOptions,
    ): Promise<PackageType> =>
      this.request<PackageType>('PATCH', `/package_types/${id}`, {
        ...options,
        body: params,
      }),

    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/package_types/${id}`, options),
  }

  /**
   * Where this seller stands with the marketplace, one row per currency:
   * earned, paid, still owed, and earnings the payout provider has not yet
   * confirmed. Computed from the ledger, so the rows carry no id.
   */
  readonly balances = {
    list: (options?: RequestOptions): Promise<{ data: Balance[] }> =>
      this.request<{ data: Balance[] }>('GET', '/balances', options),
  }

  /**
   * What this seller has earned, order by order — the sale less the
   * marketplace's commission, credited when the goods went out.
   *
   * Read-only: a refund writes a negative reversal row rather than editing
   * the earning. Filter with `q[order_id_eq]` or `q[payout_id_eq]`.
   */
  readonly transfers = {
    list: (
      params?: ListParams<SellerTransferFilters, SellerTransferSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Transfer>> =>
      this.request<PaginatedResponse<Transfer>>('GET', '/transfers', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<Transfer> =>
      this.request<Transfer>('GET', `/transfers/${id}`, options),
  }

  /**
   * Settlements to this seller, each batching the earnings that accumulated
   * since the last one. Created by the marketplace's sweep and confirmed by
   * the payout provider or the operator, so read-only here.
   */
  readonly payouts = {
    list: (
      params?: ListParams<SellerPayoutFilters, SellerPayoutSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Payout>> =>
      this.request<PaginatedResponse<Payout>>('GET', '/payouts', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<Payout> =>
      this.request<Payout>('GET', `/payouts/${id}`, options),
  }

  /**
   * This seller's own policy documents — their returns policy, shipping
   * policy, whatever the marketplace asks them to publish.
   *
   * Addressable by slug as well as prefixed id, matching the storefront.
   */
  readonly policies = {
    list: (
      params?: ListParams<PolicyFilters, PolicySort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Policy>> =>
      this.request<PaginatedResponse<Policy>>('GET', '/policies', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (idOrSlug: string, options?: RequestOptions): Promise<Policy> =>
      this.request<Policy>('GET', `/policies/${idOrSlug}`, options),

    create: (params: PolicyCreateParams, options?: RequestOptions): Promise<Policy> =>
      this.request<Policy>('POST', '/policies', { ...options, body: params }),

    update: (
      idOrSlug: string,
      params: PolicyUpdateParams,
      options?: RequestOptions,
    ): Promise<Policy> =>
      this.request<Policy>('PATCH', `/policies/${idOrSlug}`, { ...options, body: params }),

    delete: (idOrSlug: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/policies/${idOrSlug}`, options),
  }

  /**
   * Bulk-listing this seller's catalog from a CSV.
   *
   * The flow is the operator's: upload the file with `files.upload()`,
   * `create()` the import from the returned `signed_id`, and the response
   * comes back in the `mapping` state carrying `schema_fields`, `csv_headers`,
   * a `sample_row` and the auto-assigned `mappings`. Adjust those and call
   * `completeMapping(id)` to start processing, then poll `get(id)` while
   * `status` is `completed_mapping`/`processing` (`completed`/`failed` are
   * terminal). Failed rows are listed via
   * `rows.list(id, { status_eq: 'failed' })` and re-run with
   * `retryFailedRows(id)`.
   *
   * Products only, and what an import creates is a draft: a seller reaches
   * `active` through review, never by uploading.
   */
  readonly imports = {
    list: (
      params?: ListParams<ImportFilters, ImportSort>,
      options?: RequestOptions,
    ): Promise<PaginatedResponse<Import>> =>
      this.request<PaginatedResponse<Import>>('GET', '/imports', {
        ...options,
        params: params ? transformListParams(params) : undefined,
      }),

    get: (id: string, options?: RequestOptions): Promise<Import> =>
      this.request<Import>('GET', `/imports/${id}`, options),

    create: (params: ImportCreateParams, options?: RequestOptions): Promise<Import> =>
      this.request<Import>('POST', '/imports', { ...options, body: params }),

    completeMapping: (
      id: string,
      params?: ImportCompleteMappingParams,
      options?: RequestOptions,
    ): Promise<Import> =>
      this.request<Import>('PATCH', `/imports/${id}/complete_mapping`, {
        ...options,
        body: params ?? {},
      }),

    retryFailedRows: (id: string, options?: RequestOptions): Promise<Import> =>
      this.request<Import>('PATCH', `/imports/${id}/retry_failed_rows`, options),

    delete: (id: string, options?: RequestOptions): Promise<void> =>
      this.request<void>('DELETE', `/imports/${id}`, options),

    rows: {
      list: (
        importId: string,
        params?: ListParams<ImportRowFilters, ImportRowSort>,
        options?: RequestOptions,
      ): Promise<PaginatedResponse<ImportRow>> =>
        this.request<PaginatedResponse<ImportRow>>('GET', `/imports/${importId}/rows`, {
          ...options,
          params: params ? transformListParams(params) : undefined,
        }),
    },
  }
}

/**
 * API shorthand for an import type, not the Ruby class name.
 *
 * One member today: products are the only dataset a seller owns. Customers
 * belong to the marketplace, and translations of catalog copy are its
 * merchandising — the Seller API refuses both.
 */
export type SellerImportType = 'products'

export interface ImportMappingParam {
  /** Canonical schema field name (see `Import.schema_fields[].name`). */
  schema_field: string
  /** CSV header to read the field from; `null` unmaps the field. */
  file_column: string | null
}

/** What a seller may write on one of their stock locations. */
export interface DeliveryZoneListParams extends ListParams {
  /** Only zones under this delivery profile. */
  delivery_profile_id?: string
  [key: string]: unknown
}

/** One way a delivery method can be priced. */
export interface DeliveryCalculatorType {
  type: string
  name: string
  /** JSON Schema of the calculator's `preferences`. */
  schema: PreferenceSchema
}

/** One condition a seller may put on their own method. */
export interface DeliveryMethodRuleType {
  type: string
  name: string
  description: string
  /** JSON Schema of the rule's `preferences`. */
  schema: PreferenceSchema
}

/**
 * The datasets a seller may export.
 *
 * Deliberately narrower than the operator's list: only records that can be
 * narrowed to one seller are offered, since that narrowing is what keeps one
 * seller's file free of another's rows.
 */
export type SellerExportType = 'orders' | 'products'

/** A country as the address form needs it. Name it from `iso` with `Intl.DisplayNames`. */
export type SellerCountry = Country

/** Where to send a seller to set up how they get paid. */
export interface PayoutAccountLink {
  /** Null when the provider hosts no onboarding of its own. */
  url: string | null
}

/** What `/seller/onboarding` answers. */
export interface OnboardingResponse {
  /** The seller's lifecycle status, e.g. `onboarding`, `ready_for_review`. */
  status: string
  /**
   * Optional requirements included — this is how far along, not how close to
   * approval. Just the two counts: a percentage is arithmetic over them, and a
   * copy here would be a second definition of the same fact.
   */
  progress: { done: number; total: number }
  requirements: RequirementStatus[]
}

/** The fields a seller may set on their own product. */
/**
 * What a bulk product action did. `skipped_count` is present only when the
 * action left something alone — a key on every response would tell a caller
 * that never skips anything that nothing was skipped.
 */
export interface BulkProductResult {
  product_count: number
  skipped_count?: number
}

/** What `/seller/me` answers. */
/**
 * One CanCanCan rule, in the shape the panels' `<Can>` reads. Identical to
 * the Admin API's, on purpose: the framework's permission model is one
 * implementation, so its input has to be too.
 */
export interface PermissionRule {
  /** true for `can`, false for `cannot` */
  allow: boolean
  /** Action names, e.g. ["read", "update"] or ["manage"] */
  actions: string[]
  /** Subject short names, e.g. ["product"] or ["all"] */
  subjects: string[]
  /** The rule carries per-record conditions the API will still enforce. */
  has_conditions: boolean
}

export interface MeResponse {
  /**
   * `Account` rather than `TeamMember`: reading your own record also shows
   * the panel language you chose, which the team list does not publish about
   * a colleague.
   */
  user: Account
  sellers: SellerSummary[]
  /**
   * The marketplace's own settings that shape what the panel lets a seller
   * do — whether sellers may upload digital files, and of which types.
   */
  store: Store
  /** Empty until a seller is named — capability is per seller. */
  permissions: PermissionRule[]
  permission_keys: string[]
}

/**
 * `client.me`: an object with `get` and `update`, which is also callable as
 * `client.me()` — the 1.0.0-beta.1/beta.2 form — for backwards compatibility.
 */
export interface MeResource {
  /** @deprecated Use `me.get()` instead. Calling `me()` directly will be removed in a future release. */
  (options?: RequestOptions): Promise<MeResponse>
  /** Reads the signed-in person, the sellers they may act for, and their permissions. */
  get(options?: RequestOptions): Promise<MeResponse>
  /**
   * Edits the signed-in person's own account — the name and photo their
   * team sees, and the panel's language. Not the seller business they act
   * for: that is `profile.update`.
   *
   * `avatar` takes a direct-upload signed id to set the photo, or `null` to
   * remove it; omitting it leaves the current one alone.
   */
  update(params: AccountUpdateParams, options?: RequestOptions): Promise<MeResponse>
}