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.

4.4 KB
Raw Blame
import type { StockLevel, StockLevelUpdateParams, StockLocation } from '@spree/admin-sdk'
import {
  adminClient,
  useResourceKey,
  useResourceKeyBuilder,
  useResourceMutation,
} from '@spree/dashboard-core'
import { type QueryKey, useQuery, useQueryClient } from '@tanstack/react-query'
import i18n from 'i18next'

interface UseStockLevelsParams {
  page?: number
  limit?: number
  stock_location_id_eq?: string
  variant_sku_or_variant_product_name_cont?: string
}

/** Preserve expanded associations when a PATCH response omits them. */
export function mergeStockLevelUpdate(previous: StockLevel, updated: StockLevel): StockLevel {
  return {
    ...previous,
    ...updated,
    variant: updated.variant ?? previous.variant,
    stock_location: updated.stock_location ?? previous.stock_location,
  }
}

export function useStockLevels(params: UseStockLevelsParams = {}) {
  return useQuery({
    queryKey: useResourceKey('stock-levels', params),
    queryFn: () =>
      adminClient.stockLevels.list({
        page: params.page ?? 1,
        limit: params.limit ?? 25,
        // The stock-at-location panel renders the variant's product name +
        // SKU per row, so expand the association into the response.
        // Without this, only `variant_id` comes back and the row falls
        // back to displaying the prefixed ID.
        expand: ['variant'],
        ...(params.stock_location_id_eq && {
          stock_location_id_eq: params.stock_location_id_eq,
        }),
        ...(params.variant_sku_or_variant_product_name_cont && {
          variant_sku_or_variant_product_name_cont: params.variant_sku_or_variant_product_name_cont,
        }),
      }),
    enabled: !!params.stock_location_id_eq,
  })
}

export function useUpdateStockLevel(id: string, extraInvalidate: QueryKey[] = []) {
  const queryClient = useQueryClient()
  const buildKey = useResourceKeyBuilder()

  return useResourceMutation<StockLevel, Error, StockLevelUpdateParams>({
    mutationFn: (params) => adminClient.stockLevels.update(id, params),
    // The list is patched rather than invalidated: correcting a count from
    // the Inventory page would otherwise refetch every row, and the edited
    // row would be replaced underneath the pointer. The response carries the
    // updated level, so the cached row is the same data the refetch would
    // have brought back.
    invalidate: [['stock-levels', id], ...extraInvalidate],
    successMessage: i18n.t('admin.stock_levels.messages.stock_updated'),
    errorMessage: i18n.t('admin.errors.failed_to_update'),
    showValidationErrors: true,
    onSuccess: (updated) => {
      queryClient.setQueriesData<{ data: StockLevel[] }>(
        { queryKey: buildKey('stock-levels') },
        (cached) => {
          if (!cached?.data) return cached
          const index = cached.data.findIndex((level) => level.id === updated.id)
          if (index === -1) return cached

          const data = [...cached.data]
          data[index] = mergeStockLevelUpdate(cached.data[index], updated)
          return { ...cached, data }
        },
      )
    },
  })
}

export function useDeleteStockLevel() {
  const queryClient = useQueryClient()
  const buildKey = useResourceKeyBuilder()

  return useResourceMutation<void, Error, string>({
    mutationFn: (id) => adminClient.stockLevels.delete(id),
    invalidate: [['stock-levels']],
    successMessage: i18n.t('admin.stock_levels.messages.stock_level_deleted'),
    errorMessage: i18n.t('admin.errors.failed_to_delete'),
    onSuccess: (_data, id) => {
      queryClient.removeQueries({ queryKey: buildKey('stock-levels', id) })
    },
  })
}

/** Location picker for the Inventory page's filter panel. */
export function stockLocationAutocompleteProps(queryKey: string) {
  return {
    queryKey,
    search: (query: string) =>
      adminClient.stockLocations.list({ search: query, limit: 100, sort: 'name' }),
    hydrate: (ids: string[]) => adminClient.stockLocations.list({ id_in: ids, limit: ids.length }),
    // Every warehouse, so the filter opens as a list rather than a search
    // box: a store has a handful, and the API caps the page at 100 anyway.
    listAll: () => adminClient.stockLocations.list({ limit: 100, sort: 'name' }),
    getOptionLabel: (location: StockLocation) => location.name ?? location.id,
    placeholder: i18n.t('admin.stock_levels.location_filter.placeholder'),
    emptyText: i18n.t('admin.stock_levels.location_filter.empty'),
  }
}