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.

9.8 KB
Raw Blame
import { i18n, runtimeListParams, setApiClient } from '@spree/dashboard-core'
import type { SellerApiClient, SellerExportCreateParams } from '@spree/seller-sdk'
import { createSellerClient } from '@spree/seller-sdk'

/**
 * Which seller the signed-in user is acting as.
 *
 * Kept out of React state because the client needs it on every request,
 * including ones fired before any component renders. The URL is the real
 * source of truth — the `$sellerId` route layout writes it here as it renders
 * — and this copy is only what the request headers read.
 */
const SELLER_STORAGE_KEY = 'spree.seller.id'

let client: SellerApiClient | null = null

/**
 * The seller the client is currently sending, mirrored here because the SDK
 * keeps it in a closure with no reader.
 *
 * Not the same thing as the stored choice: a browser that blocks storage
 * (private mode, sandboxed iframe) still runs the panel perfectly well, and
 * `rememberSeller` sets the client either way. Reading `localStorage` to
 * answer "who are we acting as" would come back empty in exactly those
 * sessions and drop the header off every file download.
 */
let activeSellerId: string | null = null

/**
 * Builds the Seller API client and registers it with the shared framework.
 *
 * The host calls this once at boot, before rendering. `@spree/dashboard-core`
 * is the framework behind both panels, so it cannot own either client — the
 * operator's dashboard registers an Admin API client the same way.
 *
 * Leave `baseUrl` unset for relative URLs, so the Vite dev proxy (or a
 * static-host rewrite in production) keeps the panel same-origin with the API
 * — which is what lets the seller refresh cookie ride under `SameSite=Lax`
 * without HTTPS. Set it only for a genuinely cross-origin deployment.
 */
