The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
feat(admin): align price lists with Figma (MER-160) (#1331)
Viktor Holik0bfb44935881
diff --git a/integration-tests/http/price-lists/admin/price-list-offers.spec.ts b/integration-tests/http/price-lists/admin/price-list-offers.spec.tsnew file mode 100644index 000000000..c2479cb83--- /dev/null+++ b/integration-tests/http/price-lists/admin/price-list-offers.spec.ts@@ -0,0 +1,227 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"++import {+ adminHeaders,+ createAdminUser,+} from "../../../helpers/create-admin-user"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++/**+ * A price list "override"/"sale" for a marketplace offer is a native price in the+ * variant's shared price set, discriminated by an `offer_id` price rule — the same+ * mechanism the offer's own price uses (`create-offers.ts`). The stock admin+ * price-list routes already accept `rules: { offer_id }` per price, so no route+ * override is needed. This spec locks in the contract: the override applies to the+ * targeted offer and does NOT leak to a different offer selling the same variant.+ */+medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Admin - Price Lists (offer-scoped price rules)", () => {+ let appContainer: MedusaContainer+ let variantId: string+ let priceSetId: string+ let offerA: any+ let offerB: any++ const seedSellerOffer = async (opts: {+ email: string+ name: string+ variantId: string+ amount: number+ }) => {+ const { seller, headers } = await createSellerUser(appContainer, {+ email: opts.email,+ name: opts.name,+ })+ const tag = `${opts.name}`++ const stockLocation = (+ await api.post(+ `/vendor/stock-locations`,+ { name: `Warehouse_${tag}` },+ headers+ )+ ).data.stock_location++ const shippingProfile = (+ await api.post(+ `/vendor/shipping-profiles`,+ { name: `SP_${tag}`, type: "default" },+ headers+ )+ ).data.shipping_profile++ const offer = (+ await api.post(+ `/vendor/offers`,+ {+ sku: `OF_${tag}`,+ variant_id: opts.variantId,+ shipping_profile_id: shippingProfile.id,+ inventory_items: [+ {+ title: `Inv_${tag}`,+ required_quantity: 1,+ stock_levels: [+ { location_id: stockLocation.id, stocked_quantity: 10 },+ ],+ },+ ],+ prices: [{ amount: opts.amount, currency_code: "usd" }],+ },+ headers+ )+ ).data.offer++ return { sellerId: (seller as any).id, offer }+ }++ const calc = async (offerId: string) => {+ const pricingModule = appContainer.resolve(Modules.PRICING)+ const [result] = await pricingModule.calculatePrices(+ { id: [priceSetId] },+ { context: { currency_code: "usd", offer_id: offerId } }+ )+ return result?.calculated_amount ?? null+ }++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)++ // A single master product + variant, sold by two sellers via two offers.+ const seller = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "ProductOwner",+ })+ const product = await createVendorProduct(api, seller.headers, {+ title: "Shared Master Product",+ sku: "SHARED-1",+ })+ variantId = product.variants[0].id++ offerA = (+ await seedSellerOffer({+ email: "[email protected]",+ name: "OfferA",+ variantId,+ amount: 1000,+ })+ ).offer+ offerB = (+ await seedSellerOffer({+ email: "[email protected]",+ name: "OfferB",+ variantId,+ amount: 1000,+ })+ ).offer++ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)+ const { data: variants } = await query.graph({+ entity: "product_variant",+ fields: ["id", "price_set.id"],+ filters: { id: variantId },+ })+ priceSetId = (variants[0] as any).price_set.id+ })++ it("creates a price list override scoped to a single offer via rules.offer_id", async () => {+ const res = await api.post(+ "/admin/price-lists",+ {+ title: "Winter 24",+ description: "Offer A markdown",+ type: "override",+ status: "active",+ prices: [+ {+ variant_id: variantId,+ currency_code: "usd",+ amount: 500,+ rules: { offer_id: offerA.id },+ },+ ],+ },+ adminHeaders+ )++ expect(res.status).toEqual(200)+ const priceListId = res.data.price_list.id++ // The persisted price carries the offer_id rule (read via the data layer;+ // the HTTP detail route does not populate price_rules).+ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)+ const { data: persisted } = await query.graph({+ entity: "price",+ filters: { price_list_id: priceListId },+ fields: ["id", "amount", "price_rules.attribute", "price_rules.value"],+ })+ expect(persisted).toHaveLength(1)+ expect((persisted[0] as any).price_rules).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ attribute: "offer_id",+ value: offerA.id,+ }),+ ])+ )++ // Isolation: the override wins for offer A, offer B keeps its base price.+ expect(await calc(offerA.id)).toEqual(500)+ expect(await calc(offerB.id)).toEqual(1000)+ })++ it("adds and updates offer-scoped prices via the /prices/batch route", async () => {+ const priceListId = (+ await api.post(+ "/admin/price-lists",+ {+ title: "Batch PL",+ description: "batch",+ type: "override",+ status: "active",+ prices: [+ {+ variant_id: variantId,+ currency_code: "usd",+ amount: 500,+ rules: { offer_id: offerA.id },+ },+ ],+ },+ adminHeaders+ )+ ).data.price_list.id++ // Add an override for offer B and lower offer A's override.+ const batch = await api.post(+ `/admin/price-lists/${priceListId}/prices/batch`,+ {+ create: [+ {+ variant_id: variantId,+ currency_code: "usd",+ amount: 700,+ rules: { offer_id: offerB.id },+ },+ ],+ },+ adminHeaders+ )+ expect(batch.status).toEqual(200)++ expect(await calc(offerA.id)).toEqual(500)+ expect(await calc(offerB.id)).toEqual(700)+ })+ })+ },+})diff --git a/integration-tests/http/price-lists/admin/price-lists.spec.ts b/integration-tests/http/price-lists/admin/price-lists.spec.tsnew file mode 100644index 000000000..73daf56a3--- /dev/null+++ b/integration-tests/http/price-lists/admin/price-lists.spec.ts@@ -0,0 +1,102 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"++import {+ adminHeaders,+ createAdminUser,+} from "../../../helpers/create-admin-user"+import { createSellerUser } from "../../../helpers/create-seller-user"++jest.setTimeout(50000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Admin - Price Lists (marketplace fields)", () => {+ let appContainer: MedusaContainer+ let sellerHeaders: any++ beforeAll(async () => {+ appContainer = getContainer()+ })++ beforeEach(async () => {+ await createAdminUser(dbConnection, adminHeaders, appContainer)++ const seller = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Owner Store",+ })+ sellerHeaders = seller.headers++ // Vendor-created price list is linked to the seller via+ // createSellerPriceListsWorkflow — this is the "store-owned" case.+ await api.post(+ "/vendor/price-lists",+ {+ title: "Owner Store PL",+ description: "seller owned",+ status: "active",+ type: "sale",+ },+ sellerHeaders+ )+ })++ it("resolves the owning seller via +seller.name (Owner column)", async () => {+ const res = await api.get(+ "/admin/price-lists?fields=%2Bseller.name",+ adminHeaders+ )++ expect(res.status).toEqual(200)+ const pl = res.data.price_lists.find(+ (p: any) => p.title === "Owner Store PL"+ )+ expect(pl).toBeDefined()+ // The field must actually come back non-empty — not just type-check.+ expect(pl.seller).toBeDefined()+ expect(pl.seller.name).toEqual("Owner Store")+ })++ it("accepts the marketplace list filters (type / status / created_at / updated_at)", async () => {+ const type = await api.get(+ "/admin/price-lists?type[]=sale",+ adminHeaders+ )+ expect(type.status).toEqual(200)+ expect(+ type.data.price_lists.some((p: any) => p.title === "Owner Store PL")+ ).toBe(true)++ const override = await api.get(+ "/admin/price-lists?type[]=override",+ adminHeaders+ )+ expect(override.status).toEqual(200)+ expect(+ override.data.price_lists.some(+ (p: any) => p.title === "Owner Store PL"+ )+ ).toBe(false)++ const status = await api.get(+ "/admin/price-lists?status[]=active",+ adminHeaders+ )+ expect(status.status).toEqual(200)++ const created = await api.get(+ "/admin/price-lists?created_at[$gte]=2020-01-01",+ adminHeaders+ )+ expect(created.status).toEqual(200)++ const updated = await api.get(+ "/admin/price-lists?updated_at[$lte]=2999-01-01",+ adminHeaders+ )+ expect(updated.status).toEqual(200)+ })+ })+ },+})diff --git a/packages/admin/src/components/common/thumbnail/thumbnail.tsx b/packages/admin/src/components/common/thumbnail/thumbnail.tsxindex 5e32de1cd..a29afbb95 100644--- a/packages/admin/src/components/common/thumbnail/thumbnail.tsx+++ b/packages/admin/src/components/common/thumbnail/thumbnail.tsx@@ -11,7 +11,7 @@ export const Thumbnail = ({ src, alt, size = "base" }: ThumbnailProps) => {return (<divclassName={clx(- "bg-ui-bg-component border-ui-border-base flex items-center justify-center overflow-hidden rounded border",+ "bg-ui-bg-component border-ui-border-base flex shrink-0 items-center justify-center overflow-hidden rounded border",{"h-8 w-6": size === "base","h-5 w-4": size === "small",diff --git a/packages/admin/src/get-route-map.tsx b/packages/admin/src/get-route-map.tsxindex 25f705899..8796da255 100644--- a/packages/admin/src/get-route-map.tsx+++ b/packages/admin/src/get-route-map.tsx@@ -676,6 +676,13 @@ export function getRouteMap({lazy: () =>import("./pages/price-lists/price-list-configuration"),},+ {+ path: "customer-availability",+ lazy: () =>+ import(+ "./pages/price-lists/price-list-customer-availability"+ ),+ },{path: "products/add",lazy: () =>diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.jsonindex c9a5e328e..ccd46556b 100644--- a/packages/admin/src/i18n/translations/en.json+++ b/packages/admin/src/i18n/translations/en.json@@ -2787,18 +2787,32 @@"confirmation": "You are about to delete the price list \"{{title}}\". This action cannot be undone.","successToast": "Price list \"{{title}}\" was successfully deleted."},+ "list": {+ "noRecords": {+ "title": "No price lists yet",+ "message": "Create price lists for sales and price overrides"+ },+ "noResults": {+ "title": "No results",+ "message": "Try changing the filters or search query"+ }+ },"create": {"header": "Create Price List",- "subheader": "Create a new price list to manage the prices of your products.",+ "subheader": "Create a new price list to manage the prices of your offers.","tabs": {"details": "Details",- "products": "Products",+ "products": "Offers","prices": "Prices"},"successToast": "Price list {{title}} was successfully created.",+ "validation": {+ "title": "Please enter a title",+ "description": "Please enter a description"+ },"products": {"list": {- "noRecordsMessage": "Create a product first."+ "noRecordsMessage": "Create an offer first."}}},@@ -2814,33 +2828,51 @@"successToast": "Price list configuration was successfully updated."}},+ "customerAvailability": {+ "header": "Customer availability",+ "add": "Add customer groups",+ "list": {+ "noRecordsTitle": "No customer groups",+ "noRecordsMessage": "Add customer groups to restrict which customers this price list applies to."+ },+ "edit": {+ "header": "Customer availability",+ "description": "Choose which customer groups the price list should be applied to.",+ "successToast": "Customer availability was successfully updated."+ }+ },"products": {- "header": "Products",+ "header": "Offers","actions": {- "addProducts": "Add products",+ "addProducts": "Add offers","editPrices": "Edit prices",- "editPricesDisabled": "Add products before editing prices"+ "editPricesDisabled": "Add offers before editing prices"},"delete": {- "confirmation_one": "You are about to delete the prices for {{count}} product in the price list. This action cannot be undone.",- "confirmation_other": "You are about to delete the prices for {{count}} products in the price list. This action cannot be undone.",- "successToast_one": "Successfully deleted prices for {{count}} product.",- "successToast_other": "Successfully deleted prices for {{count}} products."+ "confirmation_one": "You are about to remove {{count}} offer from the price list. This action cannot be undone.",+ "confirmation_other": "You are about to remove {{count}} offers from the price list. This action cannot be undone.",+ "successToast_one": "Successfully removed {{count}} offer from the price list.",+ "successToast_other": "Successfully removed {{count}} offers from the price list."},"add": {"successToast": "Prices were successfully added to the price list.",- "alreadyInPriceList": "This product is already in the price list",- "noVariants": "This product has no variants"+ "alreadyInPriceList": "This offer is already in the price list",+ "noVariants": "This offer has no variants"},"edit": {"successToast": "Prices were successfully updated."}},"fields": {+ "offerVariant": "Offer/Variant","priceOverrides": {"label": "Price overrides","header": "Price Overrides"},+ "owner": {+ "label": "Owner",+ "marketplace": "Mercur"+ },"status": {"label": "Status","options": {@@ -2848,6 +2880,10 @@"draft": "Draft","expired": "Expired","scheduled": "Scheduled"+ },+ "descriptions": {+ "draft": "Customers will not be able to see the price list",+ "active": "Customers will be able to see the price list"}},"type": {@@ -2856,7 +2892,7 @@"options": {"sale": {"label": "Sale",- "description": "Sale prices are temporary price changes for products."+ "description": "Sale prices are temporary price changes for offers."},"override": {"label": "Override",@@ -2865,11 +2901,11 @@}},"startsAt": {- "label": "Price list has a start date?",+ "label": "Start date","hint": "Schedule the price list to activate in the future."},"endsAt": {- "label": "Price list has an expiry date?",+ "label": "Expiry date","hint": "Schedule the price list to deactivate in the future."},"customerAvailability": {diff --git a/packages/admin/src/pages/price-lists/common/build-offer-grid-data.ts b/packages/admin/src/pages/price-lists/common/build-offer-grid-data.tsnew file mode 100644index 000000000..c97eb53e5--- /dev/null+++ b/packages/admin/src/pages/price-lists/common/build-offer-grid-data.ts@@ -0,0 +1,91 @@+import { OfferDTO } from "@mercurjs/types"++import { PriceListGridRow } from "./hooks/use-price-list-grid-columns"++type ProductWithVariants = {+ variants?: { id: string; title?: string | null }[] | null+}++/**+ * Turn the selected offers + their products into the interleaved grid rows for+ * the Prices grid: one group header per (product, seller) followed by that+ * seller's variant/offer rows. The same product from two sellers yields two+ * separate groups. Also returns offer_id -> variant_id for seeding the form.+ */+export const buildOfferGridData = (+ offers: OfferDTO[],+ products: ProductWithVariants[]+) => {+ const variantTitle: Record<string, string> = {}+ // Canonical variant order per product, so rows sort like the variant column.+ const variantOrder: Record<string, number> = {}+ for (const product of products) {+ ;(product.variants ?? []).forEach((variant, index) => {+ variantTitle[variant.id] = variant.title ?? ""+ variantOrder[variant.id] = index+ })+ }++ const variantIdByOffer: Record<string, string> = {}++ const groups = new Map<+ string,+ {+ product_title: string+ product_thumbnail?: string | null+ seller_name: string+ offers: OfferDTO[]+ }+ >()++ for (const offer of offers) {+ variantIdByOffer[offer.id] = offer.variant_id+ const key = `${offer.product_id}::${offer.seller_id}`+ const group = groups.get(key)+ if (group) {+ group.offers.push(offer)+ } else {+ groups.set(key, {+ product_title: offer.product?.title ?? "",+ product_thumbnail: offer.product?.thumbnail ?? null,+ seller_name: offer.seller?.name ?? "",+ offers: [offer],+ })+ }+ }++ const gridData: PriceListGridRow[] = []+ for (const [key, group] of groups) {+ gridData.push({+ __group: true,+ id: `group-${key}`,+ product_title: group.product_title,+ product_thumbnail: group.product_thumbnail,+ seller_name: group.seller_name,+ })+ const sortedOffers = [...group.offers].sort((a, b) => {+ const oa = variantOrder[a.variant_id]+ const ob = variantOrder[b.variant_id]+ if (oa !== undefined && ob !== undefined && oa !== ob) {+ return oa - ob+ }+ return (variantTitle[a.variant_id] ?? a.sku ?? "").localeCompare(+ variantTitle[b.variant_id] ?? b.sku ?? ""+ )+ })+ for (const offer of sortedOffers) {+ gridData.push({+ __group: false,+ id: offer.id,+ offer_id: offer.id,+ variant_id: offer.variant_id,+ variant_title: variantTitle[offer.variant_id] ?? offer.sku ?? "",+ product_id: offer.product_id,+ seller_name: group.seller_name,+ sku: offer.sku ?? "",+ })+ }+ }++ return { gridData, variantIdByOffer }+}diff --git a/packages/admin/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx b/packages/admin/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsxindex bd9ff849a..1b42fc34b 100644--- a/packages/admin/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx+++ b/packages/admin/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx@@ -9,13 +9,38 @@ import {DataGrid,} from "../../../../components/data-grid"import { createDataGridPriceColumns } from "../../../../components/data-grid/helpers/create-data-grid-price-columns"-import { PricingCreateSchemaType } from "../../price-list-create/components/price-list-create-form/schema"-import { isProductRow } from "../utils"-const columnHelper = createDataGridHelper<- HttpTypes.AdminProduct | HttpTypes.AdminProductVariant,- PricingCreateSchemaType->()+/**+ * The Prices grid is keyed by **offer**, not variant: the same product sold by+ * two sellers must show as two separate groups (product + seller) with their own+ * variant rows, never merged. Each offer row binds prices to `offers.<offer_id>`.+ */+export type PriceListGridGroupRow = {+ __group: true+ id: string+ product_title: string+ product_thumbnail?: string | null+ seller_name: string+}++export type PriceListGridOfferRow = {+ __group: false+ id: string+ offer_id: string+ variant_id: string+ variant_title: string+ product_id: string+ seller_name: string+ sku: string+}++export type PriceListGridRow = PriceListGridGroupRow | PriceListGridOfferRow++export const isPriceListGroupRow = (+ row: PriceListGridRow+): row is PriceListGridGroupRow => (row as PriceListGridGroupRow).__group === true++const columnHelper = createDataGridHelper<PriceListGridRow, any>()export const usePriceListGridColumns = ({currencies = [],@@ -28,21 +53,21 @@ export const usePriceListGridColumns = ({}) => {const { t } = useTranslation()- const colDefs: ColumnDef<- HttpTypes.AdminProduct | HttpTypes.AdminProductVariant- >[] = useMemo(() => {+ const colDefs: ColumnDef<PriceListGridRow>[] = useMemo(() => {return [columnHelper.column({- id: t("fields.title"),- header: t("fields.title"),+ id: t("priceLists.fields.offerVariant"),+ header: t("priceLists.fields.offerVariant"),cell: (context) => {- const entity = context.row.original- if (isProductRow(entity)) {+ const row = context.row.original+ if (isPriceListGroupRow(row)) {return (<DataGrid.ReadonlyCell context={context}><div className="flex h-full w-full items-center gap-x-2 overflow-hidden">- <Thumbnail src={entity.thumbnail} size="small" />- <span className="truncate">{entity.title}</span>+ <Thumbnail src={row.product_thumbnail} size="small" />+ <span className="truncate font-medium">+ {row.product_title}+ </span></div></DataGrid.ReadonlyCell>)@@ -51,36 +76,57 @@ export const usePriceListGridColumns = ({return (<DataGrid.ReadonlyCell context={context} color="normal"><div className="flex h-full w-full items-center gap-x-2 overflow-hidden">- <span className="truncate">{entity.title}</span>+ <span className="truncate">{row.variant_title}</span></div></DataGrid.ReadonlyCell>)},disableHiding: true,}),- ...createDataGridPriceColumns<- HttpTypes.AdminProduct | HttpTypes.AdminProductVariant,- PricingCreateSchemaType- >({+ columnHelper.column({+ id: "store",+ name: t("offers.fields.store"),+ header: t("offers.fields.store"),+ cell: (context) => {+ const row = context.row.original+ return (+ <DataGrid.ReadonlyCell context={context}>+ <span className="text-ui-fg-subtle truncate">+ {row.seller_name}+ </span>+ </DataGrid.ReadonlyCell>+ )+ },+ }),+ columnHelper.column({+ id: "offer_sku",+ name: t("fields.sku"),+ header: t("fields.sku"),+ cell: (context) => {+ const row = context.row.original+ const sku = isPriceListGroupRow(row) ? "" : row.sku+ return (+ <DataGrid.ReadonlyCell context={context}>+ <span className="text-ui-fg-subtle truncate">{sku}</span>+ </DataGrid.ReadonlyCell>+ )+ },+ }),+ ...createDataGridPriceColumns<PriceListGridRow, any>({currencies: currencies.map((c) => c.currency_code),regions,pricePreferences,- isReadyOnly: (context) => {- const entity = context.row.original- return isProductRow(entity)- },+ isReadyOnly: (context) =>+ isPriceListGroupRow(context.row.original),getFieldName: (context, value) => {- const entity = context.row.original-- if (isProductRow(entity)) {+ const row = context.row.original+ if (isPriceListGroupRow(row)) {return null}-if (context.column.id?.startsWith("currency_prices")) {- return `products.${entity.product_id}.variants.${entity.id}.currency_prices.${value}.amount`+ return `offers.${row.offer_id}.currency_prices.${value}.amount`}-- return `products.${entity.product_id}.variants.${entity.id}.region_prices.${value}.amount`+ return `offers.${row.offer_id}.region_prices.${value}.amount`},t,}),diff --git a/packages/admin/src/pages/price-lists/common/schemas.ts b/packages/admin/src/pages/price-lists/common/schemas.tsindex dceda6eb8..cf624f705 100644--- a/packages/admin/src/pages/price-lists/common/schemas.ts+++ b/packages/admin/src/pages/price-lists/common/schemas.ts@@ -56,6 +56,22 @@ export type PriceListCreateProductsSchema = z.infer<typeof PriceListCreateProductsSchema>+// Offer-keyed prices: one entry per offer (a seller's variant listing) so the+// same variant offered by two sellers stays separate.+export const PriceListCreateOfferSchema = z.object({+ variant_id: z.string(),+ currency_prices: z.record(PriceListCreateCurrencyPriceSchema.optional()),+ region_prices: z.record(PriceListCreateRegionPriceSchema.optional()),+})++export type PriceListCreateOffer = z.infer<typeof PriceListCreateOfferSchema>++export const PriceListCreateOffersSchema = z.record(PriceListCreateOfferSchema)++export type PriceListCreateOffersSchema = z.infer<+ typeof PriceListCreateOffersSchema+>+export const PriceListUpdateCurrencyPriceSchema = z.object({amount: z.string().or(z.number()).optional(),id: z.string().nullish(),@@ -94,3 +110,17 @@ export const PriceListUpdateProductsSchema = z.record(export type PriceListUpdateProductsSchema = z.infer<typeof PriceListUpdateProductsSchema>++export const PriceListUpdateOfferSchema = z.object({+ variant_id: z.string(),+ currency_prices: z.record(PriceListUpdateCurrencyPriceSchema.optional()),+ region_prices: z.record(PriceListUpdateRegionPriceSchema.optional()),+})++export const PriceListUpdateOffersSchema = z.record(PriceListUpdateOfferSchema)++export type PriceListUpdateOffersSchema = z.infer<+ typeof PriceListUpdateOffersSchema+>++export type PriceListUpdateOffer = z.infer<typeof PriceListUpdateOfferSchema>diff --git a/packages/admin/src/pages/price-lists/common/utils.ts b/packages/admin/src/pages/price-lists/common/utils.tsindex fb26dd6ba..d998e94ff 100644--- a/packages/admin/src/pages/price-lists/common/utils.ts+++ b/packages/admin/src/pages/price-lists/common/utils.ts@@ -4,8 +4,7 @@ import { castNumber } from "../../../lib/cast-number"import { PriceListDateStatus, PriceListStatus } from "./constants"import {PriceListCreateCurrencyPrice,- PriceListCreateProductVariantSchema,- PriceListCreateProductsSchema,+ PriceListCreateOffersSchema,} from "./schemas"const getValues = (priceList: HttpTypes.AdminPriceList) => {@@ -64,62 +63,55 @@ export const isProductRow = (return "variants" in row}-const extractPricesFromVariants = (- variantId: string,- variant: PriceListCreateProductVariantSchema,+// Build the API price payload from the offer-keyed grid state. Each price+// carries its offer_id rule so the override is scoped to that seller's offer.+export const extractPricesFromOffers = (+ offers: PriceListCreateOffersSchema,regions: HttpTypes.AdminRegion[]) => {- const extractPriceDetails = (- price: PriceListCreateCurrencyPrice,- priceType: "region" | "currency",- id: string- ) => {- const currencyCode =- priceType === "currency"- ? id- : regions.find((r) => r.id === id)?.currency_code-- if (!currencyCode) {- throw new Response(- JSON.stringify({ message: i18n.t("validation.currencyCodeNotFound") }),- { status: 400, headers: { "Content-Type": "application/json" } }- )+ return Object.entries(offers).flatMap(([offerId, offer]) => {+ const extractPriceDetails = (+ price: PriceListCreateCurrencyPrice,+ priceType: "region" | "currency",+ id: string+ ) => {+ const currencyCode =+ priceType === "currency"+ ? id+ : regions.find((r) => r.id === id)?.currency_code++ if (!currencyCode) {+ throw new Response(+ JSON.stringify({ message: i18n.t("validation.currencyCodeNotFound") }),+ { status: 400, headers: { "Content-Type": "application/json" } }+ )+ }++ return {+ amount: castNumber(price.amount!),+ rules: {+ offer_id: offerId,+ ...(priceType === "region" ? { region_id: id } : {}),+ },+ currency_code: currencyCode,+ variant_id: offer.variant_id,+ }}- return {- amount: castNumber(price.amount!),- ...(priceType === "region" ? { rules: { region_id: id } } : {}),- currency_code: currencyCode,- variant_id: variantId,- }- }-- const currencyPrices = Object.entries(variant.currency_prices || {}).flatMap(- ([currencyCode, currencyPrice]) => {- return currencyPrice?.amount- ? [extractPriceDetails(currencyPrice, "currency", currencyCode)]- : []- }- )-- const regionPrices = Object.entries(variant.region_prices || {}).flatMap(- ([regionId, regionPrice]) => {- return regionPrice?.amount- ? [extractPriceDetails(regionPrice, "region", regionId)]- : []- }- )-- return [...currencyPrices, ...regionPrices]-}+ const currencyPrices = Object.entries(offer.currency_prices || {}).flatMap(+ ([currencyCode, currencyPrice]) =>+ currencyPrice?.amount+ ? [extractPriceDetails(currencyPrice, "currency", currencyCode)]+ : []+ )-export const exctractPricesFromProducts = (- products: PriceListCreateProductsSchema,- regions: HttpTypes.AdminRegion[]-) => {- return Object.values(products).flatMap(({ variants }) =>- Object.entries(variants).flatMap(([variantId, variant]) =>- extractPricesFromVariants(variantId, variant, regions)+ const regionPrices = Object.entries(offer.region_prices || {}).flatMap(+ ([regionId, regionPrice]) =>+ regionPrice?.amount+ ? [extractPriceDetails(regionPrice, "region", regionId)]+ : [])- )++ return [...currencyPrices, ...regionPrices]+ })}diff --git a/packages/admin/src/pages/price-lists/price-list-configuration/components/price-list-configuration-form/price-list-configuration-form.tsx b/packages/admin/src/pages/price-lists/price-list-configuration/components/price-list-configuration-form/price-list-configuration-form.tsxindex d28e8f3fd..d2660be7c 100644--- a/packages/admin/src/pages/price-lists/price-list-configuration/components/price-list-configuration-form/price-list-configuration-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-configuration/components/price-list-configuration-form/price-list-configuration-form.tsx@@ -1,110 +1,45 @@import { zodResolver } from "@hookform/resolvers/zod"-import { MagnifyingGlass, XMark } from "@medusajs/icons"import { HttpTypes } from "@medusajs/types"-import {- Button,- DatePicker,- Divider,- Heading,- IconButton,- Text,- clx,- toast,-} from "@medusajs/ui"-import { useFieldArray, useForm } from "react-hook-form"+import { Button, DatePicker, toast } from "@medusajs/ui"+import { useForm } from "react-hook-form"import { useTranslation } from "react-i18next"import { z } from "zod"import { Form } from "../../../../../components/common/form"import { RouteDrawer, useRouteModal } from "../../../../../components/modals"-import { StackedDrawer } from "../../../../../components/modals/stacked-drawer"-import { useStackedModal } from "../../../../../components/modals/stacked-modal-provider"import { KeyboundForm } from "../../../../../components/utilities/keybound-form"import { useUpdatePriceList } from "../../../../../hooks/api/price-lists"-import { PriceListCustomerGroupRuleForm } from "../../../common/components/price-list-customer-group-rule-form"-import { PricingCustomerGroupsArrayType } from "../../../price-list-create/components/price-list-create-form/schema"type PriceListConfigurationFormProps = {priceList: HttpTypes.AdminPriceList- customerGroups: { id: string; name: string }[]}const PriceListConfigurationSchema = z.object({ends_at: z.date().nullable(),starts_at: z.date().nullable(),- customer_group_id: z.array(- z.object({- id: z.string(),- name: z.string(),- })- ),})-const STACKED_MODAL_ID = "cg"-export const PriceListConfigurationForm = ({priceList,- customerGroups,}: PriceListConfigurationFormProps) => {const { t } = useTranslation()const { handleSuccess } = useRouteModal()- const { setIsOpen } = useStackedModal()const form = useForm<z.infer<typeof PriceListConfigurationSchema>>({defaultValues: {ends_at: priceList.ends_at ? new Date(priceList.ends_at) : null,starts_at: priceList.starts_at ? new Date(priceList.starts_at) : null,- customer_group_id: customerGroups,},resolver: zodResolver(PriceListConfigurationSchema),})- const { fields, remove, append } = useFieldArray({- control: form.control,- name: "customer_group_id",- keyName: "cg_id",- })-- const handleAddCustomerGroup = (groups: PricingCustomerGroupsArrayType) => {- if (!groups.length) {- form.setValue("customer_group_id", [])- setIsOpen(STACKED_MODAL_ID, false)- return- }-- const newIds = groups.map((group) => group.id)-- const fieldsToAdd = groups.filter(- (group) => !fields.some((field) => field.id === group.id)- )-- for (const field of fields) {- if (!newIds.includes(field.id)) {- remove(fields.indexOf(field))- }- }-- append(fieldsToAdd)- setIsOpen(STACKED_MODAL_ID, false)- }-const { mutateAsync } = useUpdatePriceList(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- const groupIds = values.customer_group_id.map((group) => group.id)- const rules = { ...priceList.rules } // preserve other rules set on the PL-- if (groupIds.length) {- rules["customer.groups.id"] = groupIds- } else {- delete rules["customer.groups.id"]- }-await mutateAsync({starts_at: values.starts_at?.toISOString() || null,ends_at: values.ends_at?.toISOString() || null,- rules: rules,},{onSuccess: () => {@@ -125,7 +60,7 @@ export const PriceListConfigurationForm = ({className="flex flex-1 flex-col overflow-hidden"onSubmit={handleSubmit}>- <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-auto" data-testid="price-list-configuration-form-body">+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto" data-testid="price-list-configuration-form-body"><Form.Fieldcontrol={form.control}name="starts_at"@@ -133,14 +68,9 @@ export const PriceListConfigurationForm = ({return (<Form.Item><div className="grid grid-cols-1 gap-3">- <div className="flex flex-col">- <Form.Label optional>- {t("priceLists.fields.startsAt.label")}- </Form.Label>- <Form.Hint>- {t("priceLists.fields.startsAt.hint")}- </Form.Hint>- </div>+ <Form.Label optional>+ {t("priceLists.fields.startsAt.label")}+ </Form.Label><Form.Control><DatePickergranularity="minute"@@ -154,7 +84,6 @@ export const PriceListConfigurationForm = ({)}}/>- <Divider /><Form.Fieldcontrol={form.control}name="ends_at"@@ -162,14 +91,9 @@ export const PriceListConfigurationForm = ({return (<Form.Item><div className="grid grid-cols-1 gap-3">- <div className="flex flex-col">- <Form.Label optional>- {t("priceLists.fields.endsAt.label")}- </Form.Label>- <Form.Hint>- {t("priceLists.fields.endsAt.hint")}- </Form.Hint>- </div>+ <Form.Label optional>+ {t("priceLists.fields.endsAt.label")}+ </Form.Label><Form.Control><DatePickergranularity="minute"@@ -183,118 +107,6 @@ export const PriceListConfigurationForm = ({)}}/>- <Divider />- <Form.Field- control={form.control}- name="customer_group_id"- render={({ field }) => {- return (- <Form.Item>- <div>- <Form.Label optional>- {t("priceLists.fields.customerAvailability.label")}- </Form.Label>- <Form.Hint>- {t("priceLists.fields.customerAvailability.hint")}- </Form.Hint>- </div>- <Form.Control>- <div- className={clx(- "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",- "aria-[invalid='true']:shadow-borders-error"- )}- role="application"- ref={field.ref}- >- <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">- <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">- {t(- "priceLists.fields.customerAvailability.attribute"- )}- </div>- <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">- {t("operators.in")}- </div>- </div>- <div className="flex items-center gap-1.5 px-1.5" data-testid="price-list-configuration-customer-groups-dropdown">- <StackedDrawer id={STACKED_MODAL_ID} data-testid="price-list-configuration-customer-groups-stacked-drawer">- <StackedDrawer.Trigger asChild>- <button- type="button"- className="bg-ui-bg-field shadow-borders-base txt-compact-small text-ui-fg-muted flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5"- data-testid="price-list-configuration-customer-groups-search-button"- >- <MagnifyingGlass />- {t(- "priceLists.fields.customerAvailability.placeholder"- )}- </button>- </StackedDrawer.Trigger>- <StackedDrawer.Trigger asChild>- <Button variant="secondary" data-testid="price-list-configuration-customer-groups-browse-button">- {t("actions.browse")}- </Button>- </StackedDrawer.Trigger>- <StackedDrawer.Content data-testid="price-list-configuration-customer-groups-drawer-content">- <StackedDrawer.Header data-testid="price-list-configuration-customer-groups-drawer-header">- <StackedDrawer.Title asChild>- <Heading data-testid="price-list-configuration-customer-groups-drawer-title">- {t(- "priceLists.fields.customerAvailability.header"- )}- </Heading>- </StackedDrawer.Title>- <StackedDrawer.Description className="sr-only" data-testid="price-list-configuration-customer-groups-drawer-description">- {t(- "priceLists.fields.customerAvailability.hint"- )}- </StackedDrawer.Description>- </StackedDrawer.Header>- <PriceListCustomerGroupRuleForm- type="drawer"- setState={handleAddCustomerGroup}- state={fields}- />- </StackedDrawer.Content>- </StackedDrawer>- </div>- {fields.length > 0 ? (- <div className="flex flex-col gap-y-1.5" data-testid="price-list-configuration-customer-groups-list">- <Divider variant="dashed" />- <div className="flex flex-col gap-y-1.5 px-1.5">- {fields.map((field, index) => {- return (- <div- key={field.cg_id}- className="bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5"- data-testid={`price-list-configuration-customer-groups-item-${index}`}- >- <Text size="small" leading="compact" data-testid={`price-list-configuration-customer-groups-item-${index}-name`}>- {field.name}- </Text>- <IconButton- size="small"- variant="transparent"- type="button"- onClick={() => remove(index)}- data-testid={`price-list-configuration-customer-groups-item-${index}-remove-button`}- >- <XMark />- </IconButton>- </div>- )- })}- </div>- </div>- ) : null}- </div>- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}- /></RouteDrawer.Body><RouteDrawer.Footer className="shrink-0" data-testid="price-list-configuration-form-footer"><div className="flex items-center justify-end gap-x-2">diff --git a/packages/admin/src/pages/price-lists/price-list-configuration/price-list-configuration.tsx b/packages/admin/src/pages/price-lists/price-list-configuration/price-list-configuration.tsxindex b0de3dded..eda4fb282 100644--- a/packages/admin/src/pages/price-lists/price-list-configuration/price-list-configuration.tsx+++ b/packages/admin/src/pages/price-lists/price-list-configuration/price-list-configuration.tsx@@ -2,7 +2,6 @@ import { Heading } from "@medusajs/ui"import { useTranslation } from "react-i18next"import { useParams } from "react-router-dom"import { RouteDrawer } from "../../../components/modals"-import { useCustomerGroups } from "../../../hooks/api/customer-groups"import { usePriceList } from "../../../hooks/api/price-lists"import { PriceListConfigurationForm } from "./components/price-list-configuration-form"@@ -12,42 +11,12 @@ export const PriceListConfiguration = () => {const { price_list, isPending, isError, error } = usePriceList(id!)- const customerGroupIds = price_list?.rules?.["customer.groups.id"] as- | string[]- | undefined-- const {- customer_groups,- isPending: isCustomerGroupsPending,- isError: isCustomerGroupsError,- error: customerGroupsError,- } = useCustomerGroups(- {- id: customerGroupIds,- },- { enabled: !!customerGroupIds?.length }- )-- const initialCustomerGroups =- customer_groups?.map((group) => ({- id: group.id,- name: group.name!,- })) || []-- const isCustomerGroupsReady = isPending- ? false- : !(!!customerGroupIds?.length && isCustomerGroupsPending)-- const ready = !isPending && !!price_list && isCustomerGroupsReady+ const ready = !isPending && !!price_listif (isError) {throw error}- if (isCustomerGroupsError) {- throw customerGroupsError- }-return (<RouteDrawer><RouteDrawer.Header>@@ -55,12 +24,7 @@ export const PriceListConfiguration = () => {<Heading>{t("priceLists.configuration.edit.header")}</Heading></RouteDrawer.Title></RouteDrawer.Header>- {ready && (- <PriceListConfigurationForm- priceList={price_list}- customerGroups={initialCustomerGroups}- />- )}+ {ready && <PriceListConfigurationForm priceList={price_list} />}</RouteDrawer>)}diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsxindex cd5f715c4..605bc9485 100644--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx@@ -8,7 +8,7 @@ import { HttpTypes, PriceListStatus, PriceListType } from "@medusajs/types"import { useRouteModal } from "../../../../../components/modals"import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { useCreatePriceList } from "../../../../../hooks/api/price-lists"-import { exctractPricesFromProducts } from "../../../common/utils"+import { extractPricesFromOffers } from "../../../common/utils"import { PriceListDetailsForm } from "./price-list-details-form"import { PriceListPricesForm } from "./price-list-prices-form"import { PriceListProductsForm } from "./price-list-products-form"@@ -39,13 +39,14 @@ export const PriceListCreateForm = ({const form = useForm<PricingCreateSchemaType>({defaultValues: {type: "sale",- status: "active",+ status: "draft",title: "",description: "",starts_at: null,ends_at: null,product_ids: [],- products: {},+ offer_ids: [],+ offers: {},rules: {customer_group_id: [],},@@ -57,13 +58,13 @@ export const PriceListCreateForm = ({const { mutateAsync, isPending } = useCreatePriceList()const handleSubmit = form.handleSubmit(async (data) => {- const { rules, products } = data+ const { rules, offers } = dataconst rulesPayload = rules?.customer_group_id?.length? { "customer.groups.id": rules.customer_group_id.map((cg) => cg.id) }: undefined- const prices = exctractPricesFromProducts(products, regions)+ const prices = extractPricesFromOffers(offers, regions)await mutateAsync({diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsxindex 1dd3f78c4..4199e20cc 100644--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx@@ -7,7 +7,6 @@ import {IconButton,Input,RadioGroup,- Select,Text,Textarea,clx,@@ -105,53 +104,53 @@ const Root = () => {}}/><div className="flex flex-col gap-y-4">- <div className="grid grid-cols-1 gap-4 md:grid-cols-2">- <Form.Field- control={form.control}- name="title"- render={({ field }) => (- <Form.Item data-testid="price-list-details-form-title-item">- <Form.Label data-testid="price-list-details-form-title-label">{t("fields.title")}</Form.Label>- <Form.Control data-testid="price-list-details-form-title-control">- <Input {...field} data-testid="price-list-details-form-title-input" />- </Form.Control>- <Form.ErrorMessage data-testid="price-list-details-form-title-error" />- </Form.Item>- )}- />- <Form.Field- control={form.control}- name="status"- render={({ field: { onChange, ref, ...field } }) => (- <Form.Item data-testid="price-list-details-form-status-item">- <Form.Label data-testid="price-list-details-form-status-label">- {t("priceLists.fields.status.label")}- </Form.Label>- <Form.Control data-testid="price-list-details-form-status-control">- <Select- dir={direction}- {...field}- onValueChange={onChange}- data-testid="price-list-details-form-status-select"- >- <Select.Trigger ref={ref} data-testid="price-list-details-form-status-trigger">- <Select.Value data-testid="price-list-details-form-status-value" />- </Select.Trigger>- <Select.Content data-testid="price-list-details-form-status-content">- <Select.Item value="active" data-testid="price-list-details-form-status-option-active">- {t("priceLists.fields.status.options.active")}- </Select.Item>- <Select.Item value="draft" data-testid="price-list-details-form-status-option-draft">- {t("priceLists.fields.status.options.draft")}- </Select.Item>- </Select.Content>- </Select>- </Form.Control>- <Form.ErrorMessage data-testid="price-list-details-form-status-error" />- </Form.Item>- )}- />- </div>+ <Form.Field+ control={form.control}+ name="status"+ render={({ field: { onChange, ...rest } }) => (+ <Form.Item data-testid="price-list-details-form-status-item">+ <Form.Label data-testid="price-list-details-form-status-label">+ {t("priceLists.fields.status.label")}+ </Form.Label>+ <Form.Control data-testid="price-list-details-form-status-control">+ <RadioGroup+ dir={direction}+ onValueChange={onChange}+ {...rest}+ className="grid grid-cols-1 gap-4 md:grid-cols-2"+ data-testid="price-list-details-form-status-radio-group"+ >+ <RadioGroup.ChoiceBox+ value="draft"+ label={t("priceLists.fields.status.options.draft")}+ description={t("priceLists.fields.status.descriptions.draft")}+ data-testid="price-list-details-form-status-option-draft"+ />+ <RadioGroup.ChoiceBox+ value="active"+ label={t("priceLists.fields.status.options.active")}+ description={t("priceLists.fields.status.descriptions.active")}+ data-testid="price-list-details-form-status-option-active"+ />+ </RadioGroup>+ </Form.Control>+ <Form.ErrorMessage data-testid="price-list-details-form-status-error" />+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="title"+ render={({ field }) => (+ <Form.Item data-testid="price-list-details-form-title-item">+ <Form.Label data-testid="price-list-details-form-title-label">{t("fields.title")}</Form.Label>+ <Form.Control data-testid="price-list-details-form-title-control">+ <Input {...field} data-testid="price-list-details-form-title-input" />+ </Form.Control>+ <Form.ErrorMessage data-testid="price-list-details-form-title-error" />+ </Form.Item>+ )}+ /><Form.Fieldcontrol={form.control}name="description"@@ -167,20 +166,15 @@ const Root = () => {/></div><Divider />- <Form.Field- control={form.control}- name="starts_at"- render={({ field }) => (- <Form.Item data-testid="price-list-details-form-starts-at-item">- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- <div className="flex flex-col">- <Form.Label optional data-testid="price-list-details-form-starts-at-label">- {t("priceLists.fields.startsAt.label")}- </Form.Label>- <Form.Hint data-testid="price-list-details-form-starts-at-hint">- {t("priceLists.fields.startsAt.hint")}- </Form.Hint>- </div>+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <Form.Field+ control={form.control}+ name="starts_at"+ render={({ field }) => (+ <Form.Item data-testid="price-list-details-form-starts-at-item">+ <Form.Label optional data-testid="price-list-details-form-starts-at-label">+ {t("priceLists.fields.startsAt.label")}+ </Form.Label><Form.Control data-testid="price-list-details-form-starts-at-control"><DatePickergranularity="minute"@@ -189,24 +183,18 @@ const Root = () => {data-testid="price-list-details-form-starts-at-input"/></Form.Control>- </div>- <Form.ErrorMessage data-testid="price-list-details-form-starts-at-error" />- </Form.Item>- )}- />- <Divider />- <Form.Field- control={form.control}- name="ends_at"- render={({ field }) => (- <Form.Item data-testid="price-list-details-form-ends-at-item">- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- <div className="flex flex-col">- <Form.Label optional data-testid="price-list-details-form-ends-at-label">- {t("priceLists.fields.endsAt.label")}- </Form.Label>- <Form.Hint data-testid="price-list-details-form-ends-at-hint">{t("priceLists.fields.endsAt.hint")}</Form.Hint>- </div>+ <Form.ErrorMessage data-testid="price-list-details-form-starts-at-error" />+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="ends_at"+ render={({ field }) => (+ <Form.Item data-testid="price-list-details-form-ends-at-item">+ <Form.Label optional data-testid="price-list-details-form-ends-at-label">+ {t("priceLists.fields.endsAt.label")}+ </Form.Label><Form.Control data-testid="price-list-details-form-ends-at-control"><DatePickergranularity="minute"@@ -215,11 +203,11 @@ const Root = () => {data-testid="price-list-details-form-ends-at-input"/></Form.Control>- </div>- <Form.ErrorMessage data-testid="price-list-details-form-ends-at-error" />- </Form.Item>- )}- />+ <Form.ErrorMessage data-testid="price-list-details-form-ends-at-error" />+ </Form.Item>+ )}+ />+ </div><Divider /><Form.Fieldcontrol={form.control}diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsxindex 29243afc6..9dfd3779c 100644--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx@@ -1,14 +1,18 @@import { HttpTypes } from "@medusajs/types"-import { useEffect } from "react"+import { OfferDTO } from "@mercurjs/types"+import { useEffect, useMemo } from "react"import { useWatch } from "react-hook-form"import { DataGrid } from "../../../../../components/data-grid"import { useRouteModal } from "../../../../../components/modals"import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { defineTabMeta } from "../../../../../components/tabbed-form/types"+import { useOffers } from "../../../../../hooks/api/offers"import { useProducts } from "../../../../../hooks/api/products"-import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"-import { PriceListCreateProductVariantsSchema } from "../../../common/schemas"-import { isProductRow } from "../../../common/utils"+import {+ PriceListGridRow,+ usePriceListGridColumns,+} from "../../../common/hooks/use-price-list-grid-columns"+import { buildOfferGridData } from "../../../common/build-offer-grid-data"import { PricingCreateSchemaType } from "./schema"type PriceListPricesFormProps = {@@ -23,46 +27,56 @@ const Root = ({pricePreferences,}: PriceListPricesFormProps) => {const form = useTabbedForm<PricingCreateSchemaType>()+ const { setValue } = form+ const { setCloseOnEscape } = useRouteModal()- const ids = useWatch({- control: form.control,- name: "product_ids",- })+ const offerIds = useWatch({ control: form.control, name: "offer_ids" })+ const existingOffers = useWatch({ control: form.control, name: "offers" })- const existingProducts = useWatch({- control: form.control,- name: "products",- })+ const { offers: selectedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds?.length || 1,+ fields:+ "id,variant_id,product_id,seller_id,sku,seller.name,product.title,product.thumbnail",+ },+ { enabled: (offerIds?.length ?? 0) > 0 }+ )- const { products, isLoading, isError, error } = useProducts({- id: ids.map((id) => id.id),- limit: ids.length,- fields: "title,thumbnail,*variants",- })+ const productIds = useMemo(+ () =>+ Array.from(+ new Set((selectedOffers ?? []).map((o: OfferDTO) => o.product_id))+ ),+ [selectedOffers]+ )- const { setCloseOnEscape } = useRouteModal()+ const { products, isLoading } = useProducts(+ { id: productIds, limit: productIds.length || 1, fields: "id,*variants" },+ { enabled: productIds.length > 0 }+ )- const { setValue } = form+ const { gridData, variantIdByOffer } = useMemo(+ () =>+ buildOfferGridData(+ (selectedOffers ?? []) as OfferDTO[],+ products ?? []+ ),+ [selectedOffers, products]+ )+ // Seed an empty price entry per offer so the grid cells bind.useEffect(() => {- if (!isLoading && products) {- products.forEach((product) => {- if (existingProducts[product.id] || !product.variants) {- return- }-- setValue(`products.${product.id}.variants`, {- ...product.variants.reduce((variants, variant) => {- variants[variant.id] = {- currency_prices: {},- region_prices: {},- }- return variants- }, {} as PriceListCreateProductVariantsSchema),+ for (const [offerId, variantId] of Object.entries(variantIdByOffer)) {+ if (!existingOffers?.[offerId]) {+ setValue(`offers.${offerId}`, {+ variant_id: variantId,+ currency_prices: {},+ region_prices: {},})- })+ }}- }, [products, existingProducts, isLoading, setValue])+ }, [variantIdByOffer, existingOffers, setValue])const columns = usePriceListGridColumns({currencies,@@ -70,21 +84,12 @@ const Root = ({pricePreferences,})- if (isError) {- throw error- }-return (<div className="flex size-full flex-col divide-y overflow-hidden"><DataGridisLoading={isLoading}columns={columns}- data={products}- getSubRows={(row) => {- if (isProductRow(row) && row.variants) {- return row.variants- }- }}+ data={gridData as PriceListGridRow[]}state={form}onEditingChange={(editing) => setCloseOnEscape(!editing)}/>@@ -95,7 +100,7 @@ const Root = ({Root._tabMeta = defineTabMeta<PricingCreateSchemaType>({id: "price",labelKey: "priceLists.create.tabs.prices",- validationFields: ["products"],+ validationFields: ["offers"],})export const PriceListPricesForm = Rootdiff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsxindex 7767fc1c6..b26eac7eb 100644--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx@@ -1,86 +1,78 @@-import { HttpTypes } from "@medusajs/types"-import { Checkbox } from "@medusajs/ui"import { keepPreviousData } from "@tanstack/react-query"import {+ ColumnDef,OnChangeFn,RowSelectionState,- createColumnHelper,} from "@tanstack/react-table"-import { useMemo, useState } from "react"-import { useWatch } from "react-hook-form"-+import { useMemo, useRef, useState } from "react"import { useTranslation } from "react-i18next"++import { OfferDTO } from "@mercurjs/types"+import { _DataTable } from "../../../../../components/table/data-table"import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { defineTabMeta } from "../../../../../components/tabbed-form/types"-import { useProducts } from "../../../../../hooks/api/products"-import { useProductTableColumns } from "../../../../../hooks/table/columns/use-product-table-columns"-import { useProductTableFilters } from "../../../../../hooks/table/filters/use-product-table-filters"-import { useProductTableQuery } from "../../../../../hooks/table/query/use-product-table-query"+import { useOffers } from "../../../../../hooks/api/offers"import { useDataTable } from "../../../../../hooks/use-data-table"-import { PriceListCreateProductsSchema } from "../../../common/schemas"+import { useOfferTableColumns } from "../../../../offers/_components/use-offer-table-columns"+import { useOfferTableFilters } from "../../../../offers/_components/use-offer-table-filters"+import { useOfferTableQuery } from "../../../../offers/_components/use-offer-table-query"import { PricingCreateSchemaType } from "./schema"const PAGE_SIZE = 50const PREFIX = "p"-function getInitialSelection(products: { id: string }[]) {- return products.reduce((acc, curr) => {- acc[curr.id] = true-- return acc- }, {} as RowSelectionState)-}-const Root = () => {const { t } = useTranslation()const form = useTabbedForm<PricingCreateSchemaType>()- const { control, setValue } = form+ const { setValue } = form- const selectedIds = useWatch({- control,- name: "product_ids",- })+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})- const productRecords = useWatch({- control,- name: "products",- })-- const [rowSelection, setRowSelection] = useState<RowSelectionState>(- getInitialSelection(selectedIds)- )-- const { searchParams, raw } = useProductTableQuery({+ const { searchParams, raw } = useOfferTableQuery({pageSize: PAGE_SIZE,prefix: PREFIX,})- const { products, count, isLoading, isError, error } = useProducts(- searchParams,- {- placeholderData: keepPreviousData,+ // Grouped: one row per (store, product). Each row's `offer_ids` covers every+ // variant that store offers for the product, so selecting a row makes all of+ // those variants priceable. Variant→offer resolution happens in the Prices tab.+ const { offers, count, isLoading, isError, error } = useOffers(searchParams, {+ placeholderData: keepPreviousData,+ })++ // grouped row id -> { product_id, offer_ids }, kept across pages so a selection+ // can be resolved even after paginating away.+ const offerMeta = useRef<+ Record<string, { product_id: string; offer_ids: string[] }>+ >({})+ for (const offer of (offers ?? []) as OfferDTO[]) {+ offerMeta.current[offer.id] = {+ product_id: offer.product_id,+ offer_ids: offer.offer_ids ?? [offer.id],}- )+ }const updater: OnChangeFn<RowSelectionState> = (fn) => {const state = typeof fn === "function" ? fn(rowSelection) : fn- const ids = Object.keys(state)- const productRecordKeys = Object.keys(productRecords)+ const selectedRowIds = Object.keys(state).filter(+ (rowId) => offerMeta.current[rowId]+ )- const updatedRecords = productRecordKeys.reduce((acc, key) => {- if (ids.includes(key)) {- acc[key] = productRecords[key]- }+ const productIds = Array.from(+ new Set(selectedRowIds.map((id) => offerMeta.current[id].product_id))+ )- return acc- }, {} as PriceListCreateProductsSchema)+ const offerIds = Array.from(+ new Set(selectedRowIds.flatMap((id) => offerMeta.current[id].offer_ids))+ )- const update = ids.map((id) => ({ id }))-- setValue("product_ids", update, { shouldDirty: true, shouldTouch: true })-- setValue("products", updatedRecords, {+ setValue(+ "product_ids",+ productIds.map((id) => ({ id })),+ { shouldDirty: true, shouldTouch: true }+ )+ setValue("offer_ids", offerIds, {shouldDirty: true,shouldTouch: true,})@@ -89,16 +81,14 @@ const Root = () => {}const columns = useColumns()- const filters = useProductTableFilters()+ const filters = useOfferTableFilters()const { table } = useDataTable({- data: products || [],+ data: (offers ?? []) as OfferDTO[],columns,count,enablePagination: true,- enableRowSelection: (row) => {- return !!row.original.variants?.length- },+ enableRowSelection: true,getRowId: (row) => row.id,rowSelection: {state: rowSelection,@@ -124,11 +114,10 @@ const Root = () => {isLoading={isLoading}layout="fill"orderBy={[- { key: "title", label: t("fields.title") },- { key: "status", label: t("fields.status") },{ key: "created_at", label: t("fields.createdAt") },{ key: "updated_at", label: t("fields.updatedAt") },]}+ defaultOrder="-created_at"paginationsearchqueryObject={raw}@@ -140,44 +129,14 @@ const Root = () => {)}-const columnHelper = createColumnHelper<HttpTypes.AdminProduct>()-const useColumns = () => {- const base = useProductTableColumns()+ const base = useOfferTableColumns()+ // The offers list ships a leading select column + a trailing OfferActions+ // menu; keep the informative columns (select … status) and drop the actions+ // menu, which is meaningless inside the picker.return useMemo(- () => [- columnHelper.display({- id: "select",- header: ({ table }) => {- return (- <Checkbox- checked={- table.getIsSomePageRowsSelected()- ? "indeterminate"- : table.getIsAllPageRowsSelected()- }- onCheckedChange={(value) =>- table.toggleAllPageRowsSelected(!!value)- }- />- )- },- cell: ({ row }) => {- return (- <Checkbox- checked={row.getIsSelected()}- disabled={!row.getCanSelect()}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => {- e.stopPropagation()- }}- />- )- },- }),- ...base,- ],+ () => base.slice(0, -1) as ColumnDef<OfferDTO>[],[base])}diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/schema.ts b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/schema.tsindex 245deda85..fa307dc7a 100644--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/schema.ts+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/schema.ts@@ -1,6 +1,7 @@+import i18n from "i18next"import { z } from "zod"import {- PriceListCreateProductsSchema,+ PriceListCreateOffersSchema,PriceListRulesSchema,} from "../../../common/schemas"@@ -18,12 +19,19 @@ export type PricingCustomerGroupsArrayType = z.infer<export const PricingCreateSchema = z.object({type: z.enum(["sale", "override"]),status: z.enum(["draft", "active"]),- title: z.string().min(1),- description: z.string().min(1),+ title: z.string().min(1, i18n.t("priceLists.create.validation.title")),+ description: z+ .string()+ .min(1, i18n.t("priceLists.create.validation.description")),starts_at: z.date().nullish(),ends_at: z.date().nullish(),product_ids: z.array(z.object({ id: z.string() })).min(1),- products: PriceListCreateProductsSchema,+ // Offer ids selected in the picker (every variant of the chosen store+product+ // groups). The Prices tab hydrates `offers` from these.+ offer_ids: z.array(z.string()).default([]),+ // Offer-keyed prices (offer_id -> { variant_id, prices }), so the same variant+ // from two sellers stays separate.+ offers: PriceListCreateOffersSchema.default({}),rules: PriceListRulesSchema.nullish(),})@@ -50,7 +58,7 @@ export const PricingProductsFields = Object.keys() as (keyof typeof PricingProductsSchema.shape)[]export const PricingPricesSchema = PricingCreateSchema.pick({- products: true,+ offers: true,})export const PricingPricesFields = Object.keys(diff --git a/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/index.ts b/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/index.tsnew file mode 100644index 000000000..9fb81b45e--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/index.ts@@ -0,0 +1 @@+export * from "./price-list-customer-availability-form"diff --git a/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/price-list-customer-availability-form.tsx b/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/price-list-customer-availability-form.tsxnew file mode 100644index 000000000..9f65f9016--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-customer-availability/components/price-list-customer-availability-form/price-list-customer-availability-form.tsx@@ -0,0 +1,147 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { HttpTypes } from "@medusajs/types"+import { Button, Select, Text, toast } from "@medusajs/ui"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import { z } from "zod"++import { Form } from "../../../../../components/common/form"+import { Combobox } from "../../../../../components/inputs/combobox"+import { RouteDrawer, useRouteModal } from "../../../../../components/modals"+import { KeyboundForm } from "../../../../../components/utilities/keybound-form"+import { useComboboxData } from "../../../../../hooks/use-combobox-data"+import { useUpdatePriceList } from "../../../../../hooks/api/price-lists"+import { useDocumentDirection } from "../../../../../hooks/use-document-direction"+import { sdk } from "../../../../../lib/client"++type PriceListCustomerAvailabilityFormProps = {+ priceList: HttpTypes.AdminPriceList+ customerGroups: { id: string; name: string }[]+}++const PriceListCustomerAvailabilitySchema = z.object({+ customer_group_ids: z.array(z.string()).default([]),+})++export const PriceListCustomerAvailabilityForm = ({+ priceList,+ customerGroups,+}: PriceListCustomerAvailabilityFormProps) => {+ const { t } = useTranslation()+ const { handleSuccess } = useRouteModal()+ const direction = useDocumentDirection()++ const form = useForm<z.infer<typeof PriceListCustomerAvailabilitySchema>>({+ defaultValues: {+ customer_group_ids: customerGroups.map((group) => group.id),+ },+ resolver: zodResolver(PriceListCustomerAvailabilitySchema),+ })++ const groups = useComboboxData({+ queryKey: ["price-list-customer-groups"],+ queryFn: (params) => sdk.admin.customerGroups.query(params),+ getOptions: (data) =>+ data.customer_groups.map((group) => ({+ label: group.name!,+ value: group.id,+ })),+ defaultValue: customerGroups.map((group) => group.id),+ defaultValueKey: "id",+ })++ const { mutateAsync } = useUpdatePriceList(priceList.id)++ const handleSubmit = form.handleSubmit(async (values) => {+ const rules = { ...priceList.rules }++ if (values.customer_group_ids.length) {+ rules["customer.groups.id"] = values.customer_group_ids+ } else {+ delete rules["customer.groups.id"]+ }++ await mutateAsync(+ { rules },+ {+ onSuccess: () => {+ toast.success(t("priceLists.customerAvailability.edit.successToast"))+ handleSuccess()+ },+ onError: (error) => toast.error(error.message),+ }+ )+ })++ return (+ <RouteDrawer.Form form={form} data-testid="price-list-customer-availability-form">+ <RouteDrawer.Description className="sr-only">+ {t("priceLists.customerAvailability.edit.description")}+ </RouteDrawer.Description>+ <KeyboundForm+ className="flex flex-1 flex-col overflow-hidden"+ onSubmit={handleSubmit}+ >+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto" data-testid="price-list-customer-availability-form-body">+ <Text size="small" className="text-ui-fg-subtle">+ {t("priceLists.fields.customerAvailability.hint")}+ </Text>+ <Form.Field+ control={form.control}+ name="customer_group_ids"+ render={({ field: { ref, onChange, ...field } }) => (+ <Form.Item>+ <div className="bg-ui-bg-subtle border-ui-border-base flex flex-col gap-2 rounded-xl border p-2 md:flex-row">+ <Select disabled value="customer_group" dir={direction}>+ <Select.Trigger className="bg-ui-bg-base md:basis-1/3" data-testid="price-list-customer-availability-attribute">+ <Select.Value />+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="customer_group">+ {t("priceLists.fields.customerAvailability.attribute")}+ </Select.Item>+ </Select.Content>+ </Select>+ <Select disabled value="in" dir={direction}>+ <Select.Trigger className="bg-ui-bg-base md:basis-1/6" data-testid="price-list-customer-availability-operator">+ <Select.Value />+ </Select.Trigger>+ <Select.Content>+ <Select.Item value="in">{t("operators.in")}</Select.Item>+ </Select.Content>+ </Select>+ <div className="md:basis-1/2">+ <Form.Control>+ <Combobox+ {...field}+ {...groups}+ ref={ref}+ onChange={onChange}+ placeholder={t("labels.selectValues")}+ className="bg-ui-bg-base"+ data-testid="price-list-customer-availability-values"+ />+ </Form.Control>+ </div>+ </div>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ />+ </RouteDrawer.Body>+ <RouteDrawer.Footer className="shrink-0" data-testid="price-list-customer-availability-form-footer">+ <div className="flex items-center justify-end gap-x-2">+ <RouteDrawer.Close asChild>+ <Button size="small" variant="secondary" data-testid="price-list-customer-availability-form-cancel-button">+ {t("actions.cancel")}+ </Button>+ </RouteDrawer.Close>+ <Button size="small" type="submit" data-testid="price-list-customer-availability-form-save-button">+ {t("actions.save")}+ </Button>+ </div>+ </RouteDrawer.Footer>+ </KeyboundForm>+ </RouteDrawer.Form>+ )+}diff --git a/packages/admin/src/pages/price-lists/price-list-customer-availability/index.ts b/packages/admin/src/pages/price-lists/price-list-customer-availability/index.tsnew file mode 100644index 000000000..978217595--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-customer-availability/index.ts@@ -0,0 +1 @@+export { PriceListCustomerAvailability as Component } from "./price-list-customer-availability"diff --git a/packages/admin/src/pages/price-lists/price-list-customer-availability/price-list-customer-availability.tsx b/packages/admin/src/pages/price-lists/price-list-customer-availability/price-list-customer-availability.tsxnew file mode 100644index 000000000..36f9f6b49--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-customer-availability/price-list-customer-availability.tsx@@ -0,0 +1,66 @@+import { Heading } from "@medusajs/ui"+import { useTranslation } from "react-i18next"+import { useParams } from "react-router-dom"+import { RouteDrawer } from "../../../components/modals"+import { useCustomerGroups } from "../../../hooks/api/customer-groups"+import { usePriceList } from "../../../hooks/api/price-lists"+import { PriceListCustomerAvailabilityForm } from "./components/price-list-customer-availability-form"++export const PriceListCustomerAvailability = () => {+ const { t } = useTranslation()+ const { id } = useParams()++ const { price_list, isPending, isError, error } = usePriceList(id!)++ const customerGroupIds = price_list?.rules?.["customer.groups.id"] as+ | string[]+ | undefined++ const {+ customer_groups,+ isPending: isCustomerGroupsPending,+ isError: isCustomerGroupsError,+ error: customerGroupsError,+ } = useCustomerGroups(+ {+ id: customerGroupIds,+ },+ { enabled: !!customerGroupIds?.length }+ )++ const initialCustomerGroups =+ customer_groups?.map((group) => ({+ id: group.id,+ name: group.name!,+ })) || []++ const isCustomerGroupsReady = isPending+ ? false+ : !(!!customerGroupIds?.length && isCustomerGroupsPending)++ const ready = !isPending && !!price_list && isCustomerGroupsReady++ if (isError) {+ throw error+ }++ if (isCustomerGroupsError) {+ throw customerGroupsError+ }++ return (+ <RouteDrawer>+ <RouteDrawer.Header>+ <RouteDrawer.Title asChild>+ <Heading>{t("priceLists.customerAvailability.edit.header")}</Heading>+ </RouteDrawer.Title>+ </RouteDrawer.Header>+ {ready && (+ <PriceListCustomerAvailabilityForm+ priceList={price_list}+ customerGroups={initialCustomerGroups}+ />+ )}+ </RouteDrawer>+ )+}diff --git a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-configuration-section/price-list-configuration-section.tsx b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-configuration-section/price-list-configuration-section.tsxindex 54f1e9529..6872510b3 100644--- a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-configuration-section/price-list-configuration-section.tsx+++ b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-configuration-section/price-list-configuration-section.tsx@@ -7,9 +7,6 @@ import { DisplayExtensionZone } from "@mercurjs/dashboard-shared"import { ActionMenu } from "../../../../../components/common/action-menu"import { DateRangeDisplay } from "../../../../../components/common/date-range-display"-import { ListSummary } from "../../../../../components/common/list-summary"-import { Skeleton } from "../../../../../components/common/skeleton"-import { useCustomerGroups } from "../../../../../hooks/api/customer-groups"type PriceListConfigurationSectionProps = {priceList: HttpTypes.AdminPriceList@@ -23,10 +20,7 @@ export const PriceListConfigurationSection = ({return (<Container className="flex flex-col gap-y-4" data-testid="price-list-configuration-section-container"><div className="flex items-center justify-between" data-testid="price-list-configuration-section-header">- <div>- <Heading level="h2" data-testid="price-list-configuration-section-heading">{t("priceLists.configuration.header")}</Heading>- <CustomerGroupDisplay priceList={priceList} />- </div>+ <Heading level="h2" data-testid="price-list-configuration-section-heading">{t("priceLists.configuration.header")}</Heading><ActionMenugroups={[{@@ -58,46 +52,3 @@ export const PriceListConfigurationSection = ({</Container>)}--const CustomerGroupDisplay = ({- priceList,-}: {- priceList: HttpTypes.AdminPriceList-}) => {- const { t } = useTranslation()-- const customerGroupIds = priceList.rules["customer.groups.id"] as- | string[]- | undefined-- const { customer_groups, isPending, isError, } = useCustomerGroups(- {- id: customerGroupIds,- },- {- enabled: !!customerGroupIds?.length,- }- )-- if (isError || !customerGroupIds?.length) {- return null- }-- if (isPending || !customer_groups) {- return <Skeleton className="h-5 w-full max-w-48" />- }-- return (- <div className="txt-small-plus text-ui-fg-muted flex items-center gap-x-1.5">- <span className="text-ui-fg-subtle">- {t("priceLists.fields.customerAvailability.attribute")}- </span>- <span>·</span>- <ListSummary- list={customer_groups.map((group) => group.name!)}- n={1}- className="txt-small-plus text-ui-fg-muted"- />- </div>- )-}diff --git a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/index.ts b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/index.tsnew file mode 100644index 000000000..ef1b0a099--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/index.ts@@ -0,0 +1 @@+export * from "./price-list-customer-availability-section"diff --git a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/price-list-customer-availability-section.tsx b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/price-list-customer-availability-section.tsxnew file mode 100644index 000000000..56691b552--- /dev/null+++ b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-customer-availability-section/price-list-customer-availability-section.tsx@@ -0,0 +1,92 @@+import { PencilSquare } from "@medusajs/icons"+import { HttpTypes } from "@medusajs/types"+import { Badge, Container, Heading } from "@medusajs/ui"+import { useTranslation } from "react-i18next"++import { ActionMenu } from "../../../../../components/common/action-menu"+import { BadgeListSummary } from "../../../../../components/common/badge-list-summary"+import { NoRecords } from "../../../../../components/common/empty-table-content"+import { Skeleton } from "../../../../../components/common/skeleton"+import { useCustomerGroups } from "../../../../../hooks/api/customer-groups"++type PriceListCustomerAvailabilitySectionProps = {+ priceList: HttpTypes.AdminPriceList+}++export const PriceListCustomerAvailabilitySection = ({+ priceList,+}: PriceListCustomerAvailabilitySectionProps) => {+ const { t } = useTranslation()++ const customerGroupIds = priceList.rules?.["customer.groups.id"] as+ | string[]+ | undefined++ const { customer_groups, isPending, isError } = useCustomerGroups(+ { id: customerGroupIds },+ { enabled: !!customerGroupIds?.length }+ )++ const isEmpty = !customerGroupIds?.length || isError++ return (+ <Container className="p-0" data-testid="price-list-customer-availability-section-container">+ <div className="flex items-center justify-between px-6 py-4" data-testid="price-list-customer-availability-section-header">+ <Heading level="h2" data-testid="price-list-customer-availability-section-heading">+ {t("priceLists.customerAvailability.header")}+ </Heading>+ <ActionMenu+ groups={[+ {+ actions: [+ {+ label: t("actions.edit"),+ to: "customer-availability",+ icon: <PencilSquare />,+ },+ ],+ },+ ]}+ data-testid="price-list-customer-availability-section-action-menu"+ />+ </div>++ <div className="text-ui-fg-subtle flex flex-col gap-2 px-6 pb-4 pt-2" data-testid="price-list-customer-availability-section-content">+ {isEmpty ? (+ <NoRecords+ className="h-[180px]"+ icon={null}+ title={t("priceLists.customerAvailability.list.noRecordsTitle")}+ message={t("priceLists.customerAvailability.list.noRecordsMessage")}+ action={{+ to: "customer-availability",+ label: t("priceLists.customerAvailability.add"),+ }}+ dataTestId="price-list-customer-availability-section-add-button"+ />+ ) : isPending || !customer_groups ? (+ <Skeleton className="h-5 w-full max-w-48" />+ ) : (+ <div className="bg-ui-bg-subtle shadow-borders-base align-center flex justify-around rounded-md p-2">+ <div className="text-ui-fg-subtle txt-compact-xsmall flex items-center whitespace-nowrap">+ <Badge+ size="2xsmall"+ className="txt-compact-xsmall-plus tag-neutral-text mx-1 inline-block truncate"+ >+ {t("priceLists.fields.customerAvailability.attribute")}+ </Badge>+ <span className="txt-compact-2xsmall mx-1 inline-block">+ {t("operators.in")}+ </span>+ <BadgeListSummary+ inline+ className="!txt-compact-small-plus"+ list={customer_groups.map((group) => group.name!)}+ />+ </div>+ </div>+ )}+ </div>+ </Container>+ )+}diff --git a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-product-section/price-list-product-section.tsx b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-product-section/price-list-product-section.tsxindex 22b40de40..fe70e32b2 100644--- a/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-product-section/price-list-product-section.tsx+++ b/packages/admin/src/pages/price-lists/price-list-detail/components/price-list-product-section/price-list-product-section.tsx@@ -1,23 +1,35 @@-import { ExclamationCircle, PencilSquare, Plus, Trash } from "@medusajs/icons"+import {+ EllipsisHorizontal,+ ExclamationCircle,+ PencilSquare,+ Trash,+} from "@medusajs/icons"import type { HttpTypes } from "@medusajs/types"-import { Checkbox, Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"+import { Button, Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"import { keepPreviousData } from "@tanstack/react-query"-import type { RowSelectionState } from "@tanstack/react-table"-import { createColumnHelper } from "@tanstack/react-table"-import { useMemo, useState } from "react"+import {+ ColumnDef,+ createColumnHelper,+ type RowSelectionState,+} from "@tanstack/react-table"+import { useMemo, useRef, useState } from "react"import { useTranslation } from "react-i18next"-import { useNavigate } from "react-router-dom"+import { Link, useNavigate } from "react-router-dom"import { DisplayExtensionZone } from "@mercurjs/dashboard-shared"+import { OfferDTO } from "@mercurjs/types"import { ActionMenu } from "../../../../../components/common/action-menu"import { _DataTable } from "../../../../../components/table/data-table"-import { usePriceListLinkProducts } from "../../../../../hooks/api/price-lists"-import { useProducts } from "../../../../../hooks/api/products"-import { useProductTableColumns } from "../../../../../hooks/table/columns/use-product-table-columns"-import { useProductTableFilters } from "../../../../../hooks/table/filters/use-product-table-filters"-import { useProductTableQuery } from "../../../../../hooks/table/query/use-product-table-query"+import {+ usePriceList,+ usePriceListLinkProducts,+} from "../../../../../hooks/api/price-lists"+import { useOffers } from "../../../../../hooks/api/offers"import { useDataTable } from "../../../../../hooks/use-data-table"+import { useOfferTableColumns } from "../../../../offers/_components/use-offer-table-columns"+import { useOfferTableFilters } from "../../../../offers/_components/use-offer-table-filters"+import { useOfferTableQuery } from "../../../../offers/_components/use-offer-table-query"type PriceListProductSectionProps = {priceList: HttpTypes.AdminPriceList@@ -35,27 +47,84 @@ export const PriceListProductSection = ({const [rowSelection, setRowSelection] = useState<RowSelectionState>({})- const { searchParams, raw } = useProductTableQuery({+ // The detail route doesn't populate prices by default (and a price has no+ // variant_id), so fetch the price rules explicitly to get the offer ids that+ // this price list targets.+ const { price_list: pricedList } = usePriceList(priceList.id, {+ fields: "id,+prices.price_rules.attribute,+prices.price_rules.value",+ })++ const offerIds = useMemo(() => {+ const ids = new Set<string>()+ for (const price of pricedList?.prices ?? []) {+ const offerId = (price as { rules?: Record<string, string> }).rules+ ?.offer_id+ if (offerId) {+ ids.add(offerId)+ }+ }+ return Array.from(ids)+ }, [pricedList])++ const { searchParams, raw } = useOfferTableQuery({pageSize: PAGE_SIZE,prefix: PREFIX,})- const { products, count, isLoading, isError, error } = useProducts(- {- ...searchParams,- price_list_id: [priceList.id],- },+ // Fetch ALL the price list's offers (ungrouped) so the client-side grouping by+ // store+product is complete; pagination then happens over the grouped rows.+ const { group_by_seller: _grouped, ...ungroupedParams } =+ searchParams as Record<string, unknown>+ const { offers, isLoading, isError, error } = useOffers(+ { ...ungroupedParams, id: offerIds, limit: offerIds.length || 1, offset: 0 },{placeholderData: keepPreviousData,+ enabled: offerIds.length > 0,})- const filters = useProductTableFilters()+ // One row per (store, product); the Variants column shows how many of that+ // store's variants are in this price list.+ const groupedOffers = useMemo(() => {+ const groups = new Map<string, OfferDTO>()+ for (const offer of (offers ?? []) as OfferDTO[]) {+ const key = `${offer.seller_id}:${offer.product_id}`+ const existing = groups.get(key)+ if (existing) {+ existing.variant_count = (existing.variant_count ?? 0) + 1+ ;(existing.offer_ids ??= []).push(offer.id)+ } else {+ groups.set(key, {+ ...offer,+ id: key,+ variant_count: 1,+ offer_ids: [offer.id],+ })+ }+ }+ return Array.from(groups.values())+ }, [offers])++ const groupToProduct = useRef<Record<string, string>>({})+ for (const group of groupedOffers) {+ groupToProduct.current[group.id] = group.product_id+ }++ const selectedProductIds = () =>+ Array.from(+ new Set(+ Object.keys(rowSelection)+ .map((groupId) => groupToProduct.current[groupId])+ .filter(Boolean)+ )+ )+const columns = useColumns(priceList)+ const filters = useOfferTableFilters()const { mutateAsync } = usePriceListLinkProducts(priceList.id)const { table } = useDataTable({- data: products || [],- count,+ data: groupedOffers,+ count: groupedOffers.length,columns,enablePagination: true,enableRowSelection: true,@@ -69,12 +138,14 @@ export const PriceListProductSection = ({})const handleDelete = async () => {+ const productIds = selectedProductIds()+const res = await prompt({title: t("general.areYouSure"),description: t("priceLists.products.delete.confirmation", {- count: Object.keys(rowSelection).length,+ count: productIds.length,}),- confirmText: t("actions.delete"),+ confirmText: t("actions.remove"),cancelText: t("actions.cancel"),})@@ -83,29 +154,23 @@ export const PriceListProductSection = ({}mutateAsync(- {- remove: Object.keys(rowSelection),- },+ { remove: productIds },{onSuccess: () => {toast.success(t("priceLists.products.delete.successToast", {- count: Object.keys(rowSelection).length,+ count: productIds.length,}))-setRowSelection({})},- onError: (e) => {- toast.error(e.message)- },+ onError: (e) => toast.error(e.message),})}const handleEdit = async () => {- const ids = Object.keys(rowSelection).join(",")-+ const ids = selectedProductIds().join(",")navigate(`products/edit?ids[]=${ids}`)}@@ -113,27 +178,31 @@ export const PriceListProductSection = ({<Container className="divide-y p-0" data-testid="price-list-product-section-container"><div className="flex items-center justify-between px-6 py-4" data-testid="price-list-product-section-header"><Heading data-testid="price-list-product-section-heading">{t("priceLists.products.header")}</Heading>- <ActionMenu- groups={[- {- actions: [- {- label: t("priceLists.products.actions.addProducts"),- to: "products/add",- icon: <Plus />,- },- {- label: t("priceLists.products.actions.editPrices"),- to: "products/edit",- icon: <PencilSquare />,- disabled: count === 0,- disabledTooltip: t("priceLists.products.actions.editPricesDisabled"),- },- ],- },- ]}- data-testid="price-list-product-section-action-menu"- />+ <div className="flex items-center gap-x-2">+ <ActionMenu+ groups={[+ {+ actions: [+ {+ label: t("priceLists.products.actions.editPrices"),+ to: "products/edit",+ icon: <PencilSquare />,+ disabled: groupedOffers.length === 0,+ disabledTooltip: t("priceLists.products.actions.editPricesDisabled"),+ },+ ],+ },+ ]}+ data-testid="price-list-product-section-action-menu"+ >+ <Button size="small" variant="secondary" className="h-7 w-7 p-0" data-testid="price-list-product-section-action-menu-trigger">+ <EllipsisHorizontal />+ </Button>+ </ActionMenu>+ <Button size="small" variant="secondary" asChild data-testid="price-list-product-section-add-button">+ <Link to="products/add">{t("actions.add")}</Link>+ </Button>+ </div></div>{isError ? (<div className="flex items-center gap-x-2 px-6 py-4" data-testid="price-list-product-section-error">@@ -143,52 +212,48 @@ export const PriceListProductSection = ({</Text></div>) : (- <_DataTable- table={table}- filters={filters}- columns={columns}- count={count}- pageSize={PAGE_SIZE}- isLoading={isLoading}- navigateTo={(row) => `/products/${row.original.id}`}- orderBy={[- { key: "title", label: t("fields.title") },- { key: "created_at", label: t("fields.createdAt") },- { key: "updated_at", label: t("fields.updatedAt") },- ]}- commands={[- {- action: handleEdit,- label: t("actions.edit"),- shortcut: "e",- },- {- action: handleDelete,- label: t("actions.delete"),- shortcut: "d",- },- ]}- pagination- search- prefix={PREFIX}- queryObject={raw}- data-testid="price-list-product-section-table"- />+ <_DataTable+ table={table}+ filters={filters}+ columns={columns}+ count={groupedOffers.length}+ pageSize={PAGE_SIZE}+ isLoading={isLoading}+ navigateTo={(row) => `/products/${row.original.product_id}`}+ orderBy={[+ { key: "created_at", label: t("fields.createdAt") },+ { key: "updated_at", label: t("fields.updatedAt") },+ ]}+ defaultOrder="-created_at"+ commands={[+ {+ action: handleEdit,+ label: t("priceLists.products.actions.editPrices"),+ shortcut: "e",+ },+ {+ action: handleDelete,+ label: t("actions.remove"),+ shortcut: "r",+ },+ ]}+ pagination+ search+ prefix={PREFIX}+ queryObject={raw}+ data-testid="price-list-product-section-table"+ />)}- <DisplayExtensionZone- model="price_list"- zone="products"- data={priceList}- />+ <DisplayExtensionZone model="price_list" zone="products" data={priceList} /></Container>)}-const ProductRowAction = ({- product,+const OfferRowAction = ({+ offer,priceList,}: {- product: HttpTypes.AdminProduct+ offer: OfferDTOpriceList: HttpTypes.AdminPriceList}) => {const { t } = useTranslation()@@ -198,10 +263,8 @@ const ProductRowAction = ({const handleDelete = async () => {const res = await prompt({title: t("general.areYouSure"),- description: t("priceLists.products.delete.confirmation", {- count: 1,- }),- confirmText: t("actions.delete"),+ description: t("priceLists.products.delete.confirmation", { count: 1 }),+ confirmText: t("actions.remove"),cancelText: t("actions.cancel"),})@@ -210,20 +273,14 @@ const ProductRowAction = ({}mutateAsync(- {- remove: [product.id],- },+ { remove: [offer.product_id] },{onSuccess: () => {toast.success(- t("priceLists.products.delete.successToast", {- count: 1,- })+ t("priceLists.products.delete.successToast", { count: 1 }))},- onError: (e) => {- toast.error(e.message)- },+ onError: (e) => toast.error(e.message),})}@@ -236,7 +293,7 @@ const ProductRowAction = ({{icon: <PencilSquare />,label: t("priceLists.products.actions.editPrices"),- to: `products/edit?ids[]=${product.id}`,+ to: `products/edit?ids[]=${offer.product_id}`,},],},@@ -254,48 +311,20 @@ const ProductRowAction = ({)}-const columnHelper = createColumnHelper<HttpTypes.AdminProduct>()+const columnHelper = createColumnHelper<OfferDTO>()const useColumns = (priceList: HttpTypes.AdminPriceList) => {- const base = useProductTableColumns()+ const base = useOfferTableColumns()return useMemo(() => [- columnHelper.display({- id: "select",- header: ({ table }) => {- return (- <Checkbox- checked={- table.getIsSomePageRowsSelected()- ? "indeterminate"- : table.getIsAllPageRowsSelected()- }- onCheckedChange={(value) =>- table.toggleAllPageRowsSelected(!!value)- }- />- )- },- cell: ({ row }) => {- return (- <Checkbox- checked={row.getIsSelected()}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => {- e.stopPropagation()- }}- />- )- },- }),- ...base,+ ...(base.slice(0, -1) as ColumnDef<OfferDTO>[]),columnHelper.display({id: "actions",cell: ({ row }) => (- <ProductRowAction product={row.original} priceList={priceList} />+ <OfferRowAction offer={row.original} priceList={priceList} />),- }),+ }) as ColumnDef<OfferDTO>,],[base, priceList])diff --git a/packages/admin/src/pages/price-lists/price-list-detail/loader.ts b/packages/admin/src/pages/price-lists/price-list-detail/loader.tsindex b6ad528e1..97a42e859 100644--- a/packages/admin/src/pages/price-lists/price-list-detail/loader.ts+++ b/packages/admin/src/pages/price-lists/price-list-detail/loader.ts@@ -5,7 +5,7 @@ import { sdk } from "../../../lib/client"import { queryClient } from "../../../lib/query-client"const pricingDetailQuery = (id: string) => {- const query = getLinkQuery("price_list")+ const query = getLinkQuery("price_list", "+prices.id")return {queryKey: priceListsQueryKeys.detail(id, query),diff --git a/packages/admin/src/pages/price-lists/price-list-detail/price-list-detail.tsx b/packages/admin/src/pages/price-lists/price-list-detail/price-list-detail.tsxindex cf524e305..c771bda56 100644--- a/packages/admin/src/pages/price-lists/price-list-detail/price-list-detail.tsx+++ b/packages/admin/src/pages/price-lists/price-list-detail/price-list-detail.tsx@@ -7,13 +7,14 @@ import { TwoColumnPageSkeleton } from "../../../components/common/skeleton"import { TwoColumnPage } from "../../../components/layout/pages"import { usePriceList } from "../../../hooks/api/price-lists"import { PriceListConfigurationSection } from "./components/price-list-configuration-section"+import { PriceListCustomerAvailabilitySection } from "./components/price-list-customer-availability-section"import { PriceListGeneralSection } from "./components/price-list-general-section"import { PriceListProductSection } from "./components/price-list-product-section"const Root = ({ children }: { children?: ReactNode }) => {const { id } = useParams()- const linkQuery = useLinkQuery("price_list")+ const linkQuery = useLinkQuery("price_list", "+prices.id")const { price_list, isLoading, isError, error } = usePriceList(id!, linkQuery)if (isLoading || !price_list) {@@ -35,6 +36,7 @@ const Root = ({ children }: { children?: ReactNode }) => {<TwoColumnPage.Main><WidgetZone id="price-lists.detail.main" data={price_list}><PriceListGeneralSection priceList={price_list} />+ <PriceListCustomerAvailabilitySection priceList={price_list} /><PriceListProductSection priceList={price_list} /></WidgetZone></TwoColumnPage.Main>@@ -51,6 +53,7 @@ export const PriceListDetailPage = Object.assign(Root, {Main: TwoColumnPage.Main,Sidebar: TwoColumnPage.Sidebar,MainGeneralSection: PriceListGeneralSection,+ MainCustomerAvailabilitySection: PriceListCustomerAvailabilitySection,MainProductSection: PriceListProductSection,SidebarConfigurationSection: PriceListConfigurationSection,})diff --git a/packages/admin/src/pages/price-lists/price-list-edit/components/price-list-edit-form/edit-price-list-form.tsx b/packages/admin/src/pages/price-lists/price-list-edit/components/price-list-edit-form/edit-price-list-form.tsxindex b9ea5435d..77053c380 100644--- a/packages/admin/src/pages/price-lists/price-list-edit/components/price-list-edit-form/edit-price-list-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-edit/components/price-list-edit-form/edit-price-list-form.tsx@@ -1,12 +1,5 @@import { HttpTypes } from "@medusajs/types"-import {- Button,- Input,- RadioGroup,- Select,- Textarea,- toast,-} from "@medusajs/ui"+import { Button, Input, RadioGroup, Textarea, toast } from "@medusajs/ui"import { useTranslation } from "react-i18next"import { z } from "zod"@@ -30,7 +23,7 @@ const PriceListEditSchema = z.object({status: z.nativeEnum(PriceListStatus),type: z.nativeEnum(PriceListType),title: z.string().min(1),- description: z.string().min(1),+ description: z.string().optional(),})export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {@@ -53,7 +46,13 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {const { mutateAsync, isPending } = useUpdatePriceList(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- await mutateAsync(values, {+ const { additional_data, ...rest } = values+ const payload =+ additional_data && Object.keys(additional_data).length+ ? { ...rest, additional_data }+ : rest++ await mutateAsync(payload, {onSuccess: ({ price_list }) => {toast.success(t("priceLists.edit.successToast", {@@ -119,62 +118,67 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {}}/><div className="flex flex-col gap-y-4">- <Form.Field- control={form.control}- name="title"- render={({ field }) => {- return (- <Form.Item data-testid="price-list-edit-form-title-item">- <Form.Label data-testid="price-list-edit-form-title-label">{t("fields.title")}</Form.Label>- <Form.Control data-testid="price-list-edit-form-title-control">- <Input {...field} data-testid="price-list-edit-form-title-input" />- </Form.Control>- <Form.ErrorMessage data-testid="price-list-edit-form-title-error" />- </Form.Item>- )- }}- /><Form.Fieldcontrol={form.control}name="status"- render={({ field: { onChange, ref, ...field } }) => {+ render={({ field: { onChange, ...rest } }) => {return (<Form.Item data-testid="price-list-edit-form-status-item"><Form.Label data-testid="price-list-edit-form-status-label">{t("priceLists.fields.status.label")}</Form.Label><Form.Control data-testid="price-list-edit-form-status-control">- <Select- dir={direction}- {...field}+ <RadioGroup+ dir={direction}onValueChange={onChange}- data-testid="price-list-edit-form-status-select"+ {...rest}+ data-testid="price-list-edit-form-status-radio-group">- <Select.Trigger ref={ref}>- <Select.Value />- </Select.Trigger>- <Select.Content>- <Select.Item value={PriceListStatus.ACTIVE} data-testid="price-list-edit-form-status-option-active">- {t("priceLists.fields.status.options.active")}- </Select.Item>- <Select.Item value={PriceListStatus.DRAFT} data-testid="price-list-edit-form-status-option-draft">- {t("priceLists.fields.status.options.draft")}- </Select.Item>- </Select.Content>- </Select>+ <RadioGroup.ChoiceBox+ value={PriceListStatus.DRAFT}+ label={t("priceLists.fields.status.options.draft")}+ description={t(+ "priceLists.fields.status.descriptions.draft"+ )}+ data-testid="price-list-edit-form-status-option-draft"+ />+ <RadioGroup.ChoiceBox+ value={PriceListStatus.ACTIVE}+ label={t("priceLists.fields.status.options.active")}+ description={t(+ "priceLists.fields.status.descriptions.active"+ )}+ data-testid="price-list-edit-form-status-option-active"+ />+ </RadioGroup></Form.Control><Form.ErrorMessage data-testid="price-list-edit-form-status-error" /></Form.Item>)}}/>+ <Form.Field+ control={form.control}+ name="title"+ render={({ field }) => {+ return (+ <Form.Item data-testid="price-list-edit-form-title-item">+ <Form.Label data-testid="price-list-edit-form-title-label">{t("fields.title")}</Form.Label>+ <Form.Control data-testid="price-list-edit-form-title-control">+ <Input {...field} data-testid="price-list-edit-form-title-input" />+ </Form.Control>+ <Form.ErrorMessage data-testid="price-list-edit-form-title-error" />+ </Form.Item>+ )+ }}+ /><Form.Fieldcontrol={form.control}name="description"render={({ field }) => {return (<Form.Item data-testid="price-list-edit-form-description-item">- <Form.Label data-testid="price-list-edit-form-description-label">{t("fields.description")}</Form.Label>+ <Form.Label optional data-testid="price-list-edit-form-description-label">{t("fields.description")}</Form.Label><Form.Control data-testid="price-list-edit-form-description-control"><Textarea {...field} data-testid="price-list-edit-form-description-input" /></Form.Control>diff --git a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-data-table.tsx b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-data-table.tsxindex 131788521..8045b7e3b 100644--- a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-data-table.tsx+++ b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-data-table.tsx@@ -1,3 +1,4 @@+import { CurrencyDollar } from "@medusajs/icons"import { HttpTypes } from "@medusajs/types"import { keepPreviousData } from "@tanstack/react-query"import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"@@ -46,7 +47,7 @@ export const PriceListListDataTable = () => {const { searchParams, raw } = usePricingTableQuery({pageSize: PAGE_SIZE,})- const linkQuery = useLinkQuery("price_list")+ const linkQuery = useLinkQuery("price_list", "+seller.name,+prices.id")const { price_lists, count, isLoading, isError, error } = usePriceLists({ ...searchParams, ...linkQuery },{@@ -82,14 +83,23 @@ export const PriceListListDataTable = () => {filters={filters}orderBy={[{ key: "title", label: t("fields.title") },- { key: "status", label: t("fields.status") },{ key: "created_at", label: t("fields.createdAt") },{ key: "updated_at", label: t("fields.updatedAt") },]}+ defaultOrder="title"queryObject={raw}pageSize={PAGE_SIZE}navigateTo={(row) => row.original.id}isLoading={isLoading}+ noRecords={{+ icon: <CurrencyDollar className="text-ui-fg-subtle" />,+ title: t("priceLists.list.noRecords.title"),+ message: t("priceLists.list.noRecords.message"),+ action: {+ to: "create",+ label: t("actions.create"),+ },+ }}paginationsearch/>diff --git a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-header.tsx b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-header.tsxindex f79fb0f69..47e2c7fdf 100644--- a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-header.tsx+++ b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/price-list-list-header.tsx@@ -1,5 +1,5 @@import { ReactNode, Children } from "react"-import { Button, Heading, Text } from "@medusajs/ui"+import { Button, Heading } from "@medusajs/ui"import { useTranslation } from "react-i18next"import { Link } from "react-router-dom"@@ -8,9 +8,6 @@ export const PriceListListTitle = () => {return (<div><Heading>{t("priceLists.domain")}</Heading>- <Text className="text-ui-fg-subtle" size="small">- {t("priceLists.subtitle")}- </Text></div>)}diff --git a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-columns.tsx b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-columns.tsxindex 0a3bb588a..7dee6f130 100644--- a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-columns.tsx+++ b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-columns.tsx@@ -10,7 +10,11 @@ import {} from "../../../../../components/table/table-cells/common/text-cell"import { getPriceListStatus } from "../../../common/utils"-const columnHelper = createColumnHelper<HttpTypes.AdminPriceList>()+type PriceListWithSeller = HttpTypes.AdminPriceList & {+ seller?: { name?: string | null } | null+}++const columnHelper = createColumnHelper<PriceListWithSeller>()export const usePricingTableColumns = () => {const { t } = useTranslation()@@ -21,18 +25,44 @@ export const usePricingTableColumns = () => {header: () => <TextHeader text={t("fields.title")} />,cell: (info) => info.getValue(),}),+ columnHelper.accessor("type", {+ header: () => <TextHeader text={t("priceLists.fields.type.label")} />,+ cell: (info) => (+ <TextCell+ text={+ info.getValue() === "sale"+ ? t("priceLists.fields.type.options.sale.label")+ : t("priceLists.fields.type.options.override.label")+ }+ />+ ),+ }),+ columnHelper.accessor("prices", {+ header: () => (+ <TextHeader text={t("priceLists.fields.priceOverrides.header")} />+ ),+ cell: (info) => <TextCell text={`${info.getValue()?.length || "-"}`} />,+ }),+ columnHelper.display({+ id: "owner",+ header: () => <TextHeader text={t("priceLists.fields.owner.label")} />,+ cell: ({ row }) => (+ <TextCell+ text={+ row.original.seller?.name ||+ t("priceLists.fields.owner.marketplace")+ }+ />+ ),+ }),columnHelper.accessor("status", {- header: t("priceLists.fields.status.label"),+ header: () => <TextHeader text={t("priceLists.fields.status.label")} />,cell: ({ row }) => {const { color, text } = getPriceListStatus(t, row.original)return <StatusCell color={color}>{text}</StatusCell>},}),- columnHelper.accessor("prices", {- header: t("priceLists.fields.priceOverrides.header"),- cell: (info) => <TextCell text={`${info.getValue()?.length || "-"}`} />,- }),],[t])diff --git a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-filters.tsx b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-filters.tsxindex ed84ef4f8..d0548a0fb 100644--- a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-filters.tsx+++ b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-filters.tsx@@ -5,8 +5,38 @@ export const usePricingTableFilters = () => {const { t } = useTranslation()const filters: Filter[] = [- { label: t("fields.createdAt"), key: "starts_at", type: "date" },- { label: t("fields.updatedAt"), key: "ends_at", type: "date" },+ {+ label: t("priceLists.fields.type.label"),+ key: "type",+ type: "select",+ options: [+ {+ label: t("priceLists.fields.type.options.sale.label"),+ value: "sale",+ },+ {+ label: t("priceLists.fields.type.options.override.label"),+ value: "override",+ },+ ],+ },+ {+ label: t("priceLists.fields.status.label"),+ key: "status",+ type: "select",+ options: [+ {+ label: t("priceLists.fields.status.options.active"),+ value: "active",+ },+ {+ label: t("priceLists.fields.status.options.draft"),+ value: "draft",+ },+ ],+ },+ { label: t("fields.createdAt"), key: "created_at", type: "date" },+ { label: t("fields.updatedAt"), key: "updated_at", type: "date" },]return filtersdiff --git a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-query.tsx b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-query.tsxindex 2202259c6..abc56cd65 100644--- a/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-query.tsx+++ b/packages/admin/src/pages/price-lists/price-list-list/components/price-list-list-table/use-pricing-table-query.tsx@@ -9,17 +9,22 @@ export const usePricingTableQuery = ({prefix?: string}) => {const raw = useQueryParams(- ["offset", "q", "order", "status", "starts_at", "ends_at"],+ ["offset", "q", "order", "type", "status", "created_at", "updated_at"],prefix)- const searchParams: HttpTypes.AdminPriceListListParams = {+ const searchParams: HttpTypes.AdminPriceListListParams & {+ type?: string[]+ created_at?: Record<string, string>+ updated_at?: Record<string, string>+ } = {limit: pageSize,offset: raw.offset ? Number(raw.offset) : 0,order: raw.order,+ type: raw.type?.split(","),status: raw.status?.split(",") as PriceListStatus[],- starts_at: raw.starts_at ? JSON.parse(raw.starts_at) : undefined,- ends_at: raw.ends_at ? JSON.parse(raw.ends_at) : undefined,+ created_at: raw.created_at ? JSON.parse(raw.created_at) : undefined,+ updated_at: raw.updated_at ? JSON.parse(raw.updated_at) : undefined,q: raw.q,}diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsxindex 408adea9f..4b441b0a4 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx@@ -9,7 +9,7 @@ import { z } from "zod"import { useRouteModal } from "../../../../../components/modals"import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { useBatchPriceListPrices } from "../../../../../hooks/api/price-lists"-import { exctractPricesFromProducts } from "../../../common/utils"+import { extractPricesFromOffers } from "../../../common/utils"import { PriceListPricesAddPricesForm } from "./price-list-prices-add-prices-form"import { PriceListPricesAddProductIdsForm } from "./price-list-prices-add-product-ids-form"import { PriceListPricesAddSchema } from "./schema"@@ -40,8 +40,9 @@ export const PriceListPricesAddForm = ({const form = useForm<PriceListPricesAddSchemaType>({defaultValues: {- products: {},+ offers: {},product_ids: [],+ offer_ids: [],...extraDefaults,} as PriceListPricesAddSchemaType,resolver: zodResolver(schema ?? PriceListPricesAddSchema),@@ -50,9 +51,9 @@ export const PriceListPricesAddForm = ({const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- const { products } = values+ const { offers } = values- const prices = exctractPricesFromProducts(products, regions)+ const prices = extractPricesFromOffers(offers, regions)await mutateAsync({diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsxindex bd46fceb4..6f4493ba1 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx@@ -1,15 +1,19 @@import { HttpTypes } from "@medusajs/types"-import { useEffect } from "react"+import { OfferDTO } from "@mercurjs/types"+import { useEffect, useMemo } from "react"import { useWatch } from "react-hook-form"import { DataGrid } from "../../../../../components/data-grid"import { useRouteModal } from "../../../../../components/modals"import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { defineTabMeta } from "../../../../../components/tabbed-form/types"+import { useOffers } from "../../../../../hooks/api/offers"import { useProducts } from "../../../../../hooks/api/products"-import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"-import { PriceListCreateProductVariantsSchema } from "../../../common/schemas"-import { isProductRow } from "../../../common/utils"+import { buildOfferGridData } from "../../../common/build-offer-grid-data"+import {+ PriceListGridRow,+ usePriceListGridColumns,+} from "../../../common/hooks/use-price-list-grid-columns"import { PriceListPricesAddSchema } from "./schema"type PriceListPricesAddPricesFormProps = {@@ -24,46 +28,55 @@ const Root = ({pricePreferences,}: PriceListPricesAddPricesFormProps) => {const form = useTabbedForm<PriceListPricesAddSchema>()+ const { setValue } = form+ const { setCloseOnEscape } = useRouteModal()- const ids = useWatch({- control: form.control,- name: "product_ids",- })+ const offerIds = useWatch({ control: form.control, name: "offer_ids" })+ const existingOffers = useWatch({ control: form.control, name: "offers" })- const existingProducts = useWatch({- control: form.control,- name: "products",- })+ const { offers: selectedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds?.length || 1,+ fields:+ "id,variant_id,product_id,seller_id,sku,seller.name,product.title,product.thumbnail",+ },+ { enabled: (offerIds?.length ?? 0) > 0 }+ )- const { products, isLoading, isError, error } = useProducts({- id: ids.map((id) => id.id),- limit: ids.length,- fields: "title,thumbnail,*variants",- })+ const productIds = useMemo(+ () =>+ Array.from(+ new Set((selectedOffers ?? []).map((o: OfferDTO) => o.product_id))+ ),+ [selectedOffers]+ )- const { setValue } = form+ const { products, isLoading } = useProducts(+ { id: productIds, limit: productIds.length || 1, fields: "id,*variants" },+ { enabled: productIds.length > 0 }+ )- const { setCloseOnEscape } = useRouteModal()+ const { gridData, variantIdByOffer } = useMemo(+ () =>+ buildOfferGridData(+ (selectedOffers ?? []) as OfferDTO[],+ products ?? []+ ),+ [selectedOffers, products]+ )useEffect(() => {- if (!isLoading && products) {- products.forEach((product) => {- if (existingProducts[product.id] || !product.variants) {- return- }-- setValue(`products.${product.id}.variants`, {- ...product.variants.reduce((variants, variant) => {- variants[variant.id] = {- currency_prices: {},- region_prices: {},- }- return variants- }, {} as PriceListCreateProductVariantsSchema),+ for (const [offerId, variantId] of Object.entries(variantIdByOffer)) {+ if (!existingOffers?.[offerId]) {+ setValue(`offers.${offerId}`, {+ variant_id: variantId,+ currency_prices: {},+ region_prices: {},})- })+ }}- }, [products, existingProducts, isLoading, setValue])+ }, [variantIdByOffer, existingOffers, setValue])const columns = usePriceListGridColumns({currencies,@@ -71,21 +84,12 @@ const Root = ({pricePreferences,})- if (isError) {- throw error- }-return (<div className="flex size-full flex-col divide-y overflow-hidden"><DataGridisLoading={isLoading}columns={columns}- data={products}- getSubRows={(row) => {- if (isProductRow(row) && row.variants) {- return row.variants- }- }}+ data={gridData as PriceListGridRow[]}state={form}onEditingChange={(editing) => setCloseOnEscape(!editing)}/>@@ -96,7 +100,7 @@ const Root = ({Root._tabMeta = defineTabMeta<PriceListPricesAddSchema>({id: "price",labelKey: "priceLists.create.tabs.prices",- validationFields: ["products"],+ validationFields: ["offers"],})export const PriceListPricesAddPricesForm = Rootdiff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsxindex a696504c2..164f4aace 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx@@ -2,22 +2,25 @@ import { HttpTypes } from "@medusajs/types"import { Checkbox, Tooltip } from "@medusajs/ui"import { keepPreviousData } from "@tanstack/react-query"import {+ ColumnDef,OnChangeFn,RowSelectionState,createColumnHelper,} from "@tanstack/react-table"-import { useMemo, useState } from "react"-import { useWatch } from "react-hook-form"+import { useMemo, useRef, useState } from "react"import { useTranslation } from "react-i18next"++import { OfferDTO } from "@mercurjs/types"+import { _DataTable } from "../../../../../components/table/data-table"import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"import { defineTabMeta } from "../../../../../components/tabbed-form/types"-import { useProducts } from "../../../../../hooks/api/products"-import { useProductTableColumns } from "../../../../../hooks/table/columns/use-product-table-columns"-import { useProductTableFilters } from "../../../../../hooks/table/filters/use-product-table-filters"-import { useProductTableQuery } from "../../../../../hooks/table/query/use-product-table-query"+import { useOffers } from "../../../../../hooks/api/offers"+import { usePriceList } from "../../../../../hooks/api/price-lists"import { useDataTable } from "../../../../../hooks/use-data-table"-import { PriceListCreateProductsSchema } from "../../../common/schemas"+import { useOfferTableColumns } from "../../../../offers/_components/use-offer-table-columns"+import { useOfferTableFilters } from "../../../../offers/_components/use-offer-table-filters"+import { useOfferTableQuery } from "../../../../offers/_components/use-offer-table-query"import { PriceListPricesAddSchema } from "./schema"type PriceListPricesAddProductIdsFormProps = {@@ -27,76 +30,74 @@ type PriceListPricesAddProductIdsFormProps = {const PAGE_SIZE = 50const PREFIX = "p"-function getInitialSelection(products: { id: string }[]) {- return products.reduce((acc, curr) => {- acc[curr.id] = true-- return acc- }, {} as RowSelectionState)-}--const Root = ({- priceList,-}: PriceListPricesAddProductIdsFormProps) => {+const Root = ({ priceList }: PriceListPricesAddProductIdsFormProps) => {const { t } = useTranslation()const form = useTabbedForm<PriceListPricesAddSchema>()- const { control, setValue } = form+ const { setValue } = form- const variantIdMap = useMemo(() => {- return (priceList.prices ?? []).reduce(- (acc, curr) => {- acc[curr.variant_id] = true-- return acc- },- {} as Record<string, boolean>- )- }, [priceList.prices])-- const selectedIds = useWatch({- control,- name: "product_ids",+ // Offers already in this price list are disabled so they can't be re-added.+ const { price_list: pricedList } = usePriceList(priceList.id, {+ fields: "id,+prices.price_rules.attribute,+prices.price_rules.value",})+ const existingOfferIds = useMemo(() => {+ const set = new Set<string>()+ for (const price of pricedList?.prices ?? []) {+ const offerId = (price as { rules?: Record<string, string> }).rules+ ?.offer_id+ if (offerId) {+ set.add(offerId)+ }+ }+ return set+ }, [pricedList])- const productRecords = useWatch({- control,- name: "products",- })+ const isAlreadyAdded = (row: OfferDTO) =>+ (row.offer_ids ?? [row.id]).some((id) => existingOfferIds.has(id))- const [rowSelection, setRowSelection] = useState<RowSelectionState>(- getInitialSelection(selectedIds)- )+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})- const { searchParams, raw } = useProductTableQuery({+ const { searchParams, raw } = useOfferTableQuery({pageSize: PAGE_SIZE,prefix: PREFIX,})- const { products, count, isLoading, isError, error } = useProducts(- searchParams,- {- placeholderData: keepPreviousData,+ // Grouped: one row per (store, product). Each row's `offer_ids` covers every+ // variant that store offers for the product; variant→offer resolution happens+ // in the Prices tab.+ const { offers, count, isLoading, isError, error } = useOffers(searchParams, {+ placeholderData: keepPreviousData,+ })++ const offerMeta = useRef<+ Record<string, { product_id: string; offer_ids: string[] }>+ >({})+ for (const offer of (offers ?? []) as OfferDTO[]) {+ offerMeta.current[offer.id] = {+ product_id: offer.product_id,+ offer_ids: offer.offer_ids ?? [offer.id],}- )+ }const updater: OnChangeFn<RowSelectionState> = (fn) => {const state = typeof fn === "function" ? fn(rowSelection) : fn- const ids = Object.keys(state)- const productRecordKeys = Object.keys(productRecords)-- const updatedRecords = productRecordKeys.reduce((acc, key) => {- if (ids.includes(key)) {- acc[key] = productRecords[key]- }-- return acc- }, {} as PriceListCreateProductsSchema)+ const selectedRowIds = Object.keys(state).filter(+ (rowId) => offerMeta.current[rowId]+ )- const update = ids.map((id) => ({ id }))+ const productIds = Array.from(+ new Set(selectedRowIds.map((id) => offerMeta.current[id].product_id))+ )- setValue("product_ids", update, { shouldDirty: true, shouldTouch: true })+ const offerIds = Array.from(+ new Set(selectedRowIds.flatMap((id) => offerMeta.current[id].offer_ids))+ )- setValue("products", updatedRecords, {+ setValue(+ "product_ids",+ productIds.map((id) => ({ id })),+ { shouldDirty: true, shouldTouch: true }+ )+ setValue("offer_ids", offerIds, {shouldDirty: true,shouldTouch: true,})@@ -104,20 +105,15 @@ const Root = ({setRowSelection(state)}- const columns = useColumns()- const filters = useProductTableFilters()+ const columns = useColumns(t)+ const filters = useOfferTableFilters()const { table } = useDataTable({- data: products || [],+ data: (offers ?? []) as OfferDTO[],columns,count,enablePagination: true,- enableRowSelection: (row) => {- return (- !!row.original.variants?.length &&- !row.original.variants?.some((v) => variantIdMap[v.id])- )- },+ enableRowSelection: (row) => !isAlreadyAdded(row.original),getRowId: (row) => row.id,rowSelection: {state: rowSelection,@@ -125,9 +121,6 @@ const Root = ({},pageSize: PAGE_SIZE,prefix: PREFIX,- meta: {- variantIdMap,- },})if (isError) {@@ -146,11 +139,10 @@ const Root = ({isLoading={isLoading}layout="fill"orderBy={[- { key: "title", label: t("fields.title") },- { key: "status", label: t("fields.status") },{ key: "created_at", label: t("fields.createdAt") },{ key: "updated_at", label: t("fields.updatedAt") },]}+ defaultOrder="-created_at"paginationsearchqueryObject={raw}@@ -159,75 +151,51 @@ const Root = ({)}-const columnHelper = createColumnHelper<HttpTypes.AdminProduct>()--const useColumns = () => {- const { t } = useTranslation()- const base = useProductTableColumns()-- return useMemo(- () => [- columnHelper.display({- id: "select",- header: ({ table }) => {- return (- <Checkbox- checked={- table.getIsSomePageRowsSelected()- ? "indeterminate"- : table.getIsAllPageRowsSelected()- }- onCheckedChange={(value) =>- table.toggleAllPageRowsSelected(!!value)- }- />- )- },- cell: ({ row, table }) => {- const { variantIdMap } = table.options.meta as {- variantIdMap: Record<string, boolean>+const columnHelper = createColumnHelper<OfferDTO>()++const useColumns = (t: (key: string) => string) => {+ const base = useOfferTableColumns()++ return useMemo(() => {+ // Replace the offer list's select column with one that disables rows+ // already in the price list, and drop the trailing actions column.+ const selectColumn = columnHelper.display({+ id: "select",+ header: ({ table }) => (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()}-- const isPreselected = row.original.variants?.some(- (v) => variantIdMap[v.id]- )- const isDisabled = !row.getCanSelect() || isPreselected- const isChecked = row.getIsSelected() || isPreselected-- const Component = (- <Checkbox- checked={isChecked}- disabled={isDisabled}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => {- e.stopPropagation()- }}- />+ onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}+ />+ ),+ cell: ({ row }) => {+ const checkbox = (+ <Checkbox+ checked={row.getIsSelected()}+ disabled={!row.getCanSelect()}+ onCheckedChange={(value) => row.toggleSelected(!!value)}+ onClick={(e) => e.stopPropagation()}+ />+ )+ if (!row.getCanSelect()) {+ return (+ <Tooltip content={t("priceLists.products.add.alreadyInPriceList")}>+ {checkbox}+ </Tooltip>)+ }+ return checkbox+ },+ }) as ColumnDef<OfferDTO>- if (isPreselected) {- return (- <Tooltip content={t("priceLists.products.add.alreadyInPriceList")}>- {Component}- </Tooltip>- )- }-- if (isDisabled) {- return (- <Tooltip content={t("priceLists.products.add.noVariants")}>- {Component}- </Tooltip>- )- }-- return Component- },- }),- ...base,- ],- [base, t]- )+ return [+ selectColumn,+ ...(base.slice(1, -1) as ColumnDef<OfferDTO>[]),+ ]+ }, [base, t])}Root._tabMeta = defineTabMeta<PriceListPricesAddSchema>({diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/schema.ts b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/schema.tsindex b5341c166..0dbbe8b4c 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/schema.ts+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/schema.ts@@ -1,9 +1,10 @@import { z } from "zod"-import { PriceListCreateProductsSchema } from "../../../common/schemas"+import { PriceListCreateOffersSchema } from "../../../common/schemas"export const PriceListPricesAddSchema = z.object({product_ids: z.array(z.object({ id: z.string() })).min(1),- products: PriceListCreateProductsSchema,+ offer_ids: z.array(z.string()).default([]),+ offers: PriceListCreateOffersSchema.default({}),})export type PriceListPricesAddSchema = z.infer<typeof PriceListPricesAddSchema>@@ -19,7 +20,7 @@ export const PriceListPricesAddProductsIdsFields = Object.keys() as (keyof typeof PriceListPricesAddProductIdsSchema.shape)[]export const PriceListPricesAddProductsSchema = PriceListPricesAddSchema.pick({- products: true,+ offers: true,})export const PriceListPricesAddProductsFields = Object.keys(diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsxindex 491d5550c..3aaa18bf1 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx@@ -28,7 +28,7 @@ const Root = ({ children }: { children?: ReactNode }) => {}return (- <RouteFocusModal prev="../..">+ <RouteFocusModal prev={`/price-lists/${id}`}>{ready && (Children.count(children) > 0 ? (childrendiff --git a/packages/admin/src/pages/price-lists/price-list-prices-edit/components/price-list-prices-edit-form/price-list-prices-edit-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-edit/components/price-list-prices-edit-form/price-list-prices-edit-form.tsxindex 56a6d686b..3896b30b7 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-edit/components/price-list-prices-edit-form/price-list-prices-edit-form.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-edit/components/price-list-prices-edit-form/price-list-prices-edit-form.tsx@@ -14,28 +14,29 @@ import {import { KeyboundForm } from "../../../../../components/utilities/keybound-form"import { useBatchPriceListPrices } from "../../../../../hooks/api/price-lists"import { castNumber } from "../../../../../lib/cast-number"-import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"import {- PriceListUpdateProductVariantsSchema,- PriceListUpdateProductsSchema,-} from "../../../common/schemas"-import { isProductRow } from "../../../common/utils"+ PriceListGridRow,+ usePriceListGridColumns,+} from "../../../common/hooks/use-price-list-grid-columns"+import { PriceListUpdateOffersSchema } from "../../../common/schemas"type PriceListPricesEditFormProps = {priceList: HttpTypes.AdminPriceList- products: HttpTypes.AdminProduct[]+ gridData: PriceListGridRow[]+ variantIdByOffer: Record<string, string>regions: HttpTypes.AdminRegion[]currencies: HttpTypes.AdminStoreCurrency[]pricePreferences: HttpTypes.AdminPricePreference[]}-const PricingProductPricesSchema = z.object({- products: PriceListUpdateProductsSchema,+const PricingOfferPricesSchema = z.object({+ offers: PriceListUpdateOffersSchema,})export const PriceListPricesEditForm = ({priceList,- products,+ gridData,+ variantIdByOffer,regions,currencies,pricePreferences,@@ -43,24 +44,23 @@ export const PriceListPricesEditForm = ({const { t } = useTranslation()const { handleSuccess, setCloseOnEscape } = useRouteModal()- const initialValue = useRef(initRecord(priceList, products))+ const initialValue = useRef(initRecord(priceList))- const form = useForm<z.infer<typeof PricingProductPricesSchema>>({+ const form = useForm<z.infer<typeof PricingOfferPricesSchema>>({defaultValues: {- products: initialValue.current,+ offers: initialValue.current,},- resolver: zodResolver(PricingProductPricesSchema),+ resolver: zodResolver(PricingOfferPricesSchema),})const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- const { products } = values-const { pricesToDelete, pricesToCreate, pricesToUpdate } = sortPrices(- products,+ values.offers,initialValue.current,- regions+ regions,+ variantIdByOffer)mutateAsync(@@ -72,7 +72,6 @@ export const PriceListPricesEditForm = ({{onSuccess: () => {toast.success(t("priceLists.products.edit.successToast"))-handleSuccess()},onError: (error) => {@@ -95,12 +94,7 @@ export const PriceListPricesEditForm = ({<RouteFocusModal.Body className="flex flex-col overflow-hidden" data-testid="price-list-prices-edit-form-body"><DataGridcolumns={columns}- data={products}- getSubRows={(row) => {- if (isProductRow(row) && row.variants) {- return row.variants- }- }}+ data={gridData}state={form}onEditingChange={(editing) => setCloseOnEscape(!editing)}data-testid="price-list-prices-edit-form-data-grid"@@ -124,56 +118,43 @@ export const PriceListPricesEditForm = ({}function initRecord(- priceList: HttpTypes.AdminPriceList,- products: HttpTypes.AdminProduct[]-): PriceListUpdateProductsSchema {- const record: PriceListUpdateProductsSchema = {}-- const variantPrices = priceList.prices?.reduce((variants, price) => {- const variantObject = variants[price.variant_id] || {}-- const isRegionPrice = !!price.rules?.region_id-- if (isRegionPrice) {- const regionId = price.rules.region_id as string+ priceList: HttpTypes.AdminPriceList+): PriceListUpdateOffersSchema {+ const record: PriceListUpdateOffersSchema = {}++ for (const price of priceList.prices ?? []) {+ const offerId = (price as { rules?: Record<string, string> }).rules?.offer_id+ const variantId = (price as { variant_id?: string }).variant_id+ if (!offerId || !variantId) {+ continue+ }- variantObject.region_prices = {- ...variantObject.region_prices,- [regionId]: {- amount: price.amount.toString(),- id: price.id,- },+ const entry = (record[offerId] ??= {+ variant_id: variantId,+ currency_prices: {},+ region_prices: {},+ })++ const regionId = (price as { rules?: Record<string, string> }).rules+ ?.region_id+ if (regionId) {+ entry.region_prices[regionId] = {+ amount: price.amount.toString(),+ id: price.id,}} else {- variantObject.currency_prices = {- ...variantObject.currency_prices,- [price.currency_code]: {- amount: price.amount.toString(),- id: price.id,- },+ entry.currency_prices[price.currency_code] = {+ amount: price.amount.toString(),+ id: price.id,}}-- variants[price.variant_id] = variantObject- return variants- }, {} as PriceListUpdateProductVariantsSchema)-- for (const product of products) {- record[product.id] = {- variants:- product.variants?.reduce((variants, variant) => {- const prices = variantPrices[variant.id] || {}- variants[variant.id] = prices-- return variants- }, {} as PriceListUpdateProductVariantsSchema) || {},- }}return record}type PriceObject = {+ offerId: stringvariantId: stringcurrencyCode: stringregionId?: string@@ -182,7 +163,7 @@ type PriceObject = {}function convertToPriceArray(- data: PriceListUpdateProductsSchema,+ data: PriceListUpdateOffersSchema,regions: HttpTypes.AdminRegion[]) {const prices: PriceObject[] = []@@ -192,44 +173,31 @@ function convertToPriceArray(return map}, {} as Record<string, string>)- for (const [_productId, product] of Object.entries(data || {})) {- const { variants } = product || {}-- for (const [variantId, variant] of Object.entries(variants || {})) {- const { currency_prices: currencyPrices, region_prices: regionPrices } =- variant || {}-- for (const [currencyCode, currencyPrice] of Object.entries(- currencyPrices || {}- )) {- if (- currencyPrice?.amount !== "" &&- typeof currencyPrice?.amount !== "undefined"- ) {- prices.push({- variantId,- currencyCode,- amount: castNumber(currencyPrice.amount),- id: currencyPrice.id,- })- }+ for (const [offerId, offer] of Object.entries(data || {})) {+ const { variant_id, currency_prices, region_prices } = offer || {}++ for (const [currencyCode, price] of Object.entries(currency_prices || {})) {+ if (price?.amount !== "" && typeof price?.amount !== "undefined") {+ prices.push({+ offerId,+ variantId: variant_id,+ currencyCode,+ amount: castNumber(price.amount),+ id: price.id,+ })}+ }- for (const [regionId, regionPrice] of Object.entries(- regionPrices || {}- )) {- if (- regionPrice?.amount !== "" &&- typeof regionPrice?.amount !== "undefined"- ) {- prices.push({- variantId,- regionId,- currencyCode: regionCurrencyMap[regionId],- amount: castNumber(regionPrice.amount),- id: regionPrice.id,- })- }+ for (const [regionId, price] of Object.entries(region_prices || {})) {+ if (price?.amount !== "" && typeof price?.amount !== "undefined") {+ prices.push({+ offerId,+ variantId: variant_id,+ regionId,+ currencyCode: regionCurrencyMap[regionId],+ amount: castNumber(price.amount),+ id: price.id,+ })}}}@@ -238,11 +206,18 @@ function convertToPriceArray(}function createMapKey(obj: PriceObject) {- return `${obj.variantId}-${obj.currencyCode}-${obj.regionId || "none"}-${+ return `${obj.offerId}-${obj.currencyCode}-${obj.regionId || "none"}-${obj.id || "none"}`}+function buildRules(price: PriceObject) {+ return {+ offer_id: price.offerId,+ ...(price.regionId ? { region_id: price.regionId } : {}),+ }+}+function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {const pricesToUpdate: HttpTypes.AdminUpdatePriceListPrice[] = []const pricesToCreate: HttpTypes.AdminCreatePriceListPrice[] = []@@ -251,12 +226,12 @@ function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {const initialPriceMap = initialPrices.reduce((map, price) => {map[createMapKey(price)] = pricereturn map- }, {} as Record<string, (typeof initialPrices)[0]>)+ }, {} as Record<string, PriceObject>)const newPriceMap = newPrices.reduce((map, price) => {map[createMapKey(price)] = pricereturn map- }, {} as Record<string, (typeof newPrices)[0]>)+ }, {} as Record<string, PriceObject>)const keys = new Set([...Object.keys(initialPriceMap),@@ -277,9 +252,7 @@ function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {id: newPrice.id,variant_id: newPrice.variantId,currency_code: newPrice.currencyCode,- rules: newPrice.regionId- ? { region_id: newPrice.regionId }- : undefined,+ rules: buildRules(newPrice),amount: newPrice.amount,})}@@ -289,7 +262,7 @@ function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {pricesToCreate.push({variant_id: newPrice.variantId,currency_code: newPrice.currencyCode,- rules: newPrice.regionId ? { region_id: newPrice.regionId } : undefined,+ rules: buildRules(newPrice),amount: newPrice.amount,})}@@ -303,9 +276,10 @@ function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {}function sortPrices(- data: PriceListUpdateProductsSchema,- initialValue: PriceListUpdateProductsSchema,- regions: HttpTypes.AdminRegion[]+ data: PriceListUpdateOffersSchema,+ initialValue: PriceListUpdateOffersSchema,+ regions: HttpTypes.AdminRegion[],+ _variantIdByOffer: Record<string, string>) {const initialPrices = convertToPriceArray(initialValue, regions)const newPrices = convertToPriceArray(data, regions)diff --git a/packages/admin/src/pages/price-lists/price-list-prices-edit/price-list-prices-edit.tsx b/packages/admin/src/pages/price-lists/price-list-prices-edit/price-list-prices-edit.tsxindex 2ed3e541b..b433840ac 100644--- a/packages/admin/src/pages/price-lists/price-list-prices-edit/price-list-prices-edit.tsx+++ b/packages/admin/src/pages/price-lists/price-list-prices-edit/price-list-prices-edit.tsx@@ -1,35 +1,114 @@+import { useMemo } from "react"import { useParams, useSearchParams } from "react-router-dom"import { PriceListPricesEditForm } from "./components/price-list-prices-edit-form"import { usePriceList, useProducts } from "@hooks/api"+import { OfferDTO } from "@mercurjs/types"+import { useOffers } from "../../../hooks/api/offers"import { RouteFocusModal } from "@components/modals"+import { buildOfferGridData } from "../common/build-offer-grid-data"import { usePriceListCurrencyData } from "../common/hooks/use-price-list-currency-data"export const PriceListPricesEdit = () => {const { id } = useParams()const [searchParams] = useSearchParams()const ids = searchParams.get("ids[]")+ const productFilter = useMemo(() => (ids ? ids.split(",") : undefined), [ids])const { price_list, isLoading, isError, error } = usePriceList(id!, {- fields: "*prices",+ fields:+ "id,title,+prices.amount,+prices.currency_code,+prices.price_set.variant.id,+prices.price_rules.attribute,+prices.price_rules.value",})- const productIds = ids?.split(",")++ // offer_ids currently priced in this list.+ const offerIds = useMemo(() => {+ const set = new Set<string>()+ for (const price of price_list?.prices ?? []) {+ const offerId = (price as { rules?: Record<string, string> }).rules+ ?.offer_id+ if (offerId) {+ set.add(offerId)+ }+ }+ return Array.from(set)+ }, [price_list])++ // Resolve the priced offers to their (seller, product) pairs; we then show+ // every one of that seller's offers for those products, not only the priced+ // variants, so the admin can price the seller's other variants too.+ const { offers: pricedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds.length || 1,+ fields: "id,seller_id,product_id",+ },+ { enabled: offerIds.length > 0 }+ )++ const { pairs, sellerIds } = useMemo(() => {+ const p = new Set<string>()+ const s = new Set<string>()+ for (const offer of (pricedOffers ?? []) as OfferDTO[]) {+ p.add(`${offer.seller_id}::${offer.product_id}`)+ s.add(offer.seller_id)+ }+ return { pairs: p, sellerIds: Array.from(s) }+ }, [pricedOffers])++ const { offers } = useOffers(+ {+ seller_id: sellerIds,+ limit: 1000,+ fields:+ "id,variant_id,product_id,seller_id,sku,seller.name,product.title,product.thumbnail",+ },+ { enabled: sellerIds.length > 0 }+ )++ const scopedOffers = useMemo(() => {+ const allowedProducts = productFilter ? new Set(productFilter) : undefined+ return ((offers ?? []) as OfferDTO[]).filter(+ (o) =>+ pairs.has(`${o.seller_id}::${o.product_id}`) &&+ (!allowedProducts || allowedProducts.has(o.product_id))+ )+ }, [offers, pairs, productFilter])++ const productIds = useMemo(+ () => Array.from(new Set(scopedOffers.map((o) => o.product_id))),+ [scopedOffers]+ )const {products,isLoading: isProductsLoading,isError: isProductsError,error: productError,- } = useProducts({- id: productIds,- limit: productIds?.length || 9999, // Temporary until we support lazy loading in the DataGrid- price_list_id: [id!],- fields: "title,thumbnail,*variants",- })+ } = useProducts(+ {+ id: productIds,+ limit: productIds.length || 1,+ fields: "id,*variants",+ },+ { enabled: productIds.length > 0 }+ )++ const { gridData, variantIdByOffer } = useMemo(+ () =>+ buildOfferGridData(+ scopedOffers,+ products ?? []+ ),+ [scopedOffers, products]+ )const currencyData = usePriceListCurrencyData()- const ready = currencyData.isReady &&- !isLoading && !!price_list && !isProductsLoading && !!products+ const ready =+ currencyData.isReady &&+ !isLoading &&+ !!price_list &&+ !isProductsLoading &&+ !!productsif (isError) {throw error@@ -40,17 +119,18 @@ export const PriceListPricesEdit = () => {}return (- <RouteFocusModal prev="../..">+ <RouteFocusModal prev={`/price-lists/${id}`}><RouteFocusModal.Title asChild><span className="sr-only">Edit Prices for {price_list?.title}</span></RouteFocusModal.Title><RouteFocusModal.Description className="sr-only">- Update prices for products in the price list+ Update prices for offers in the price list</RouteFocusModal.Description>{ready && (<PriceListPricesEditFormpriceList={price_list}- products={products}+ gridData={gridData}+ variantIdByOffer={variantIdByOffer}{...currencyData}/>)}diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.tsindex e82411728..2465308a0 100644--- a/packages/core/src/api/admin/middlewares.ts+++ b/packages/core/src/api/admin/middlewares.ts@@ -15,6 +15,7 @@ import { adminCommissionRatesMiddlewares } from "./commission-rates/middlewares"import { adminProductsMiddlewares } from "./products/middlewares"import { adminPromotionsMiddlewares } from "./promotions/middlewares"import { adminCampaignsMiddlewares } from "./campaigns/middlewares"+import { adminPriceListsMiddlewares } from "./price-lists/middlewares"import { adminCollectionsMiddlewares } from "./collections/middlewares"import { adminProductCategoriesMiddlewares } from "./product-categories/middlewares"import { adminProductAttributesMiddlewares } from "./product-attributes/middlewares"@@ -48,6 +49,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [...adminProductsMiddlewares,...adminPromotionsMiddlewares,...adminCampaignsMiddlewares,+ ...adminPriceListsMiddlewares,...adminCollectionsMiddlewares,...adminProductCategoriesMiddlewares,...adminProductAttributesMiddlewares,diff --git a/packages/core/src/api/admin/price-lists/middlewares.ts b/packages/core/src/api/admin/price-lists/middlewares.tsnew file mode 100644index 000000000..6d2d1fc48--- /dev/null+++ b/packages/core/src/api/admin/price-lists/middlewares.ts@@ -0,0 +1,69 @@+import { validateAndTransformQuery } from "@medusajs/framework"+import { MiddlewareRoute } from "@medusajs/framework/http"+import { listPriceListQueryConfig } from "@medusajs/medusa/api/admin/price-lists/query-config"+import { AdminGetPriceListsParams } from "@medusajs/medusa/api/admin/price-lists/validators"+import { z } from "zod"++import { ORIGINAL_MIDDLEWARES } from "../../../utils/disable-medusa-middlewares"++const LIST_MATCHER = "/admin/price-lists"++const capturedBase = (ORIGINAL_MIDDLEWARES[+ "dist/api/admin/price-lists/middlewares.js"+] ?? []) as MiddlewareRoute[]++const routeHasGet = (route: MiddlewareRoute) => {+ const methods = Array.isArray(route.method)+ ? route.method+ : route.method+ ? [route.method]+ : []+ return methods.includes("GET")+}++const baseWithoutOverrides = capturedBase.filter((route) => {+ if (route.matcher === LIST_MATCHER && routeHasGet(route)) {+ return false+ }+ return true+})++const dateOperators = z+ .object({+ $gt: z.string(),+ $gte: z.string(),+ $lt: z.string(),+ $lte: z.string(),+ })+ .partial()++// The native list validator only exposes `status`. Add the marketplace list+// filters used by the admin Price Lists table (`type`, `created_at`,+// `updated_at`) — all native `price_list` columns, so the default handler+// applies them as filters once they pass validation; no link resolution needed.+const AdminGetPriceListsWithFilters = AdminGetPriceListsParams.merge(+ z.object({+ type: z+ .union([+ z.enum(["sale", "override"]),+ z.array(z.enum(["sale", "override"])),+ ])+ .optional(),+ created_at: dateOperators.optional(),+ updated_at: dateOperators.optional(),+ })+)++export const adminPriceListsMiddlewares: MiddlewareRoute[] = [+ ...baseWithoutOverrides,+ {+ method: ["GET"],+ matcher: LIST_MATCHER,+ middlewares: [+ validateAndTransformQuery(+ AdminGetPriceListsWithFilters,+ listPriceListQueryConfig+ ),+ ],+ },+]diff --git a/packages/core/src/utils/disable-medusa-middlewares.ts b/packages/core/src/utils/disable-medusa-middlewares.tsindex 9cca6f817..9da7d2630 100644--- a/packages/core/src/utils/disable-medusa-middlewares.ts+++ b/packages/core/src/utils/disable-medusa-middlewares.ts@@ -27,6 +27,7 @@ const OVERRIDES: string[] = ["dist/api/admin/products/middlewares.js","dist/api/admin/promotions/middlewares.js","dist/api/admin/campaigns/middlewares.js",+ "dist/api/admin/price-lists/middlewares.js","dist/api/admin/product-variants/middlewares.js","dist/api/admin/product-categories/middlewares.js","dist/api/admin/collections/middlewares.js",