Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix(vendor): wait for seller regions before rendering the offer price grid (#1673)

Viktor Holikc27f9b1a511a
diff --git a/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx b/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
index b96dfa3fc..0b5f2aa05 100644
--- a/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
+++ b/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
@@ -1,5 +1,4 @@
import { HttpTypes } from "@medusajs/types"
-import { OfferDTO } from "@mercurjs/types"
import { Button, toast } from "@medusajs/ui"
import { useMemo } from "react"
import { useForm } from "react-hook-form"
@@ -18,65 +17,20 @@ import { KeyboundForm } from "../../../../components/utilities/keybound-form"
import { usePricePreferences } from "../../../../hooks/api/price-preferences"
import { useProduct, productsQueryKeys } from "../../../../hooks/api/products"
import { offerQueryKeys } from "../../../../hooks/api/offers"
-import { castNumber } from "../../../../lib/cast-number"
import { sdk } from "../../../../lib/client"
import { queryClient } from "../../../../lib/query-client"
import { OFFER_PRODUCT_DETAIL_FIELDS } from "../../common/constants"
-import { isBasePrice, isRegionPrice } from "../../common/region-prices"
import { useSellerCurrencies } from "../../common/use-seller-currencies"
-import { OfferPrice } from "../../common/types"
-
-type EditPriceRow = {
- offer_id: string
- variant_title: string
- product_thumbnail?: string | null
- prices: Record<string, number | string>
- region_prices: Record<string, number | string>
-}
-
-type Region = HttpTypes.AdminRegion
+import {
+ buildPricePayload,
+ buildRows,
+ EditPriceRow,
+ PriceProduct,
+ Region,
+} from "./utils"
type FormValues = { rows: EditPriceRow[] }
-type PriceProduct = HttpTypes.AdminProduct & {
- variants?: Array<
- HttpTypes.AdminProductVariant & { offers?: OfferDTO[] | null }
- > | null
-}
-
-const numericOrZero = (v: number | string | undefined | null): number =>
- v === "" || v === null || v === undefined ? 0 : castNumber(v) || 0
-
-const buildRows = (
- product: PriceProduct,
- currencies: string[],
- regions: Region[],
-): EditPriceRow[] =>
- (product.variants ?? []).flatMap((variant) =>
- (variant.offers ?? []).map((offer) => {
- const offerPrices = (offer.prices ?? []) as OfferPrice[]
- const prices: Record<string, number | ""> = {}
- for (const code of currencies) {
- const match = offerPrices.find(
- (p) => isBasePrice(p) && p.currency_code === code,
- )
- prices[code] = match?.amount ?? ""
- }
- const region_prices: Record<string, number | ""> = {}
- for (const region of regions) {
- const match = offerPrices.find((p) => isRegionPrice(p, region.id))
- region_prices[region.id] = match?.amount ?? ""
- }
- return {
- offer_id: offer.id,
- variant_title: variant.title ?? "",
- product_thumbnail: product.thumbnail ?? null,
- prices,
- region_prices,
- }
- }),
- )
-
const columnHelper = createDataGridHelper<EditPriceRow, FormValues>()
const useColumns = ({
@@ -136,13 +90,16 @@ const useColumns = ({
const EditPriceGrid = ({
product,
productId,
+ currencies,
+ regions,
}: {
product: PriceProduct
productId: string
+ currencies: string[]
+ regions: Region[]
}) => {
const { t } = useTranslation()
const { handleSuccess, setCloseOnEscape } = useRouteModal()
- const { currencies, regions } = useSellerCurrencies()
const canViewPricePreferences = useCan("price_preferences")
const { price_preferences: pricePreferences } = usePricePreferences(
{},
@@ -160,28 +117,12 @@ const EditPriceGrid = ({
const handleSubmit = form.handleSubmit(async (values) => {
try {
await Promise.all(
- values.rows.map((row) => {
- const prices: {
- amount: number
- currency_code: string
- rules?: Record<string, string>
- }[] = []
- for (const code of currencies) {
- const value = row.prices?.[code]
- if (value === "" || value === null || value === undefined) continue
- prices.push({ amount: numericOrZero(value), currency_code: code })
- }
- for (const region of regions) {
- const value = row.region_prices?.[region.id]
- if (value === "" || value === null || value === undefined) continue
- prices.push({
- amount: numericOrZero(value),
- currency_code: region.currency_code,
- rules: { region_id: region.id },
- })
- }
- return sdk.vendor.offers.$id.mutate({ $id: row.offer_id, prices })
- }),
+ values.rows.map((row) =>
+ sdk.vendor.offers.$id.mutate({
+ $id: row.offer_id,
+ prices: buildPricePayload(row, currencies, regions),
+ }),
+ ),
)
await queryClient.invalidateQueries({ queryKey: offerQueryKeys.lists() })
await queryClient.invalidateQueries({
@@ -237,10 +178,20 @@ export const OfferEditPricePage = () => {
const { product, isPending, isError, error } = useProduct(id!, {
fields: OFFER_PRODUCT_DETAIL_FIELDS,
})
+ const {
+ currencies,
+ regions,
+ isPending: isRegionsPending,
+ isError: isRegionsError,
+ error: regionsError,
+ } = useSellerCurrencies()
const forbidden = isError && isForbidden(error)
if (isError && !forbidden) throw error
+ if (isRegionsError) throw regionsError
+
+ const ready = !isPending && !!product && !isRegionsPending
return (
<RouteFocusModal>
@@ -258,9 +209,13 @@ export const OfferEditPricePage = () => {
</RouteFocusModal.Body>
</>
) : (
- !isPending &&
- product && (
- <EditPriceGrid product={product as PriceProduct} productId={id!} />
+ ready && (
+ <EditPriceGrid
+ product={product as PriceProduct}
+ productId={id!}
+ currencies={currencies}
+ regions={regions}
+ />
)
)}
</RouteFocusModal>
diff --git a/packages/vendor/src/pages/offers/[id]/edit-price/utils.spec.ts b/packages/vendor/src/pages/offers/[id]/edit-price/utils.spec.ts
new file mode 100644
index 000000000..9a9b48c78
--- /dev/null
+++ b/packages/vendor/src/pages/offers/[id]/edit-price/utils.spec.ts
@@ -0,0 +1,73 @@
+import { describe, expect, test } from "vitest"
+
+import { buildPricePayload, buildRows, PriceProduct } from "./utils"
+
+const eurRegion = { id: "reg_eu", currency_code: "eur" }
+
+const product = {
+ id: "prod_1",
+ thumbnail: null,
+ variants: [
+ {
+ id: "variant_1",
+ title: "Default",
+ offers: [
+ {
+ id: "offer_1",
+ prices: [
+ {
+ amount: 1200,
+ currency_code: "eur",
+ price_rules: [{ attribute: "offer_id", value: "offer_1" }],
+ },
+ {
+ amount: 1100,
+ currency_code: "eur",
+ price_rules: [
+ { attribute: "offer_id", value: "offer_1" },
+ { attribute: "region_id", value: "reg_eu" },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+} as unknown as PriceProduct
+
+describe("offer edit-price grid", () => {
+ test("rows carry the offer's current base and region prices", () => {
+ const [row] = buildRows(product, ["eur"], [eurRegion])
+
+ expect(row.prices).toEqual({ eur: 1200 })
+ expect(row.region_prices).toEqual({ reg_eu: 1100 })
+ })
+
+ test("rows built before the regions arrive would drop every price", () => {
+ const [row] = buildRows(product, [], [])
+
+ expect(buildPricePayload(row, [], [])).toEqual([])
+ })
+
+ test("an unedited row resends the prices it was built from", () => {
+ const [row] = buildRows(product, ["eur"], [eurRegion])
+
+ expect(buildPricePayload(row, ["eur"], [eurRegion])).toEqual([
+ { amount: 1200, currency_code: "eur" },
+ {
+ amount: 1100,
+ currency_code: "eur",
+ rules: { region_id: "reg_eu" },
+ },
+ ])
+ })
+
+ test("cleared cells are left out of the payload", () => {
+ const [row] = buildRows(product, ["eur"], [eurRegion])
+ row.region_prices.reg_eu = ""
+
+ expect(buildPricePayload(row, ["eur"], [eurRegion])).toEqual([
+ { amount: 1200, currency_code: "eur" },
+ ])
+ })
+})
diff --git a/packages/vendor/src/pages/offers/[id]/edit-price/utils.ts b/packages/vendor/src/pages/offers/[id]/edit-price/utils.ts
new file mode 100644
index 000000000..de71adafa
--- /dev/null
+++ b/packages/vendor/src/pages/offers/[id]/edit-price/utils.ts
@@ -0,0 +1,88 @@
+import { HttpTypes } from "@medusajs/types"
+import { OfferDTO } from "@mercurjs/types"
+
+import { castNumber } from "../../../../lib/cast-number"
+import { isBasePrice, isRegionPrice } from "../../common/region-prices"
+import { OfferPrice } from "../../common/types"
+
+export type EditPriceRow = {
+ offer_id: string
+ variant_title: string
+ product_thumbnail?: string | null
+ prices: Record<string, number | string>
+ region_prices: Record<string, number | string>
+}
+
+export type Region = HttpTypes.AdminRegion
+
+type RegionPrice = Pick<Region, "id" | "currency_code">
+
+export type PriceProduct = HttpTypes.AdminProduct & {
+ variants?: Array<
+ HttpTypes.AdminProductVariant & { offers?: OfferDTO[] | null }
+ > | null
+}
+
+export type OfferPricePayload = {
+ amount: number
+ currency_code: string
+ rules?: Record<string, string>
+}
+
+const isEmpty = (v: number | string | undefined | null): v is "" | null | undefined =>
+ v === "" || v === null || v === undefined
+
+const numericOrZero = (v: number | string): number => castNumber(v) || 0
+
+export const buildRows = (
+ product: PriceProduct,
+ currencies: string[],
+ regions: RegionPrice[],
+): EditPriceRow[] =>
+ (product.variants ?? []).flatMap((variant) =>
+ (variant.offers ?? []).map((offer) => {
+ const offerPrices = (offer.prices ?? []) as OfferPrice[]
+ const prices: Record<string, number | ""> = {}
+ for (const code of currencies) {
+ const match = offerPrices.find(
+ (p) => isBasePrice(p) && p.currency_code === code,
+ )
+ prices[code] = match?.amount ?? ""
+ }
+ const region_prices: Record<string, number | ""> = {}
+ for (const region of regions) {
+ const match = offerPrices.find((p) => isRegionPrice(p, region.id))
+ region_prices[region.id] = match?.amount ?? ""
+ }
+ return {
+ offer_id: offer.id,
+ variant_title: variant.title ?? "",
+ product_thumbnail: product.thumbnail ?? null,
+ prices,
+ region_prices,
+ }
+ }),
+ )
+
+export const buildPricePayload = (
+ row: EditPriceRow,
+ currencies: string[],
+ regions: RegionPrice[],
+): OfferPricePayload[] => {
+ const prices: OfferPricePayload[] = []
+ for (const code of currencies) {
+ const value = row.prices?.[code]
+ if (isEmpty(value)) continue
+ prices.push({ amount: numericOrZero(value), currency_code: code })
+ }
+ for (const region of regions) {
+ const value = row.region_prices?.[region.id]
+ if (isEmpty(value)) continue
+ prices.push({
+ amount: numericOrZero(value),
+ currency_code: region.currency_code,
+ rules: { region_id: region.id },
+ })
+ }
+ return prices
+}