export function createSellerApiClient({
  baseUrl = '',
}: {
  baseUrl?: string
} = {}): SellerApiClient {
  client = createSellerClient({ baseUrl })

  const remembered = rememberedSeller()
  if (remembered) setActiveSeller(remembered)

  setApiClient({
    auth: client.auth,
    setToken: (token: string) => sellerClient().setToken(token),
    onUnauthorized: (handler) => sellerClient().onUnauthorized(handler),
    // A stale seller header would ride into the next seller's first requests
    // and 403 them against a seller they may hold no role on.
    clearTenant: forgetSeller,
    fetchPermissions: async () => {
      const response = await sellerClient().me.get()

      // Both shapes, exactly as the operator's dashboard receives them. The
      // framework's `<Can>` reads CanCanCan rules; the key list is what the
      // API's own gate enforces. Dropping the rules here (an earlier version
      // did) left every `<Can>` on the panel answering false — silently.
      return { rules: response.permissions ?? [], keys: response.permission_keys ?? [] }
    },
    // The account menu's language switcher and the profile dialog both write
    // through this, so neither reaches for the Admin API from a panel holding
    // only a seller credential.
    updateAccount: (params) => sellerClient().me.update(params),
    // The shared address form reads countries through the registered client,
    // so it works in a panel that has no admin credential.
    listCountries: () => sellerClient().countries.list(),
    uploadFile: (file, options) => sellerClient().files.upload(file, options),
    // A file download is a bare fetch, so it does not go through the client
    // and picks up none of its headers. Without the seller header the Seller
    // API refuses the request before the action runs, so an export would
    // generate fine and then fail to download.
    downloadHeaders: (): Record<string, string> =>
      activeSellerId ? { 'X-Spree-Seller-Id': activeSellerId } : {},
    // Backs the shared export dialog, the same one the operator's dashboard
    // renders. The Seller API narrows what may be exported to records that
    // can be scoped to one seller, and refuses anything else.
    exports: {
      create: (params) => sellerClient().exports.create(params as SellerExportCreateParams),
      get: (id) => sellerClient().exports.get(id),
    },
    // Backs the shared CSV import wizard. Products only: customers belong to
    // the marketplace and translations of catalog copy are its merchandising,
    // so the Seller API refuses both and the wizard offers neither.
    imports: {
      list: (params) => sellerClient().imports.list(runtimeListParams(params)),
      get: (id) => sellerClient().imports.get(id),
      create: (params) =>
        sellerClient().imports.create({
          ...params,
          // Narrowed by the API too — this only keeps the SDK's own type
          // honest about what this branch accepts.
          type: params.type as 'products',
        }),
      completeMapping: (id, params) => sellerClient().imports.completeMapping(id, params),
      retryFailedRows: (id) => sellerClient().imports.retryFailedRows(id),
      delete: (id) => sellerClient().imports.delete(id),
      rows: {
        list: (importId, params) =>
          sellerClient().imports.rows.list(importId, runtimeListParams(params)),
      },
      types: ['products'],
      // This panel's product list is keyed `seller-products`, so core's
      // default `products` invalidation would miss it and the list would sit
      // on its pre-import cache.
      invalidateKeys: ['seller-products'],
      templateUrl: (type) => `/api/v3/seller/imports/template?type=${encodeURIComponent(type)}`,
      exampleUrl: (type) => `/api/v3/seller/imports/example?type=${encodeURIComponent(type)}`,
      downloadUrl: (id) => `/api/v3/seller/imports/${id}/download`,
    },
    // Backs the shared stock-locations page. No `delete`: a location holds
    // stock levels and is named on historical fulfillments, so the Seller API
    // does not offer it and the page hides the action accordingly.
    stockLocations: {
      list: (params) => sellerClient().stockLocations.list(runtimeListParams(params)),
      get: (id) => sellerClient().stockLocations.get(id),
      create: (params) => sellerClient().stockLocations.create(params),
      update: (id, params) => sellerClient().stockLocations.update(id, params),
    },
    // The marketplace's vocabulary the product form picks from: types and
    // delivery profiles only. Categories, collections and tags are filing,
    // which is the operator's at review, so they are not registered and the
    // shared Categorization card offers just these two
    // (docs/plans/6.0-multi-vendor-marketplace.md, Decision 13).
    productTypes: {
      list: (params) => sellerClient().productTypes.list(runtimeListParams(params)),
      get: (id) => sellerClient().productTypes.get(id),
    },
    deliveryProfiles: {
      list: (params) => sellerClient().deliveryProfiles.list(runtimeListParams(params)),
    },
    // What this seller packs into: their own boxes and cartons, plus the
    // marketplace's shared packaging, which the API lists read-only. Backs
    // both the packaging settings page and the variant editor's carton
    // picker (docs/plans/6.0-seller-package-types.md).
    packageTypes: {
      list: (params) => sellerClient().packageTypes.list(runtimeListParams(params)),
      get: (id) => sellerClient().packageTypes.get(id),
      create: (params) => sellerClient().packageTypes.create(params),
      update: (id, params) => sellerClient().packageTypes.update(id, params),
      delete: (id) => sellerClient().packageTypes.delete(id),
    },
    digitalAssets: {
      list: (productId, params) => sellerClient().products.digitalAssets.list(productId, params),
      // Sellers upload files only, so a file is the one thing a new asset must carry.
      create: (productId, { signed_id, ...params }) => {
        if (!signed_id) throw new Error(i18n.t('admin.errors.unexpected'))
        return sellerClient().products.digitalAssets.create(productId, { ...params, signed_id })
      },
      update: (productId, id, params) =>
        sellerClient().products.digitalAssets.update(productId, id, params),
      delete: (productId, id) => sellerClient().products.digitalAssets.delete(productId, id),
    },
  })

  return client
}

/**
 * The registered client.
 *
 * Throws rather than returning null: a panel rendering without one is
 * misconfigured, and every call would otherwise fail further away with a less
 * useful message.
 */
export function sellerClient(): SellerApiClient {
  if (!client) {
    throw new Error(
      '@spree/seller-dashboard: no API client created. Call createSellerApiClient() at boot, ' +
        'before rendering the panel.',
    )
  }

  return client
}

/** Points subsequent requests at a seller, without persisting the choice. */
export function setActiveSeller(sellerId: string): void {
  activeSellerId = sellerId
  sellerClient().setSeller(sellerId)
}

/**
 * Persists the choice so a reload does not drop the seller back to the picker.
 *
 * Every access is guarded: a browser that blocks storage (sandboxed iframe,
 * blocked third-party storage, some private modes) throws on `localStorage`,
 * and these run at boot and during logout — the two places a throw would
 * leave the panel unusable rather than merely forgetful. Losing the memory is
 * a small cost; failing to boot or to sign out is not.
 */
export function rememberSeller(sellerId: string): void {
  try {
    localStorage.setItem(SELLER_STORAGE_KEY, sellerId)
  } catch {
    // Storage unavailable — the choice lives for this page only.
  }
  setActiveSeller(sellerId)
}

export function forgetSeller(): void {
  try {
    localStorage.removeItem(SELLER_STORAGE_KEY)
  } catch {
    // Nothing to forget; clearing the header below is what matters for logout.
  }
  activeSellerId = null
  client?.setSeller('')
}

export function rememberedSeller(): string | null {
  try {
    return localStorage.getItem(SELLER_STORAGE_KEY)
  } catch {
    return null
  }
}