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(vendor): align price lists with Figma (#1338)
Viktor Holik9c79041db23b
diff --git a/apps/vendor/src/_navigation.ts b/apps/vendor/src/_navigation.tsindex 3997f282c..9f160197e 100644--- a/apps/vendor/src/_navigation.ts+++ b/apps/vendor/src/_navigation.ts@@ -4,6 +4,5 @@ import { defineNavigationConfig } from "@mercurjs/dashboard-sdk"export default defineNavigationConfig({items: [{ id: "orders", rank: 0 },- { id: "price-lists", hidden: true },],})diff --git a/apps/vendor/vite.config.ts b/apps/vendor/vite.config.tsindex 0022856e6..1152ac3eb 100644--- a/apps/vendor/vite.config.ts+++ b/apps/vendor/vite.config.ts@@ -1,6 +1,10 @@import { defineConfig, loadEnv } from 'vite'import react from '@vitejs/plugin-react'import { mercurDashboardPlugin } from '@mercurjs/dashboard-sdk/vite'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const rootDir = path.dirname(fileURLToPath(import.meta.url))// https://vite.dev/config/export default defineConfig(({ mode }) => {@@ -9,6 +13,20 @@ export default defineConfig(({ mode }) => {env.VITE_MERCUR_BACKEND_URL || env.MERCUR_BACKEND_URLreturn {+ resolve: {+ alias: {+ // `@mercurjs/vendor/extension-targets` is a build-time marker module the+ // dashboard-sdk emits (imported by `_navigation.ts` and every widget).+ // Vite's dev resolution of that `exports` subpath on the linked workspace+ // package is racy — it intermittently throws "Failed to resolve import ...+ // Does the file exist?" and blanks the app. Pin the exact specifier to the+ // same file the exports map points to so resolution is deterministic.+ '@mercurjs/vendor/extension-targets': path.join(+ rootDir,+ 'node_modules/@mercurjs/vendor/dist/extension-targets.js',+ ),+ },+ },plugins: [react(),mercurDashboardPlugin({diff --git a/integration-tests/http/price-lists/vendor/price-list-offers.spec.ts b/integration-tests/http/price-lists/vendor/price-list-offers.spec.tsnew file mode 100644index 000000000..985d69010--- /dev/null+++ b/integration-tests/http/price-lists/vendor/price-list-offers.spec.ts@@ -0,0 +1,229 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import { MedusaContainer } from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"++import { createSellerUser } from "../../../helpers/create-seller-user"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++/**+ * A vendor price-list override targets a marketplace **offer**: the override 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. This spec locks in+ * the contract for the vendor surface: the seller's override applies to their own+ * offer and does NOT leak onto a different seller's offer of the same variant.+ */+medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api }) => {+ describe("Vendor - Price Lists (offer-scoped price rules)", () => {+ let appContainer: MedusaContainer+ let variantId: string+ let priceSetId: string+ let seller1Headers: any+ 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 { seller, headers, 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 () => {+ // A single master product + variant, sold by two sellers via two offers.+ const owner = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "ProductOwner",+ })+ const product = await createVendorProduct(api, owner.headers, {+ title: "Shared Master Product",+ sku: "V-SHARED-1",+ })+ variantId = product.variants[0].id++ const a = await seedSellerOffer({+ email: "[email protected]",+ name: "VOfferA",+ variantId,+ amount: 1000,+ })+ offerA = a.offer+ seller1Headers = a.headers++ offerB = (+ await seedSellerOffer({+ email: "[email protected]",+ name: "VOfferB",+ 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 an offer-scoped override that does not leak to another seller's offer", async () => {+ const res = await api.post(+ "/vendor/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 },+ },+ ],+ },+ seller1Headers+ )++ expect(res.status).toEqual(201)+ const priceListId = res.data.price_list.id++ // The persisted price carries the offer_id rule (read via the data layer).+ 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(+ "/vendor/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 },+ },+ ],+ },+ seller1Headers+ )+ ).data.price_list.id++ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)+ const { data: created } = await query.graph({+ entity: "price",+ filters: { price_list_id: priceListId },+ fields: ["id"],+ })+ const priceId = (created[0] as any).id++ const batch = await api.post(+ `/vendor/price-lists/${priceListId}/prices/batch`,+ {+ update: [+ {+ id: priceId,+ variant_id: variantId,+ currency_code: "usd",+ amount: 300,+ rules: { offer_id: offerA.id },+ },+ ],+ },+ seller1Headers+ )+ expect(batch.status).toEqual(200)++ expect(await calc(offerA.id)).toEqual(300)+ expect(await calc(offerB.id)).toEqual(1000)+ })+ })+ },+})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.tsindex c97eb53e5..0a847e70c 100644--- 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.ts@@ -1,91 +1 @@-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 }-}+export { buildOfferGridData } from "@mercurjs/dashboard-shared"diff --git a/packages/admin/src/pages/price-lists/common/constants.ts b/packages/admin/src/pages/price-lists/common/constants.tsindex aecee622a..96051692c 100644--- a/packages/admin/src/pages/price-lists/common/constants.ts+++ b/packages/admin/src/pages/price-lists/common/constants.ts@@ -1,20 +1,5 @@-/**- * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported- */-export enum PriceListStatus {- ACTIVE = "active",- DRAFT = "draft",-}--export enum PriceListDateStatus {- SCHEDULED = "scheduled",- EXPIRED = "expired",-}--/**- * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported- */-export enum PriceListType {- SALE = "sale",- OVERRIDE = "override",-}+export {+ PriceListDateStatus,+ PriceListStatus,+ PriceListType,+} from "@mercurjs/dashboard-shared"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 1b42fc34b..d84492cd2 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,36 +9,17 @@ import {DataGrid,} from "../../../../components/data-grid"import { createDataGridPriceColumns } from "../../../../components/data-grid/helpers/create-data-grid-price-columns"+import {+ isPriceListGroupRow,+ type PriceListGridRow,+} from "@mercurjs/dashboard-shared"-/**- * 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+export {+ isPriceListGroupRow,+ type PriceListGridGroupRow,+ type PriceListGridOfferRow,+ type PriceListGridRow,+} from "@mercurjs/dashboard-shared"const columnHelper = createDataGridHelper<PriceListGridRow, any>()diff --git a/packages/admin/src/pages/price-lists/common/utils.ts b/packages/admin/src/pages/price-lists/common/utils.tsindex d998e94ff..2137eb91c 100644--- a/packages/admin/src/pages/price-lists/common/utils.ts+++ b/packages/admin/src/pages/price-lists/common/utils.ts@@ -1,117 +1,5 @@-import { HttpTypes } from "@medusajs/types"-import i18n, { TFunction } from "i18next"-import { castNumber } from "../../../lib/cast-number"-import { PriceListDateStatus, PriceListStatus } from "./constants"-import {- PriceListCreateCurrencyPrice,- PriceListCreateOffersSchema,-} from "./schemas"--const getValues = (priceList: HttpTypes.AdminPriceList) => {- const startsAt = priceList.starts_at- const endsAt = priceList.ends_at-- const isExpired = endsAt ? new Date(endsAt) < new Date() : false- const isScheduled = startsAt ? new Date(startsAt) > new Date() : false- const isDraft = priceList.status === PriceListStatus.DRAFT-- return {- isExpired,- isScheduled,- isDraft,- }-}--export const getPriceListStatus = (- t: TFunction<"translation">,- priceList: HttpTypes.AdminPriceList-) => {- const { isExpired, isScheduled, isDraft } = getValues(priceList)-- let text = t("priceLists.fields.status.options.active")- let color: "red" | "grey" | "orange" | "green" = "green"- let status: string = PriceListStatus.ACTIVE-- if (isDraft) {- color = "grey"- text = t("priceLists.fields.status.options.draft")- status = PriceListStatus.DRAFT- }-- if (isExpired) {- color = "red"- text = t("priceLists.fields.status.options.expired")- status = PriceListDateStatus.EXPIRED- }-- if (isScheduled) {- color = "orange"- text = t("priceLists.fields.status.options.scheduled")- status = PriceListDateStatus.SCHEDULED- }-- return {- color,- text,- status,- }-}--export const isProductRow = (- row: HttpTypes.AdminProduct | HttpTypes.AdminProductVariant-): row is HttpTypes.AdminProduct => {- return "variants" in row-}--// 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[]-) => {- 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,- }- }-- const currencyPrices = Object.entries(offer.currency_prices || {}).flatMap(- ([currencyCode, currencyPrice]) =>- currencyPrice?.amount- ? [extractPriceDetails(currencyPrice, "currency", currencyCode)]- : []- )-- const regionPrices = Object.entries(offer.region_prices || {}).flatMap(- ([regionId, regionPrice]) =>- regionPrice?.amount- ? [extractPriceDetails(regionPrice, "region", regionId)]- : []- )-- return [...currencyPrices, ...regionPrices]- })-}+export {+ extractPricesFromOffers,+ getPriceListStatus,+ isProductRow,+} from "@mercurjs/dashboard-shared"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 fe70e32b2..713c6eb4a 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@@ -219,7 +219,9 @@ export const PriceListProductSection = ({count={groupedOffers.length}pageSize={PAGE_SIZE}isLoading={isLoading}- navigateTo={(row) => `/products/${row.original.product_id}`}+ navigateTo={(row) =>+ `/offers/${row.original.product_id}?seller_id=${row.original.seller_id}`+ }orderBy={[{ key: "created_at", label: t("fields.createdAt") },{ key: "updated_at", label: t("fields.updatedAt") },diff --git a/packages/core/src/api/vendor/price-lists/validators.ts b/packages/core/src/api/vendor/price-lists/validators.tsindex 8f8f1d985..09658cb3d 100644--- a/packages/core/src/api/vendor/price-lists/validators.ts+++ b/packages/core/src/api/vendor/price-lists/validators.ts@@ -21,8 +21,11 @@ export const VendorGetPriceListsParams = createFindParams({z.object({q: z.string().optional(),id: z.union([z.string(), z.array(z.string())]).optional(),+ type: z.array(z.nativeEnum(PriceListType)).optional(),starts_at: createOperatorMap().optional(),ends_at: createOperatorMap().optional(),+ created_at: createOperatorMap().optional(),+ updated_at: createOperatorMap().optional(),status: z.array(z.nativeEnum(PriceListStatus)).optional(),}))diff --git a/packages/dashboard-shared/src/index.ts b/packages/dashboard-shared/src/index.tsindex 781319da2..c282e12d4 100644--- a/packages/dashboard-shared/src/index.ts+++ b/packages/dashboard-shared/src/index.ts@@ -24,3 +24,4 @@ export {export * from "./components"export * from "./hooks"export * from "./extensions"+export * from "./price-lists"diff --git a/packages/dashboard-shared/src/price-lists/build-offer-grid-data.ts b/packages/dashboard-shared/src/price-lists/build-offer-grid-data.tsnew file mode 100644index 000000000..a3c9c7036--- /dev/null+++ b/packages/dashboard-shared/src/price-lists/build-offer-grid-data.ts@@ -0,0 +1,120 @@+import { OfferDTO } from "@mercurjs/types"++/**+ * 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++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/dashboard-shared/src/price-lists/constants.ts b/packages/dashboard-shared/src/price-lists/constants.tsnew file mode 100644index 000000000..4830ebe90--- /dev/null+++ b/packages/dashboard-shared/src/price-lists/constants.ts@@ -0,0 +1,18 @@+/**+ * Re-implementation of enums from `@medusajs/medusa` as they cannot be imported+ * directly. Shared by the admin and vendor price-list surfaces.+ */+export enum PriceListStatus {+ ACTIVE = "active",+ DRAFT = "draft",+}++export enum PriceListDateStatus {+ SCHEDULED = "scheduled",+ EXPIRED = "expired",+}++export enum PriceListType {+ SALE = "sale",+ OVERRIDE = "override",+}diff --git a/packages/dashboard-shared/src/price-lists/index.ts b/packages/dashboard-shared/src/price-lists/index.tsnew file mode 100644index 000000000..6807ddaf9--- /dev/null+++ b/packages/dashboard-shared/src/price-lists/index.ts@@ -0,0 +1,19 @@+export {+ PriceListDateStatus,+ PriceListStatus,+ PriceListType,+} from "./constants"+export {+ buildOfferGridData,+ isPriceListGroupRow,+ type PriceListGridGroupRow,+ type PriceListGridOfferRow,+ type PriceListGridRow,+} from "./build-offer-grid-data"+export {+ extractPricesFromOffers,+ getPriceListStatus,+ isProductRow,+ type ExtractableOffer,+ type ExtractableOffers,+} from "./utils"diff --git a/packages/dashboard-shared/src/price-lists/utils.ts b/packages/dashboard-shared/src/price-lists/utils.tsnew file mode 100644index 000000000..6c9ad3f4b--- /dev/null+++ b/packages/dashboard-shared/src/price-lists/utils.ts@@ -0,0 +1,135 @@+import { HttpTypes } from "@mercurjs/types"+import i18n, { TFunction } from "i18next"+import { PriceListDateStatus, PriceListStatus } from "./constants"++// Local copy of the dashboards' `castNumber` helper so the shared price-list+// utilities have no dependency on either package's `lib/`.+const castNumber = (number: number | string) =>+ typeof number === "string" ? Number(number.replace(",", ".")) : number++const getValues = (priceList: HttpTypes.AdminPriceList) => {+ const startsAt = priceList.starts_at+ const endsAt = priceList.ends_at++ const isExpired = endsAt ? new Date(endsAt) < new Date() : false+ const isScheduled = startsAt ? new Date(startsAt) > new Date() : false+ const isDraft = priceList.status === PriceListStatus.DRAFT++ return {+ isExpired,+ isScheduled,+ isDraft,+ }+}++export const getPriceListStatus = (+ t: TFunction<"translation">,+ priceList: HttpTypes.AdminPriceList+) => {+ const { isExpired, isScheduled, isDraft } = getValues(priceList)++ let text = t("priceLists.fields.status.options.active")+ let color: "red" | "grey" | "orange" | "green" = "green"+ let status: string = PriceListStatus.ACTIVE++ if (isDraft) {+ color = "grey"+ text = t("priceLists.fields.status.options.draft")+ status = PriceListStatus.DRAFT+ }++ if (isExpired) {+ color = "red"+ text = t("priceLists.fields.status.options.expired")+ status = PriceListDateStatus.EXPIRED+ }++ if (isScheduled) {+ color = "orange"+ text = t("priceLists.fields.status.options.scheduled")+ status = PriceListDateStatus.SCHEDULED+ }++ return {+ color,+ text,+ status,+ }+}++export const isProductRow = (+ row: HttpTypes.AdminProduct | HttpTypes.AdminProductVariant+): row is HttpTypes.AdminProduct => {+ return "variants" in row+}++type OfferCurrencyPrice = { amount?: string | number }++// Structural shape of the offer-keyed grid state. Typed here (rather than+// importing each package's zod-inferred type) so this shared helper stays+// decoupled from either dashboard's zod instance.+export type ExtractableOffer = {+ variant_id: string+ currency_prices?: Record<string, OfferCurrencyPrice | undefined>+ region_prices?: Record<string, OfferCurrencyPrice | undefined>+}++export type ExtractableOffers = Record<string, ExtractableOffer>++/**+ * 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+ * and never leaks onto another seller's offer of the same variant.+ */+export const extractPricesFromOffers = (+ offers: ExtractableOffers,+ regions: HttpTypes.AdminRegion[]+) => {+ return Object.entries(offers).flatMap(([offerId, offer]) => {+ const extractPriceDetails = (+ price: OfferCurrencyPrice,+ 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,+ }+ }++ const currencyPrices = Object.entries(offer.currency_prices || {}).flatMap(+ ([currencyCode, currencyPrice]) =>+ currencyPrice?.amount+ ? [extractPriceDetails(currencyPrice, "currency", currencyCode)]+ : []+ )++ const regionPrices = Object.entries(offer.region_prices || {}).flatMap(+ ([regionId, regionPrice]) =>+ regionPrice?.amount+ ? [extractPriceDetails(regionPrice, "region", regionId)]+ : []+ )++ return [...currencyPrices, ...regionPrices]+ })+}diff --git a/packages/vendor/package.json b/packages/vendor/package.jsonindex 40d67e5c6..e9878e23c 100644--- a/packages/vendor/package.json+++ b/packages/vendor/package.json@@ -12,15 +12,18 @@"exports": {".": {"types": "./dist/index.d.ts",- "import": "./dist/index.js"+ "import": "./dist/index.js",+ "default": "./dist/index.js"},"./pages": {"types": "./dist/pages/index.d.ts",- "import": "./dist/pages/index.js"+ "import": "./dist/pages/index.js",+ "default": "./dist/pages/index.js"},"./extension-targets": {"types": "./dist/extension-targets.d.ts",- "import": "./dist/extension-targets.js"+ "import": "./dist/extension-targets.js",+ "default": "./dist/extension-targets.js"},"./index.css": "./dist/index.css"},diff --git a/packages/vendor/src/get-route-map.tsx b/packages/vendor/src/get-route-map.tsxindex 53adb62af..8c339917f 100644--- a/packages/vendor/src/get-route-map.tsx+++ b/packages/vendor/src/get-route-map.tsx@@ -1009,6 +1009,13 @@ export function getRouteMap({lazy: () =>import("./pages/price-lists/[id]/configuration"),},+ {+ path: "customer-availability",+ lazy: () =>+ import(+ "./pages/price-lists/[id]/customer-availability"+ ),+ },{path: "products/add",lazy: () =>diff --git a/packages/vendor/src/i18n/translations/$schema.json b/packages/vendor/src/i18n/translations/$schema.jsonindex a3faf5524..9679e491f 100644--- a/packages/vendor/src/i18n/translations/$schema.json+++ b/packages/vendor/src/i18n/translations/$schema.json@@ -5095,6 +5095,9 @@},"variantsCount_other": {"type": "string"+ },+ "store": {+ "type": "string"}},"required": [@@ -5117,7 +5120,8 @@"notEnabled","enabled","variantsCount_one",- "variantsCount_other"+ "variantsCount_other",+ "store"],"additionalProperties": false},@@ -11634,6 +11638,22 @@"list"],"additionalProperties": false+ },+ "validation": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"+ }+ },+ "required": [+ "title",+ "description"+ ],+ "additionalProperties": false}},"required": [@@ -11641,7 +11661,8 @@"subheader","tabs","successToast",- "products"+ "products",+ "validation"],"additionalProperties": false},@@ -11694,6 +11715,60 @@],"additionalProperties": false},+ "customerAvailability": {+ "type": "object",+ "properties": {+ "header": {+ "type": "string"+ },+ "add": {+ "type": "string"+ },+ "list": {+ "type": "object",+ "properties": {+ "noRecordsTitle": {+ "type": "string"+ },+ "noRecordsMessage": {+ "type": "string"+ }+ },+ "required": [+ "noRecordsTitle",+ "noRecordsMessage"+ ],+ "additionalProperties": false+ },+ "edit": {+ "type": "object",+ "properties": {+ "header": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "successToast": {+ "type": "string"+ }+ },+ "required": [+ "header",+ "description",+ "successToast"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "header",+ "add",+ "list",+ "edit"+ ],+ "additionalProperties": false+ },"products": {"type": "object","properties": {@@ -11708,11 +11783,15 @@},"editPrices": {"type": "string"+ },+ "editPricesDisabled": {+ "type": "string"}},"required": ["addProducts",- "editPrices"+ "editPrices",+ "editPricesDisabled"],"additionalProperties": false},@@ -11745,10 +11824,30 @@"properties": {"successToast": {"type": "string"+ },+ "atLeastOnePrice": {+ "type": "string"+ },+ "alreadyInPriceList": {+ "type": "string"+ },+ "noVariants": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"}},"required": [- "successToast"+ "successToast",+ "atLeastOnePrice",+ "alreadyInPriceList",+ "noVariants",+ "title",+ "description"],"additionalProperties": false},@@ -11757,10 +11856,18 @@"properties": {"successToast": {"type": "string"+ },+ "title": {+ "type": "string"+ },+ "description": {+ "type": "string"}},"required": [- "successToast"+ "successToast",+ "title",+ "description"],"additionalProperties": false}@@ -11822,11 +11929,28 @@"scheduled"],"additionalProperties": false+ },+ "descriptions": {+ "type": "object",+ "properties": {+ "draft": {+ "type": "string"+ },+ "active": {+ "type": "string"+ }+ },+ "required": [+ "draft",+ "active"+ ],+ "additionalProperties": false}},"required": ["label",- "options"+ "options",+ "descriptions"],"additionalProperties": false},@@ -11948,6 +12072,9 @@"attribute"],"additionalProperties": false+ },+ "offerVariant": {+ "type": "string"}},"required": [@@ -11956,7 +12083,33 @@"type","startsAt","endsAt",- "customerAvailability"+ "customerAvailability",+ "offerVariant"+ ],+ "additionalProperties": false+ },+ "list": {+ "type": "object",+ "properties": {+ "noRecords": {+ "type": "object",+ "properties": {+ "title": {+ "type": "string"+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "title",+ "message"+ ],+ "additionalProperties": false+ }+ },+ "required": [+ "noRecords"],"additionalProperties": false}@@ -11968,8 +12121,10 @@"create","edit","configuration",+ "customerAvailability","products",- "fields"+ "fields",+ "list"],"additionalProperties": false},diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.jsonindex 51a3c0a1f..7c94f5ef8 100644--- a/packages/vendor/src/i18n/translations/en.json+++ b/packages/vendor/src/i18n/translations/en.json@@ -1246,7 +1246,8 @@"notEnabled": "Not enabled","enabled": "Enabled","variantsCount_one": "{{count}} variant",- "variantsCount_other": "{{count}} variants"+ "variantsCount_other": "{{count}} variants",+ "store": "Store"},"status": {"published": "Published",@@ -2903,10 +2904,10 @@},"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.",@@ -2914,34 +2915,52 @@"list": {"noRecordsMessage": "Create a product first."}+ },+ "validation": {+ "title": "Please enter a title",+ "description": "Please enter a description"}},"edit": {"header": "Edit Price List",- "successToast": "Price list {{title}} was successfully updated."+ "successToast": "Price list was successfully updated."},"configuration": {"header": "Configuration","edit": {"header": "Edit Price List Configuration","description": "Edit the configuration of the price list.",- "successToast": "Price list configuration was successfully updated."+ "successToast": "Price list 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": "Price list was successfully updated."}},"products": {- "header": "Products",+ "header": "Offers","actions": {- "addProducts": "Add products",- "editPrices": "Edit prices"+ "addProducts": "Add offers",+ "editPrices": "Edit 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.",+ "successToast": "Price list was successfully updated.","atLeastOnePrice": "At least one price must be added.","alreadyInPriceList": "This product is already in the price list","noVariants": "This product has no variants",@@ -2949,7 +2968,7 @@"description": "Add products and set prices for the price list"},"edit": {- "successToast": "Prices were successfully updated.",+ "successToast": "Price list was successfully updated.","title": "Edit Prices for {{title}}","description": "Update prices for products in the price list"}@@ -2966,6 +2985,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": {@@ -2974,7 +2997,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",@@ -2983,11 +3006,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": {@@ -2996,6 +3019,13 @@"hint": "Choose which customer groups the price list should be applied to.","placeholder": "Search for customer groups","attribute": "Customer groups"+ },+ "offerVariant": "Offer/Variant"+ },+ "list": {+ "noRecords": {+ "title": "No price lists yet",+ "message": "Create price lists for sales and price overrides"}}},diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/index.tsindex 98a489def..16613ac05 100644--- a/packages/vendor/src/pages/price-lists/[id]/_components/index.ts+++ b/packages/vendor/src/pages/price-lists/[id]/_components/index.ts@@ -1,3 +1,4 @@export * from "./price-list-configuration-section"+export * from "./price-list-customer-availability-section"export * from "./price-list-general-section"export * from "./price-list-product-section"diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsxindex 776ffde8d..e62205ea3 100644--- a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx@@ -2,12 +2,11 @@ import { PencilSquare } from "@medusajs/icons"import { HttpTypes } from "@medusajs/types"import { Container, Heading } from "@medusajs/ui"import { useTranslation } from "react-i18next"+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@@ -19,14 +18,9 @@ export const PriceListConfigurationSection = ({const { t } = useTranslation()return (- <Container className="flex flex-col gap-y-4">- <div className="flex items-center justify-between">- <div>- <Heading level="h2">{t("priceLists.configuration.header")}</Heading>- {/* TODO: Customer group availability - vendor API does not support customer groups yet- <CustomerGroupDisplay priceList={priceList as any} />- */}- </div>+ <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">+ <Heading level="h2" data-testid="price-list-configuration-section-heading">{t("priceLists.configuration.header")}</Heading><ActionMenugroups={[{@@ -41,11 +35,13 @@ export const PriceListConfigurationSection = ({]}/></div>+<DateRangeDisplayendsAt={priceList.ends_at}startsAt={priceList.starts_at}showTime/>+<DisplayExtensionZonemodel="price_list"zone="configuration"@@ -54,54 +50,3 @@ export const PriceListConfigurationSection = ({</Container>)}--const _CustomerGroupDisplay = ({- priceList,-}: {- priceList: HttpTypes.AdminPriceList & { price_list_rules: any[] }-}) => {- const { t } = useTranslation()-- const customerGroupIds =- priceList.price_list_rules?.find(- (rule) => rule.attribute === "customer.groups.id"- )?.value || ([] as string[])-- const { customer_groups: customerGroupsData, isPending, isError, error } = useCustomerGroups(- undefined,- {- enabled: !!customerGroupIds?.length,- }- )-- if (isError) {- throw error- }-- if (!customerGroupIds?.length) {- return null- }-- if (isPending || !customerGroupsData) {- return <Skeleton className="h-5 w-full max-w-48" />- }-- const flatCustomerGroups = customerGroupsData.map((item) => item.customer_group)-- const filteredCustomerGroups = flatCustomerGroups- .filter((group) => customerGroupIds.includes(group.id))-- 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={filteredCustomerGroups.map((group) => group.name!)}- n={1}- className="txt-small-plus text-ui-fg-muted"- />- </div>- )-}diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/index.tsnew file mode 100644index 000000000..ef1b0a099--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/index.ts@@ -0,0 +1 @@+export * from "./price-list-customer-availability-section"diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/price-list-customer-availability-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/price-list-customer-availability-section.tsxnew file mode 100644index 000000000..7329093d5--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-customer-availability-section/price-list-customer-availability-section.tsx@@ -0,0 +1,90 @@+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 />,+ },+ ],+ },+ ]}+ />+ </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"),+ }}+ />+ ) : 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/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsxindex ac45cba99..46c9fb719 100644--- a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx@@ -29,15 +29,23 @@ export const PriceListGeneralSection = ({? t("priceLists.fields.type.options.sale.label"): t("priceLists.fields.type.options.override.label")+ const GENERAL_FIELD_IDS = [+ "title",+ "status",+ "type",+ "description",+ "price_overrides",+ ]+return (- <Container className="divide-y p-0">- <div className="flex items-center justify-between px-6 py-4">+ <Container className="divide-y p-0" data-testid="price-list-general-section-container">+ <div className="flex items-center justify-between px-6 py-4" data-testid="price-list-general-section-header"><DisplayField model="price_list" zone="general" id="title" data={priceList}>- <Heading>{priceList.title}</Heading>+ <Heading data-testid="price-list-general-section-title">{priceList.title}</Heading></DisplayField><div className="flex items-center gap-x-4"><DisplayField model="price_list" zone="general" id="status" data={priceList}>- <StatusBadge color={color}>{text}</StatusBadge>+ <StatusBadge color={color} data-testid="price-list-general-section-status">{text}</StatusBadge></DisplayField><ActionMenugroups={[@@ -64,47 +72,36 @@ export const PriceListGeneralSection = ({</div></div><DisplayField model="price_list" zone="general" id="type" data={priceList}>- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">- <Text leading="compact" size="small" weight="plus">+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4" data-testid="price-list-general-section-type">+ <Text leading="compact" size="small" weight="plus" data-testid="price-list-general-section-type-label">{t("fields.type")}</Text>- <Text size="small" className="text-pretty">+ <Text size="small" className="text-pretty" data-testid="price-list-general-section-type-value">{type}</Text></div></DisplayField><DisplayField model="price_list" zone="general" id="description" data={priceList}>- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">- <Text leading="compact" size="small" weight="plus">+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4" data-testid="price-list-general-section-description">+ <Text leading="compact" size="small" weight="plus" data-testid="price-list-general-section-description-label">{t("fields.description")}</Text>- <Text size="small" className="text-pretty">+ <Text size="small" className="text-pretty" data-testid="price-list-general-section-description-value">{priceList.description}</Text></div></DisplayField><DisplayField model="price_list" zone="general" id="price_overrides" data={priceList}>- <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">- <Text leading="compact" size="small" weight="plus">+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4" data-testid="price-list-general-section-price-overrides">+ <Text leading="compact" size="small" weight="plus" data-testid="price-list-general-section-price-overrides-label">{t("priceLists.fields.priceOverrides.label")}</Text>- <Text size="small" className="text-pretty">+ <Text size="small" className="text-pretty" data-testid="price-list-general-section-price-overrides-value">{overrideCount || "-"}</Text></div></DisplayField>- <DisplayExtensionZone- model="price_list"- zone="general"- data={priceList}- builtInFieldIds={[- "title",- "status",- "type",- "description",- "price_overrides",- ]}- />+ <DisplayExtensionZone model="price_list" zone="general" data={priceList} builtInFieldIds={GENERAL_FIELD_IDS} /></Container>)}diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsxindex e09f094a7..c09e56e66 100644--- a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx@@ -1,60 +1,168 @@-import { PencilSquare, Plus, Trash } from "@medusajs/icons";-import { HttpTypes } from "@medusajs/types";-import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui";-import { keepPreviousData } from "@tanstack/react-query";-import { RowSelectionState, createColumnHelper } from "@tanstack/react-table";-import { useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import { useNavigate } from "react-router-dom";--import { DisplayExtensionZone } from "@mercurjs/dashboard-shared";--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 { useDataTable } from "../../../../../hooks/use-data-table";+import {+ EllipsisHorizontal,+ ExclamationCircle,+ PencilSquare,+ Trash,+} from "@medusajs/icons"+import type { HttpTypes } from "@medusajs/types"+import {+ Button,+ Checkbox,+ Container,+ Heading,+ Text,+ toast,+ usePrompt,+} from "@medusajs/ui"+import { keepPreviousData } from "@tanstack/react-query"+import {+ ColumnDef,+ createColumnHelper,+ type RowSelectionState,+} from "@tanstack/react-table"+import { useMemo, useRef, useState } from "react"+import { useTranslation } from "react-i18next"+import { Link, useNavigate } from "react-router-dom"++import { DisplayExtensionZone } from "@mercurjs/dashboard-shared"+import { OfferDTO, ProductStatus } from "@mercurjs/types"++import { ActionMenu } from "@components/common/action-menu"+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"+import {+ CategoryCell,+ CategoryHeader,+} from "@components/table/table-cells/product/category-cell/category-cell"+import {+ ProductCell,+ ProductHeader,+} from "@components/table/table-cells/product/product-cell"+import {+ ProductStatusCell,+ ProductStatusHeader,+} from "@components/table/table-cells/product/product-status-cell"+import { _DataTable, type Filter } from "@components/table/data-table"+import { usePriceList, usePriceListLinkProducts } from "@hooks/api/price-lists"+import { useOffers } from "@hooks/api/offers"+import { useDataTable } from "@hooks/use-data-table"+import { useQueryParams } from "@hooks/use-query-params"type PriceListProductSectionProps = {- priceList: HttpTypes.AdminPriceList;-};+ priceList: HttpTypes.AdminPriceList+}++const PAGE_SIZE = 10+const PREFIX = "plo"++const OFFER_FIELDS =+ "id,variant_id,product_id,product.title,product.thumbnail,product.status,product.categories.id,product.categories.name,product.collection.id,product.collection.title"++const getPriceOfferId = (price: unknown): string | undefined => {+ const p = price as {+ rules?: Record<string, string>+ price_rules?: { attribute?: string; value?: string }[]+ }++ if (p.rules?.offer_id) {+ return p.rules.offer_id+ }-const PAGE_SIZE = 10;-const PREFIX = "p";+ return p.price_rules?.find((rule) => rule.attribute === "offer_id")?.value+}export const PriceListProductSection = ({priceList,}: PriceListProductSectionProps) => {- const { t } = useTranslation();- const navigate = useNavigate();- const prompt = usePrompt();+ const { t } = useTranslation()+ const navigate = useNavigate()+ const prompt = usePrompt()- const [rowSelection, setRowSelection] = useState<RowSelectionState>({});+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})- const { searchParams, raw } = useProductTableQuery({- pageSize: PAGE_SIZE,- prefix: PREFIX,- });- const { products, count, isLoading, isError, error } = useProducts(+ // 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 = getPriceOfferId(price)+ if (offerId) {+ ids.add(offerId)+ }+ }+ return Array.from(ids)+ }, [pricedList])++ // Search + date filters resolve server-side on /vendor/offers (which is+ // strict — it accepts q + created_at/updated_at, not product attributes).+ const raw = useQueryParams(+ ["q", "order", "offset", "created_at", "updated_at"],+ PREFIX+ )++ const { offers, isLoading, isError, error } = useOffers({- ...searchParams,- price_list_id: [priceList.id],+ id: offerIds,+ limit: offerIds.length || 1,+ fields: OFFER_FIELDS,+ order: raw.order,+ ...(raw.q ? { q: raw.q } : {}),+ ...(raw.created_at ? { created_at: JSON.parse(raw.created_at) } : {}),+ ...(raw.updated_at ? { updated_at: JSON.parse(raw.updated_at) } : {}),},{placeholderData: keepPreviousData,- },- );+ enabled: offerIds.length > 0,+ }+ )++ // One row per product (single seller); the Variants column shows how many of+ // that product's offers are in this price list.+ const groupedOffers = useMemo(() => {+ const groups = new Map<string, OfferDTO>()+ for (const offer of (offers ?? []) as OfferDTO[]) {+ const key = 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 filters = useProductTableFilters();- const columns = useColumns(priceList);- const { mutateAsync } = usePriceListLinkProducts(priceList.id);+ const columns = useColumns(priceList)+ const filters = useOfferSectionFilters()+ const { mutateAsync } = usePriceListLinkProducts(priceList.id)const { table } = useDataTable({- data: products || [],- count,+ data: groupedOffers,+ count: groupedOffers.length,columns,enablePagination: true,enableRowSelection: true,@@ -65,158 +173,174 @@ export const PriceListProductSection = ({updater: setRowSelection,},prefix: PREFIX,- });+ })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"),- });+ })if (!res) {- return;+ return}mutateAsync(- {- remove: Object.keys(rowSelection),- },+ { remove: productIds },{onSuccess: () => {toast.success(t("priceLists.products.delete.successToast", {- count: Object.keys(rowSelection).length,- }),- );-- setRowSelection({});- },- onError: (e) => {- toast.error(e.message);+ count: productIds.length,+ })+ )+ setRowSelection({})},- },- );- };+ onError: (e) => toast.error(e.message),+ }+ )+ }const handleEdit = async () => {- const ids = Object.keys(rowSelection).join(",");-- navigate(`products/edit?ids[]=${ids}`);- };-- if (isError) {- throw error;+ const ids = selectedProductIds().join(",")+ navigate(`products/edit?ids[]=${ids}`)}return (- <Container className="divide-y p-0">- <div className="flex items-center justify-between px-6 py-4">- <Heading level="h2">{t("priceLists.products.header")}</Heading>- <ActionMenu- groups={[+ <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>+ <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"+ ),+ },+ ],+ },+ ]}+ >+ <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">+ <ExclamationCircle className="text-ui-fg-subtle" />+ <Text size="small" className="text-ui-fg-subtle">+ {error?.message || t("general.error")}+ </Text>+ </div>+ ) : (+ <_DataTable+ table={table}+ columns={columns}+ filters={filters}+ count={groupedOffers.length}+ pageSize={PAGE_SIZE}+ isLoading={isLoading}+ navigateTo={(row) => `/offers/${row.original.product_id}`}+ orderBy={[+ { key: "created_at", label: t("fields.createdAt") },+ { key: "updated_at", label: t("fields.updatedAt") },+ ]}+ commands={[{- actions: [- {- label: t("priceLists.products.actions.addProducts"),- to: "products/add",- icon: <Plus />,- },- {- label: t("priceLists.products.actions.editPrices"),- to: "products/edit",- icon: <PencilSquare />,- },- ],+ action: handleEdit,+ label: t("priceLists.products.actions.editPrices"),+ shortcut: "e",+ },+ {+ action: handleDelete,+ label: t("actions.remove"),+ shortcut: "r",},]}+ pagination+ search+ prefix={PREFIX}+ queryObject={raw}/>- </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}- />- <DisplayExtensionZone- model="price_list"- zone="products"- data={priceList}- />+ )}+ <DisplayExtensionZone model="price_list" zone="products" data={priceList} /></Container>- );-};+ )+}++const useOfferSectionFilters = (): Filter[] => {+ const { t } = useTranslation()+ return [+ { label: t("fields.createdAt"), key: "created_at", type: "date" },+ { label: t("fields.updatedAt"), key: "updated_at", type: "date" },+ ]+}-const ProductRowAction = ({- product,+const OfferRowAction = ({+ offer,priceList,}: {- product: HttpTypes.AdminProduct;- priceList: HttpTypes.AdminPriceList;+ offer: OfferDTO+ priceList: HttpTypes.AdminPriceList}) => {- const { t } = useTranslation();- const prompt = usePrompt();- const { mutateAsync } = usePriceListLinkProducts(priceList.id);+ const { t } = useTranslation()+ const prompt = usePrompt()+ const { mutateAsync } = usePriceListLinkProducts(priceList.id)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"),- });+ })if (!res) {- return;+ return}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),+ }+ )+ }return (<ActionMenu@@ -226,7 +350,7 @@ const ProductRowAction = ({{icon: <PencilSquare />,label: t("priceLists.products.actions.editPrices"),- to: `products/edit?ids[]=${product.id}`,+ to: `products/edit?ids[]=${offer.product_id}`,},],},@@ -241,52 +365,96 @@ const ProductRowAction = ({},]}/>- );-};+ )+}-const columnHelper = createColumnHelper<HttpTypes.AdminProduct>();+const columnHelper = createColumnHelper<OfferDTO>()const useColumns = (priceList: HttpTypes.AdminPriceList) => {- const base = useProductTableColumns();+ const { t } = useTranslation()- return useMemo(+ return useMemo<ColumnDef<OfferDTO>[]>(() => [columnHelper.display({id: "select",- header: ({ table }) => {+ header: ({ table }) => (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()+ }+ onCheckedChange={(value) =>+ table.toggleAllPageRowsSelected(!!value)+ }+ />+ ),+ cell: ({ row }) => (+ <Checkbox+ checked={row.getIsSelected()}+ onCheckedChange={(value) => row.toggleSelected(!!value)}+ onClick={(e) => e.stopPropagation()}+ />+ ),+ }),+ columnHelper.display({+ id: "offer",+ header: () => <ProductHeader />,+ cell: ({ row }) => (+ <ProductCell+ product={{+ title: row.original.product?.title ?? "",+ thumbnail: row.original.product?.thumbnail ?? null,+ }}+ />+ ),+ }),+ columnHelper.display({+ id: "category",+ header: () => <CategoryHeader />,+ cell: ({ row }) => (+ <CategoryCell+ categories={(row.original.product?.categories ?? undefined) as never}+ />+ ),+ }),+ columnHelper.display({+ id: "variants",+ header: () => (+ <div className="flex h-full w-full items-center">+ <span>{t("fields.variants")}</span>+ </div>+ ),+ cell: ({ row }) => {+ const count = row.original.variant_count+ if (!count) {+ return <PlaceholderCell />+ }return (- <Checkbox- checked={- table.getIsSomePageRowsSelected()- ? "indeterminate"- : table.getIsAllPageRowsSelected()- }- onCheckedChange={(value) =>- table.toggleAllPageRowsSelected(!!value)- }- />- );+ <Text size="small" leading="compact" className="truncate">+ {t("offers.fields.variantsCount", { count })}+ </Text>+ )},+ }),+ columnHelper.display({+ id: "status",+ header: () => <ProductStatusHeader />,cell: ({ row }) => {- return (- <Checkbox- checked={row.getIsSelected()}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => {- e.stopPropagation();- }}- />- );+ const status = row.original.product?.status+ if (!status) {+ return <PlaceholderCell />+ }+ return <ProductStatusCell status={status as ProductStatus} />},}),- ...base,columnHelper.display({id: "actions",cell: ({ row }) => (- <ProductRowAction product={row.original} priceList={priceList} />+ <OfferRowAction offer={row.original} priceList={priceList} />),}),],- [base, priceList],- );-};+ [t, priceList]+ )+}diff --git a/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx b/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsxindex aea5e8a69..2f517e7cf 100644--- a/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx@@ -1,9 +1,10 @@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 "./price-list-configuration-form";export const Component = () => {@@ -12,40 +13,12 @@ export const Component = () => {const { price_list, isPending, isError, error } = usePriceList(id!);- // const customerGroupIds =- // price_list?.price_list_rules?.find(- // (rule: any) => rule.attribute === "customer.groups.id",- // )?.value || ([] as string[]);-- // const {- // customer_groups: customerGroupsData,- // isPending: isCustomerGroupsPending,- // isError: isCustomerGroupsError,- // error: customerGroupsError,- // } = useCustomerGroups(undefined, { enabled: !!customerGroupIds?.length })-- // const customerGroups = customerGroupsData?.map((item) => item.customer_group)-- // const initialCustomerGroups = (customerGroups || []).filter((group) =>- // customerGroupIds.includes(group.id)- // )-- // const isCustomerGroupsReady = isPending- // ? false- // : !!customerGroupIds?.length && isCustomerGroupsPending- // ? false- // : true-- const ready = !isPending && !!price_list; // && isCustomerGroupsReady+ const ready = !isPending && !!price_list;if (isError) {throw error;}- // if (isCustomerGroupsError) {- // throw customerGroupsError;- // }-return (<RouteDrawer><RouteDrawer.Header>@@ -53,12 +26,7 @@ export const Component = () => {<Heading>{t("priceLists.configuration.edit.header")}</Heading></RouteDrawer.Title></RouteDrawer.Header>- {ready && (- <PriceListConfigurationForm- priceList={price_list}- customerGroups={[]}- />- )}+ {ready && <PriceListConfigurationForm priceList={price_list} />}</RouteDrawer>);};diff --git a/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsxindex 81da54ebb..61c322e62 100644--- a/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx@@ -1,12 +1,7 @@import { zodResolver } from "@hookform/resolvers/zod"import { HttpTypes } from "@medusajs/types"-import {- Button,- DatePicker,- Divider,- 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"@@ -17,66 +12,34 @@ import { useUpdatePriceList } from "@hooks/api/price-lists"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(),- })- ),})--export const PriceListConfigurationForm = ({priceList,- customerGroups,}: PriceListConfigurationFormProps) => {const { t } = useTranslation()const { handleSuccess } = useRouteModal()-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 { remove: _remove } = useFieldArray({- control: form.control,- name: "customer_group_id",- keyName: "cg_id",- })---const { mutateAsync } = useUpdatePriceList(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- const rules = { ...priceList.rules } // preserve other rules set on the PL-- /* TODO: Customer group availability - vendor API does not support customer groups yet- const groupIds = values.customer_group_id.map((group) => group.id)- 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: () => {@@ -89,7 +52,7 @@ export const PriceListConfigurationForm = ({})return (- <RouteDrawer.Form form={form}>+ <RouteDrawer.Form form={form} data-testid="price-list-configuration-form"><RouteDrawer.Description className="sr-only">{t("priceLists.configuration.edit.description")}</RouteDrawer.Description>@@ -97,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">+ <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"@@ -105,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"@@ -126,7 +84,6 @@ export const PriceListConfigurationForm = ({)}}/>- <Divider /><Form.Fieldcontrol={form.control}name="ends_at"@@ -134,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"@@ -155,126 +107,15 @@ export const PriceListConfigurationForm = ({)}}/>- {/* TODO: Customer group availability - vendor API does not support customer groups yet- <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">- <StackedDrawer id={STACKED_MODAL_ID}>- <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"- >- <MagnifyingGlass />- {t(- "priceLists.fields.customerAvailability.placeholder"- )}- </button>- </StackedDrawer.Trigger>- <StackedDrawer.Trigger asChild>- <Button variant="secondary">- {t("actions.browse")}- </Button>- </StackedDrawer.Trigger>- <StackedDrawer.Content>- <StackedDrawer.Header>- <StackedDrawer.Title asChild>- <Heading>- {t(- "priceLists.fields.customerAvailability.header"- )}- </Heading>- </StackedDrawer.Title>- <StackedDrawer.Description className="sr-only">- {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">- <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"- >- <Text size="small" leading="compact">- {field.name}- </Text>- <IconButton- size="small"- variant="transparent"- type="button"- onClick={() => remove(index)}- >- <XMark />- </IconButton>- </div>- )- })}- </div>- </div>- ) : null}- </div>- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}- />- */}</RouteDrawer.Body>- <RouteDrawer.Footer className="shrink-0">+ <RouteDrawer.Footer className="shrink-0" data-testid="price-list-configuration-form-footer"><div className="flex items-center justify-end gap-x-2"><RouteDrawer.Close asChild>- <Button size="small" variant="secondary">+ <Button size="small" variant="secondary" data-testid="price-list-configuration-form-cancel-button">{t("actions.cancel")}</Button></RouteDrawer.Close>- <Button size="small" type="submit">+ <Button size="small" type="submit" data-testid="price-list-configuration-form-save-button">{t("actions.save")}</Button></div>diff --git a/packages/vendor/src/pages/price-lists/[id]/customer-availability/index.tsx b/packages/vendor/src/pages/price-lists/[id]/customer-availability/index.tsxnew file mode 100644index 000000000..876861f81--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/customer-availability/index.tsx@@ -0,0 +1,68 @@+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 "./price-list-customer-availability-form";++export const Component = () => {+ 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/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/index.ts b/packages/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/index.tsnew file mode 100644index 000000000..9fb81b45e--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/index.ts@@ -0,0 +1 @@+export * from "./price-list-customer-availability-form"diff --git a/packages/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/price-list-customer-availability-form.tsx b/packages/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/price-list-customer-availability-form.tsxnew file mode 100644index 000000000..2acea1dfb--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/customer-availability/price-list-customer-availability-form/price-list-customer-availability-form.tsx@@ -0,0 +1,101 @@+import { zodResolver } from "@hookform/resolvers/zod"+import { HttpTypes } from "@medusajs/types"+import { Button, Heading, Text, toast } from "@medusajs/ui"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import { z } from "zod"++import { RouteDrawer, useRouteModal } from "@components/modals"+import { KeyboundForm } from "@components/utilities/keybound-form"+import { useUpdatePriceList } from "@hooks/api/price-lists"+import { PriceListCustomerAvailabilitySelector } from "@pages/price-lists/common/components/price-list-customer-availability-selector"++type PriceListCustomerAvailabilityFormProps = {+ priceList: HttpTypes.AdminPriceList+ customerGroups: { id: string; name: string }[]+}++const PriceListCustomerAvailabilitySchema = z.object({+ customer_group_id: z+ .array(z.object({ id: z.string(), name: z.string() }))+ .default([]),+})++export const PriceListCustomerAvailabilityForm = ({+ priceList,+ customerGroups,+}: PriceListCustomerAvailabilityFormProps) => {+ const { t } = useTranslation()+ const { handleSuccess } = useRouteModal()++ const form = useForm<z.infer<typeof PriceListCustomerAvailabilitySchema>>({+ defaultValues: {+ customer_group_id: customerGroups,+ },+ resolver: zodResolver(PriceListCustomerAvailabilitySchema),+ })++ const { mutateAsync, isPending } = useUpdatePriceList(priceList.id)++ const handleSubmit = form.handleSubmit(async (values) => {+ const rules = { ...priceList.rules }++ if (values.customer_group_id.length) {+ rules["customer.groups.id"] = values.customer_group_id.map(+ (group) => group.id+ )+ } 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">+ <div className="flex flex-col gap-y-1">+ <Heading level="h2">+ {t("priceLists.fields.customerAvailability.label")}+ </Heading>+ <Text size="small" className="text-ui-fg-subtle">+ {t("priceLists.fields.customerAvailability.hint")}+ </Text>+ </div>+ <PriceListCustomerAvailabilitySelector+ control={form.control}+ name="customer_group_id"+ />+ </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" isLoading={isPending} data-testid="price-list-customer-availability-form-save-button">+ {t("actions.save")}+ </Button>+ </div>+ </RouteDrawer.Footer>+ </KeyboundForm>+ </RouteDrawer.Form>+ )+}diff --git a/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsx b/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsxindex 65c403be2..282909b10 100644--- a/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/edit/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"@@ -19,6 +12,7 @@ import { Form } from "@components/common/form"import { RouteDrawer, useRouteModal } from "@components/modals"import { KeyboundForm } from "@components/utilities/keybound-form"import { useUpdatePriceList } from "@hooks/api/price-lists"+import { useDocumentDirection } from "@hooks/use-document-direction"import { PriceListStatus, PriceListType } from "../../../common/constants"type PriceListEditFormProps = {@@ -29,13 +23,13 @@ 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) => {const { t } = useTranslation()const { handleSuccess } = useRouteModal()-+ const direction = useDocumentDirection()const form = useExtendableForm({schema: PriceListEditSchema,model: "price_list",@@ -52,9 +46,13 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {const { mutateAsync, isPending } = useUpdatePriceList(priceList.id)const handleSubmit = form.handleSubmit(async (values) => {- const { status, type, title, description } = values+ const { additional_data, ...rest } = values+ const payload =+ additional_data && Object.keys(additional_data).length+ ? { ...rest, additional_data }+ : rest- await mutateAsync({ status, type, title, description }, {+ await mutateAsync(payload, {onSuccess: ({ price_list }) => {toast.success(t("priceLists.edit.successToast", {@@ -71,30 +69,36 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {})return (- <RouteDrawer.Form form={form}>+ <RouteDrawer.Form form={form} data-testid="price-list-edit-form"><KeyboundFormclassName="flex flex-1 flex-col overflow-hidden"onSubmit={handleSubmit}>- <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-auto">+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-auto" data-testid="price-list-edit-form-body"><Form.Fieldcontrol={form.control}name="type"render={({ field: { onChange, ...field } }) => {return (- <Form.Item>+ <Form.Item data-testid="price-list-edit-form-type-item"><div>- <Form.Label>{t("priceLists.fields.type.label")}</Form.Label>- <Form.Hint>{t("priceLists.fields.type.hint")}</Form.Hint>+ <Form.Label data-testid="price-list-edit-form-type-label">{t("priceLists.fields.type.label")}</Form.Label>+ <Form.Hint data-testid="price-list-edit-form-type-hint">{t("priceLists.fields.type.hint")}</Form.Hint></div>- <Form.Control>- <RadioGroup {...field} onValueChange={onChange}>+ <Form.Control data-testid="price-list-edit-form-type-control">+ <RadioGroup+ dir={direction}+ {...field}+ onValueChange={onChange}+ data-testid="price-list-edit-form-type-radio-group"+ ><RadioGroup.ChoiceBoxvalue={PriceListType.SALE}label={t("priceLists.fields.type.options.sale.label")}description={t("priceLists.fields.type.options.sale.description")}+ data-testid="price-list-edit-form-type-option-sale"/><RadioGroup.ChoiceBoxvalue={PriceListType.OVERRIDE}@@ -104,10 +108,11 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {description={t("priceLists.fields.type.options.override.description")}+ data-testid="price-list-edit-form-type-option-override"/></RadioGroup></Form.Control>- <Form.ErrorMessage />+ <Form.ErrorMessage data-testid="price-list-edit-form-type-error" /></Form.Item>)}}@@ -115,44 +120,54 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {<div className="flex flex-col gap-y-4"><Form.Fieldcontrol={form.control}- name="title"- render={({ field }) => {+ name="status"+ render={({ field: { onChange, ...rest } }) => {return (- <Form.Item>- <Form.Label>{t("fields.title")}</Form.Label>- <Form.Control>- <Input {...field} />+ <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">+ <RadioGroup+ dir={direction}+ onValueChange={onChange}+ {...rest}+ data-testid="price-list-edit-form-status-radio-group"+ >+ <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 />+ <Form.ErrorMessage data-testid="price-list-edit-form-status-error" /></Form.Item>)}}/><Form.Fieldcontrol={form.control}- name="status"- render={({ field: { onChange, ref, ...field } }) => {+ name="title"+ render={({ field }) => {return (- <Form.Item>- <Form.Label>- {t("priceLists.fields.status.label")}- </Form.Label>- <Form.Control>- <Select {...field} onValueChange={onChange}>- <Select.Trigger ref={ref}>- <Select.Value />- </Select.Trigger>- <Select.Content>- <Select.Item value={PriceListStatus.ACTIVE}>- {t("priceLists.fields.status.options.active")}- </Select.Item>- <Select.Item value={PriceListStatus.DRAFT}>- {t("priceLists.fields.status.options.draft")}- </Select.Item>- </Select.Content>- </Select>+ <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 />+ <Form.ErrorMessage data-testid="price-list-edit-form-title-error" /></Form.Item>)}}@@ -162,12 +177,12 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {name="description"render={({ field }) => {return (- <Form.Item>- <Form.Label>{t("fields.description")}</Form.Label>- <Form.Control>- <Textarea {...field} />+ <Form.Item data-testid="price-list-edit-form-description-item">+ <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>- <Form.ErrorMessage />+ <Form.ErrorMessage data-testid="price-list-edit-form-description-error" /></Form.Item>)}}@@ -180,14 +195,14 @@ export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {data={priceList}/></RouteDrawer.Body>- <RouteDrawer.Footer className="shrink-0">+ <RouteDrawer.Footer className="shrink-0" data-testid="price-list-edit-form-footer"><div className="flex items-center justify-end gap-x-2"><RouteDrawer.Close asChild>- <Button size="small" variant="secondary">+ <Button size="small" variant="secondary" data-testid="price-list-edit-form-cancel-button">{t("actions.cancel")}</Button></RouteDrawer.Close>- <Button size="small" type="submit" isLoading={isPending}>+ <Button size="small" type="submit" isLoading={isPending} data-testid="price-list-edit-form-save-button">{t("actions.save")}</Button></div>diff --git a/packages/vendor/src/pages/price-lists/[id]/price-list-detail-page.tsx b/packages/vendor/src/pages/price-lists/[id]/price-list-detail-page.tsxindex cd2ec59da..f68302e54 100644--- a/packages/vendor/src/pages/price-lists/[id]/price-list-detail-page.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/price-list-detail-page.tsx@@ -7,6 +7,7 @@ import { useLinkQuery, WidgetZone } from "@mercurjs/dashboard-shared";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";@@ -16,7 +17,7 @@ const Root = ({ children }: { children?: ReactNode }) => {const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>;const { id } = useParams();- const linkQuery = useLinkQuery("price_list");+ const linkQuery = useLinkQuery("price_list", "+prices.id");const { price_list, isLoading, isError, error } = usePriceList(id!, linkQuery, {placeholderData: initialData,});@@ -40,6 +41,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>@@ -58,6 +60,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/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsxindex 25c1ef828..d4d4e8852 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx@@ -2,30 +2,24 @@import { useTranslation } from "react-i18next"import { useParams } from "react-router-dom"import { RouteFocusModal } from "@components/modals"-import { usePriceList, usePriceListProducts } from "@hooks/api/price-lists"-import { usePriceListCurrencyData } from "../../../../common/hooks/use-price-list-currency-data"+import { usePriceListEditGrid } from "./price-list-prices-edit-form/use-price-list-edit-grid"import { PriceListPricesEditForm } from "./price-list-prices-edit-form"export const Component = () => {const { t } = useTranslation()const { id } = useParams()- const { price_list, isLoading, isError, error } = usePriceList(id!)const {- products,- isLoading: isProductsLoading,- isError: isProductsError,- error: productError,- } = usePriceListProducts(id!)-- const priceListCurrencyData = usePriceListCurrencyData()-- const ready =- !isLoading &&- !!price_list &&- !isProductsLoading &&- !!products &&- priceListCurrencyData.isReady+ price_list,+ gridData,+ variantIdByOffer,+ currencyData,+ ready,+ isError,+ error,+ isProductsError,+ productError,+ } = usePriceListEditGrid(id!)if (isError) {throw error@@ -36,7 +30,7 @@ export const Component = () => {}return (- <RouteFocusModal>+ <RouteFocusModal prev={`/price-lists/${id}`}><RouteFocusModal.Title asChild><span className="sr-only">{t("priceLists.products.edit.title", { title: price_list?.title })}@@ -48,8 +42,11 @@ export const Component = () => {{ready && (<PriceListPricesEditFormpriceList={price_list}- products={products}- {...priceListCurrencyData}+ gridData={gridData}+ variantIdByOffer={variantIdByOffer}+ regions={currencyData.regions}+ currencies={currencyData.currencies}+ pricePreferences={currencyData.pricePreferences}/>)}</RouteFocusModal>diff --git a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsxindex e834dc9c4..af79eee97 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx@@ -1,63 +1,64 @@-import { DataGrid } from "@/components/data-grid";-import { RouteFocusModal, useRouteModal } from "@/components/modals";-import { KeyboundForm } from "@/components/utilities/keybound-form";-import { useBatchPriceListPrices } from "@/hooks/api";-import { castNumber } from "@/lib/cast-number";-import { usePriceListGridColumns } from "@/pages/price-lists/common/hooks/use-price-list-grid-columns";+import { zodResolver } from "@hookform/resolvers/zod"+import { HttpTypes } from "@medusajs/types"+import { Button, toast } from "@medusajs/ui"+import { useRef } from "react"+import { useForm } from "react-hook-form"+import { useTranslation } from "react-i18next"+import { z } from "zod"++import { DataGrid } from "@components/data-grid"+import { RouteFocusModal, useRouteModal } from "@components/modals"+import { KeyboundForm } from "@components/utilities/keybound-form"+import { useBatchPriceListPrices } from "@hooks/api/price-lists"+import { castNumber } from "@lib/cast-number"import {- PriceListUpdateProductsSchema,- PriceListUpdateProductVariantsSchema,-} from "@/pages/price-lists/common/schemas";-import { isProductRow } from "@/pages/price-lists/common/utils";-import { zodResolver } from "@hookform/resolvers/zod";-import { HttpTypes } from "@medusajs/types";-import { Button, toast } from "@medusajs/ui";-import { useRef } from "react";-import { useForm } from "react-hook-form";-import { useTranslation } from "react-i18next";-import { z } from "zod";+ PriceListGridRow,+ usePriceListGridColumns,+} from "@pages/price-lists/common/hooks/use-price-list-grid-columns"+import { PriceListUpdateOffersSchema } from "@pages/price-lists/common/schemas"type PriceListPricesEditFormProps = {- priceList: HttpTypes.AdminPriceList;- products: HttpTypes.AdminProduct[];- regions: HttpTypes.AdminRegion[];- currencies: string[];- pricePreferences: HttpTypes.AdminPricePreference[];-};+ priceList: HttpTypes.AdminPriceList+ gridData: PriceListGridRow[]+ variantIdByOffer: Record<string, string>+ regions: HttpTypes.AdminRegion[]+ currencies: string[]+ 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,}: PriceListPricesEditFormProps) => {- const { t } = useTranslation();- const { handleSuccess, setCloseOnEscape } = useRouteModal();+ const { t } = useTranslation()+ const { handleSuccess, setCloseOnEscape } = useRouteModal()- const initialValue = useRef(initRecord(priceList, products));+ const initialValue = useRef(initRecord(priceList, variantIdByOffer))- 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 { 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,- );+ variantIdByOffer+ )mutateAsync({@@ -67,22 +68,21 @@ export const PriceListPricesEditForm = ({},{onSuccess: () => {- toast.success(t("priceLists.products.edit.successToast"));-- handleSuccess();+ toast.success(t("priceLists.products.edit.successToast"))+ handleSuccess()},onError: (error) => {- toast.error(error.message);+ toast.error(error.message)},- },- );- });+ }+ )+ })const columns = usePriceListGridColumns({currencies,regions,pricePreferences,- });+ })return (<RouteFocusModal.Form form={form}>@@ -91,12 +91,7 @@ export const PriceListPricesEditForm = ({<RouteFocusModal.Body className="flex flex-col overflow-hidden"><DataGridcolumns={columns}- data={products}- getSubRows={(row) => {- if (isProductRow(row) && row.variants) {- return row.variants;- }- }}+ data={gridData}state={form}onEditingChange={(editing) => setCloseOnEscape(!editing)}/>@@ -115,165 +110,159 @@ export const PriceListPricesEditForm = ({</RouteFocusModal.Footer></KeyboundForm></RouteFocusModal.Form>- );-};+ )+}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;+ variantIdByOffer: Record<string, string> = {}+): PriceListUpdateOffersSchema {+ const record: PriceListUpdateOffersSchema = {}++ // Seed every offer shown in the grid with its variant_id, so editing a+ // variant that had no price yet still yields a valid offer entry+ // (variant_id is required by the schema).+ for (const [offerId, variantId] of Object.entries(variantIdByOffer)) {+ record[offerId] = {+ variant_id: variantId,+ currency_prices: {},+ region_prices: {},+ }+ }- if (isRegionPrice) {- const regionId = price.rules.region_id as string;+ 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;+ return record}type PriceObject = {- variantId: string;- currencyCode: string;- regionId?: string;- amount: number;- id?: string | null;-};+ offerId: string+ variantId: string+ currencyCode: string+ regionId?: string+ amount: number+ id?: string | null+}function convertToPriceArray(- data: PriceListUpdateProductsSchema,- regions: HttpTypes.AdminRegion[],+ data: PriceListUpdateOffersSchema,+ regions: HttpTypes.AdminRegion[]) {- const prices: PriceObject[] = [];+ const prices: PriceObject[] = []const regionCurrencyMap = regions.reduce((map, region) => {- map[region.id] = region.currency_code;- return map;+ map[region.id] = region.currency_code+ 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,- });- }+ {} as Record<string, string>+ )++ 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,+ })}}}- return prices;+ return prices}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[] = [];- const pricesToDelete: string[] = [];+ const pricesToUpdate: HttpTypes.AdminUpdatePriceListPrice[] = []+ const pricesToCreate: HttpTypes.AdminCreatePriceListPrice[] = []+ const pricesToDelete: string[] = []const initialPriceMap = initialPrices.reduce((map, price) => {- map[createMapKey(price)] = price;- return map;+ map[createMapKey(price)] = price+ return map},- {} as Record<string, (typeof initialPrices)[0]>,- );+ {} as Record<string, PriceObject>+ )const newPriceMap = newPrices.reduce((map, price) => {- map[createMapKey(price)] = price;- return map;+ map[createMapKey(price)] = price+ return map},- {} as Record<string, (typeof newPrices)[0]>,- );+ {} as Record<string, PriceObject>+ )const keys = new Set([...Object.keys(initialPriceMap),...Object.keys(newPriceMap),- ]);+ ])for (const key of keys) {- const initialPrice = initialPriceMap[key];- const newPrice = newPriceMap[key];+ const initialPrice = initialPriceMap[key]+ const newPrice = newPriceMap[key]if (initialPrice && newPrice) {if (isNaN(newPrice.amount) && newPrice.id) {- pricesToDelete.push(newPrice.id);+ pricesToDelete.push(newPrice.id)}if (initialPrice.amount !== newPrice.amount && newPrice.id) {@@ -281,11 +270,9 @@ 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,- });+ })}}@@ -293,26 +280,27 @@ 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,- });+ })}if (initialPrice && !newPrice && initialPrice.id) {- pricesToDelete.push(initialPrice.id);+ pricesToDelete.push(initialPrice.id)}}- return { pricesToDelete, pricesToCreate, pricesToUpdate };+ return { pricesToDelete, pricesToCreate, pricesToUpdate }}function sortPrices(- data: PriceListUpdateProductsSchema,- initialValue: PriceListUpdateProductsSchema,+ data: PriceListUpdateOffersSchema,+ initialValue: PriceListUpdateOffersSchema,regions: HttpTypes.AdminRegion[],+ _variantIdByOffer: Record<string, string>) {- const initialPrices = convertToPriceArray(initialValue, regions);- const newPrices = convertToPriceArray(data, regions);+ const initialPrices = convertToPriceArray(initialValue, regions)+ const newPrices = convertToPriceArray(data, regions)- return comparePrices(initialPrices, newPrices);+ return comparePrices(initialPrices, newPrices)}diff --git a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/use-price-list-edit-grid.tsx b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/use-price-list-edit-grid.tsxnew file mode 100644index 000000000..0615a0436--- /dev/null+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/use-price-list-edit-grid.tsx@@ -0,0 +1,140 @@+import { OfferDTO } from "@mercurjs/types"+import { buildOfferGridData } from "@mercurjs/dashboard-shared"+import { useMemo } from "react"++import { useOffers } from "@hooks/api/offers"+import { usePriceList } from "@hooks/api/price-lists"+import { useProducts } from "@hooks/api/products"+import { usePriceListCurrencyData } from "@pages/price-lists/common/hooks/use-price-list-currency-data"++type PriceRuleShape = {+ rules?: Record<string, string> | null+ price_rules?: { attribute?: string | null; value?: string | null }[] | null+}++const extractOfferId = (price: PriceRuleShape) =>+ price.rules?.offer_id ??+ price.price_rules?.find((r) => r.attribute === "offer_id")?.value ??+ undefined++/**+ * Builds the offer-keyed grid for the edit-prices flow: resolve the priced+ * offers → their products, then show every one of the seller's offers for those+ * products (so untouched variants can also be priced). Prices carry `offer_id`+ * so overrides stay scoped to the seller's offer.+ */+export const usePriceListEditGrid = (+ id: string,+ productFilter?: string[]+) => {+ const { price_list, isLoading, isError, error } = usePriceList(id, {+ fields:+ "id,title,+prices.amount,+prices.currency_code,+prices.price_set.variant.id,+prices.price_rules.attribute,+prices.price_rules.value",+ })++ const offerIds = useMemo(() => {+ const set = new Set<string>()+ for (const price of (price_list?.prices ?? []) as PriceRuleShape[]) {+ const offerId = extractOfferId(price)+ if (offerId) {+ set.add(offerId)+ }+ }+ return Array.from(set)+ }, [price_list])++ const { offers: pricedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds.length || 1,+ fields: "id,product_id",+ },+ { enabled: offerIds.length > 0 }+ )++ const pricedProductIds = useMemo(() => {+ const set = new Set<string>()+ for (const offer of (pricedOffers ?? []) as OfferDTO[]) {+ set.add(offer.product_id)+ }+ return set+ }, [pricedOffers])++ // Vendor offers are auto seller-scoped by the API; fetch them all and filter+ // to the priced products client-side (the route has no product_id filter).+ const { offers: allOffers } = useOffers(+ {+ limit: 1000,+ fields:+ "id,variant_id,product_id,sku,product.title,product.thumbnail",+ },+ { enabled: pricedProductIds.size > 0 }+ )++ const scopedOffers = useMemo(() => {+ const allowed = productFilter ? new Set(productFilter) : undefined+ return ((allOffers ?? []) as OfferDTO[]).filter(+ (o) =>+ pricedProductIds.has(o.product_id) &&+ (!allowed || allowed.has(o.product_id))+ )+ }, [allOffers, pricedProductIds, 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 || 1,+ fields: "id,*variants",+ },+ { enabled: productIds.length > 0 }+ )++ const { gridData, variantIdByOffer } = useMemo(+ () =>+ buildOfferGridData(+ scopedOffers,+ (products ?? []) as {+ variants?: { id: string; title?: string | null }[] | null+ }[]+ ),+ [scopedOffers, products]+ )++ const currencyData = usePriceListCurrencyData()++ // Only render once the grid data is fully built, so the form/DataGrid doesn't+ // mount with an empty grid and then flicker as the staged fetches resolve.+ const gridDataReady =+ offerIds.length === 0 ||+ (allOffers !== undefined &&+ (productIds.length === 0 || products !== undefined))++ const ready =+ currencyData.isReady &&+ !isLoading &&+ !!price_list &&+ !isProductsLoading &&+ gridDataReady++ return {+ price_list,+ gridData,+ variantIdByOffer,+ currencyData,+ ready,+ isError,+ error,+ isProductsError,+ productError,+ }+}diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsxindex 3219c1610..3d327ce5d 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx@@ -10,7 +10,7 @@ import { z } from "zod";import { RouteFocusModal, useRouteModal } from "@components/modals";import { KeyboundForm } from "@components/utilities/keybound-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 {@@ -55,8 +55,9 @@ export const PriceListPricesAddForm = ({const form = useForm<PriceListPricesAddSchema>({defaultValues: {- products: {},+ offers: {},product_ids: [],+ offer_ids: [],},resolver: zodResolver(PriceListPricesAddSchema),});@@ -65,9 +66,9 @@ export const PriceListPricesAddForm = ({const handleSubmit = form.handleSubmit(async (values) => {- const { products } = values;+ const { offers } = values;- const prices = exctractPricesFromProducts(products, regions);+ const prices = extractPricesFromOffers(offers, regions);await mutateAsync({@@ -83,7 +84,7 @@ export const PriceListPricesAddForm = ({);},(errors) => {- if (errors.products) {+ if (errors.offers) {toast.error(t("priceLists.products.add.atLeastOnePrice"));}},diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsxindex 88c637c3e..21683339c 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx@@ -1,102 +1,103 @@-import { useEffect } from 'react';--import { HttpTypes } from '@medusajs/types';-import { UseFormReturn, useWatch } from 'react-hook-form';+import { HttpTypes } from "@medusajs/types"+import { OfferDTO } from "@mercurjs/types"+import { buildOfferGridData } from "@mercurjs/dashboard-shared"+import { useEffect, useMemo } from "react"+import { UseFormReturn, useWatch } from "react-hook-form"import { DataGrid } from "@components/data-grid"import { useRouteModal } from "@components/modals"+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 { PriceListPricesAddSchema } from './schema';+import {+ PriceListGridRow,+ usePriceListGridColumns,+} from "../../../../common/hooks/use-price-list-grid-columns"+import { PriceListPricesAddSchema } from "./schema"type PriceListPricesAddPricesFormProps = {- form: UseFormReturn<PriceListPricesAddSchema>;- currencies: string[];- regions: HttpTypes.AdminRegion[];- pricePreferences: HttpTypes.AdminPricePreference[];-};+ form: UseFormReturn<PriceListPricesAddSchema>+ currencies: string[]+ regions: HttpTypes.AdminRegion[]+ pricePreferences: HttpTypes.AdminPricePreference[]+}++const OFFER_GRID_FIELDS =+ "id,variant_id,product_id,sku,product.title,product.thumbnail"export const PriceListPricesAddPricesForm = ({form,currencies,regions,- pricePreferences+ pricePreferences,}: PriceListPricesAddPricesFormProps) => {- const ids = useWatch({- control: form.control,- name: 'product_ids'- });+ const { setValue } = form+ const { setCloseOnEscape } = useRouteModal()- const existingProducts = useWatch({- control: form.control,- name: 'products'- });+ const offerIds = useWatch({ control: form.control, name: "offer_ids" })+ const existingOffers = useWatch({ control: form.control, name: "offers" })- const {- products: productsRaw,- isLoading,- isError,- error- } = useProducts({- fields: 'title,thumbnail,*variants,+status, *variants.prices'- });+ const { offers: selectedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds?.length || 1,+ fields: OFFER_GRID_FIELDS,+ },+ { enabled: (offerIds?.length ?? 0) > 0 }+ )- const products = productsRaw?.filter(product => ids.some(id => id.id === product.id));+ const productIds = useMemo(+ () =>+ Array.from(+ new Set(+ ((selectedOffers ?? []) as OfferDTO[]).map((o) => 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 ?? []) as {+ variants?: { id: string; title?: string | null }[] | null+ }[]+ ),+ [selectedOffers, products]+ )useEffect(() => {- if (!isLoading && products) {- products.forEach(product => {- /**- * If the product already exists in the form, we don't want to overwrite it.- */- 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,regions,pricePreferences,- showCurrentPriceCell: true- });-- 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)}+ onEditingChange={(editing) => setCloseOnEscape(!editing)}/></div>- );-};+ )+}diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsxindex 0c73c7932..e29f5b6a5 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx@@ -1,124 +1,119 @@-import { HttpTypes } from "@medusajs/types";-import { Checkbox, Tooltip } from "@medusajs/ui";-import { keepPreviousData } from "@tanstack/react-query";+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 { UseFormReturn, useWatch } from "react-hook-form";-import { useTranslation } from "react-i18next";-import { PriceListPricesAddSchema } from "./schema";-import { PriceListCreateProductsSchema } from "@/pages/price-lists/common/schemas";-import { useProductTableFilters } from "@/hooks/table/filters";-import { useDataTable } from "@/hooks/use-data-table";-import { _DataTable } from "@/components/table/data-table";-import { useProductTableColumns } from "@/hooks/table/columns";-import { useProducts } from "@/hooks/api";-import { useProductTableQuery } from "@/hooks/table/query";+} from "@tanstack/react-table"+import { useMemo, useRef, useState } from "react"+import { UseFormReturn } from "react-hook-form"+import { useTranslation } from "react-i18next"++import { _DataTable } from "@components/table/data-table"+import { useProducts } from "@hooks/api/products"+import { useDataTable } from "@hooks/use-data-table"+import {+ collectOfferIds,+ useOfferTableColumns,+ useOfferTableFilters,+ useOfferTableQuery,+} from "@pages/offers/_components"+import { OfferProduct } from "@pages/offers/common/types"+import { PriceListPricesAddSchema } from "./schema"type PriceListPricesAddProductIdsFormProps = {- form: UseFormReturn<PriceListPricesAddSchema>;- priceList: HttpTypes.AdminPriceList;-};--const PAGE_SIZE = 50;-const PREFIX = "p";--function getInitialSelection(products: { id: string }[]) {- return products.reduce((acc, curr) => {- acc[curr.id] = true;- return acc;- }, {} as RowSelectionState);+ form: UseFormReturn<PriceListPricesAddSchema>+ priceList: HttpTypes.AdminPriceList+}++const PAGE_SIZE = 50+const PREFIX = "p"++type PriceRuleShape = {+ rules?: Record<string, string> | null+ price_rules?: { attribute?: string | null; value?: string | null }[] | null}+const extractOfferId = (price: PriceRuleShape) =>+ price.rules?.offer_id ??+ price.price_rules?.find((r) => r.attribute === "offer_id")?.value ??+ undefined+export const PriceListPricesAddProductIdsForm = ({priceList,form,}: PriceListPricesAddProductIdsFormProps) => {- const { t } = useTranslation();- const { control, 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",- });-- const productRecords = useWatch({- control,- name: "products",- });+ const { t } = useTranslation()+ const { setValue } = form++ // Offers already in this price list are disabled so they can't be re-added.+ const existingOfferIds = useMemo(() => {+ const set = new Set<string>()+ for (const price of (priceList.prices ?? []) as PriceRuleShape[]) {+ const offerId = extractOfferId(price)+ if (offerId) {+ set.add(offerId)+ }+ }+ return set+ }, [priceList])- 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,- },- );-- 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];- }+ { placeholderData: keepPreviousData }+ )- return acc;- }, {} as PriceListCreateProductsSchema);+ const rows = (products ?? []) as OfferProduct[]- const update = ids.map((id) => ({ id }));-- setValue("product_ids", update, { shouldDirty: true, shouldTouch: true });+ const offerMeta = useRef<Record<string, string[]>>({})+ for (const row of rows) {+ offerMeta.current[row.id] = collectOfferIds(row)+ }- /**- * Update the product records to ensure that all unselected products- * are removed from the form state.- */- setValue("products", updatedRecords, {- shouldDirty: true,- shouldTouch: true,- });+ const isAlreadyAdded = (row: OfferProduct) =>+ collectOfferIds(row).length > 0 &&+ collectOfferIds(row).every((id) => existingOfferIds.has(id))- setRowSelection(state);- };+ const updater: OnChangeFn<RowSelectionState> = (fn) => {+ const state = typeof fn === "function" ? fn(rowSelection) : fn++ const productIds = Object.keys(state).filter((id) => offerMeta.current[id])+ const offerIds = Array.from(+ new Set(+ productIds+ .flatMap((id) => offerMeta.current[id] ?? [])+ .filter((id) => !existingOfferIds.has(id))+ )+ )++ setValue(+ "product_ids",+ productIds.map((id) => ({ id })),+ { shouldDirty: true, shouldTouch: true }+ )+ setValue("offer_ids", offerIds, { shouldDirty: true, shouldTouch: true })++ setRowSelection(state)+ }- const columns = useColumns();- const filters = useProductTableFilters();+ const columns = useColumns(existingOfferIds)+ const filters = useOfferTableFilters()const { table } = useDataTable({- data: products || [],+ data: rows,columns,count,enablePagination: true,- enableRowSelection: (row) => {- return (- !!row.original.variants?.length &&- !row.original.variants?.some((v) => variantIdMap[v.id])- );- },+ enableRowSelection: (row) =>+ collectOfferIds(row.original).length > 0 && !isAlreadyAdded(row.original),getRowId: (row) => row.id,rowSelection: {state: rowSelection,@@ -126,13 +121,10 @@ export const PriceListPricesAddProductIdsForm = ({},pageSize: PAGE_SIZE,prefix: PREFIX,- meta: {- variantIdMap,- },- });+ })if (isError) {- throw error;+ throw error}return (@@ -148,7 +140,6 @@ export const PriceListPricesAddProductIdsForm = ({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") },]}@@ -157,76 +148,53 @@ export const PriceListPricesAddProductIdsForm = ({queryObject={raw}/></div>- );-};--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 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();- }}- />- );-- if (isPreselected) {- return (- <Tooltip content={t("priceLists.products.add.alreadyInPriceList")}>- {Component}- </Tooltip>- );+const columnHelper = createColumnHelper<OfferProduct>()++const useColumns = (existingOfferIds: Set<string>) => {+ const { t } = useTranslation()+ const base = useOfferTableColumns()++ return useMemo(() => {+ const selectColumn = columnHelper.display({+ id: "select",+ header: ({ table }) => (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()}+ 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()}+ />+ )+ const ids = collectOfferIds(row.original)+ const alreadyAdded =+ ids.length > 0 && ids.every((id) => existingOfferIds.has(id))+ if (alreadyAdded) {+ return (+ <Tooltip content={t("priceLists.products.add.alreadyInPriceList")}>+ {checkbox}+ </Tooltip>+ )+ }+ return checkbox+ },+ })- if (isDisabled) {- return (- <Tooltip content={t("priceLists.products.add.noVariants")}>- {Component}- </Tooltip>- );- }+ const informative = base.slice(0, -1) as ColumnDef<OfferProduct>[]- return Component;- },- }),- ...base,- ],- [base, t],- );-};+ return [selectColumn, ...informative] as ColumnDef<OfferProduct>[]+ }, [base, existingOfferIds, t])+}diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.tsindex 6971fcf78..7e556ff41 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts@@ -1,74 +1,58 @@-import i18n from 'i18next';-import { z } from 'zod';+import i18n from "i18next"+import { z } from "zod"-import { PriceListCreateProductsSchema } from "../../../../common/schemas"+import { PriceListCreateOffersSchema } from "../../../../common/schemas"++const hasAmount = (amount: unknown) =>+ amount !== undefined &&+ amount !== null &&+ amount !== "" &&+ (typeof amount === "number" ? amount > 0 : String(amount).trim() !== "")const PriceListPricesAddBaseSchema = 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 const PriceListPricesAddProductIdsSchema = PriceListPricesAddBaseSchema.pick({- product_ids: true-});+export const PriceListPricesAddProductIdsSchema =+ PriceListPricesAddBaseSchema.pick({+ product_ids: true,+ })export const PriceListPricesAddProductsIdsFields = Object.keys(PriceListPricesAddProductIdsSchema.shape-) as (keyof typeof PriceListPricesAddProductIdsSchema.shape)[];+) as (keyof typeof PriceListPricesAddProductIdsSchema.shape)[]-export const PriceListPricesAddProductsSchema = PriceListPricesAddBaseSchema.pick({- products: true-});+export const PriceListPricesAddProductsSchema =+ PriceListPricesAddBaseSchema.pick({+ offers: true,+ })export const PriceListPricesAddProductsFields = Object.keys(PriceListPricesAddProductsSchema.shape-) as (keyof typeof PriceListPricesAddProductsSchema.shape)[];+) as (keyof typeof PriceListPricesAddProductsSchema.shape)[]export const PriceListPricesAddSchema = PriceListPricesAddBaseSchema.refine(- data => {- // Check if at least one product has at least one price with an amount- const productIds = data.product_ids.map(p => p.id);-- for (const productId of productIds) {- const product = data.products[productId];- if (!product) continue;-- // Check all variants of this product- for (const variant of Object.values(product.variants || {})) {- // Check currency prices- const hasCurrencyPrice = Object.values(variant.currency_prices || {}).some(price => {- const amount = price?.amount;- return (- amount !== undefined &&- amount !== null &&- amount !== '' &&- (typeof amount === 'number' ? amount > 0 : String(amount).trim() !== '')- );- });-- // Check region prices- const hasRegionPrice = Object.values(variant.region_prices || {}).some(price => {- const amount = price?.amount;- return (- amount !== undefined &&- amount !== null &&- amount !== '' &&- (typeof amount === 'number' ? amount > 0 : String(amount).trim() !== '')- );- });-- if (hasCurrencyPrice || hasRegionPrice) {- return true;- }+ (data) => {+ // At least one offer must carry a price with an amount.+ for (const offer of Object.values(data.offers)) {+ const hasCurrency = Object.values(offer.currency_prices || {}).some((p) =>+ hasAmount(p?.amount)+ )+ const hasRegion = Object.values(offer.region_prices || {}).some((p) =>+ hasAmount(p?.amount)+ )+ if (hasCurrency || hasRegion) {+ return true}}-- return false;+ return false},{- message: i18n.t('validation.atLeastOnePrice'),- path: ['products']+ message: i18n.t("validation.atLeastOnePrice"),+ path: ["offers"],}-);+)-export type PriceListPricesAddSchema = z.infer<typeof PriceListPricesAddSchema>;+export type PriceListPricesAddSchema = z.infer<typeof PriceListPricesAddSchema>diff --git a/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx b/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsxindex 23ba80365..f68bac3b2 100644--- a/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx+++ b/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx@@ -1,52 +1,43 @@-import { RouteFocusModal } from "@/components/modals";-import { useTranslation } from "react-i18next";-import { useParams, useSearchParams } from "react-router-dom";-import { PriceListPricesEditForm } from "../[variant_id]/edit/price-list-prices-edit-form";-import { usePriceListCurrencyData } from "@/pages/price-lists/common/hooks/use-price-list-currency-data";-import { usePriceList, useProducts } from "@/hooks/api";+import { useMemo } from "react"+import { useTranslation } from "react-i18next"+import { useParams, useSearchParams } from "react-router-dom"-export const Component = () => {- const { t } = useTranslation();- const { id } = useParams();- const [searchParams] = useSearchParams();- const ids = searchParams.get("ids[]");+import { RouteFocusModal } from "@components/modals"+import { usePriceListEditGrid } from "../[variant_id]/edit/price-list-prices-edit-form/use-price-list-edit-grid"+import { PriceListPricesEditForm } from "../[variant_id]/edit/price-list-prices-edit-form"- const { price_list, isLoading, isError, error } = usePriceList(id!, {- fields:- "*prices,prices.price_set.variant.id,prices.price_rules.attribute,prices.price_rules.value",- });- const productIds = ids?.split(",");+export const Component = () => {+ const { t } = useTranslation()+ const { id } = useParams()+ const [searchParams] = useSearchParams()+ const ids = searchParams.get("ids[]")+ const productFilter = useMemo(+ () => (ids ? ids.split(",") : undefined),+ [ids]+ )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!],- // TODO: Remove exclusion once we avoid including unnecessary relations by default in the query config- fields:- "title,thumbnail,*variants,-type,-collection,-options,-tags,-images,-sales_channels",- });-- const { isReady, regions, currencies, pricePreferences } =- usePriceListCurrencyData();-- const ready =- !isLoading && !!price_list && !isProductsLoading && !!products && isReady;+ price_list,+ gridData,+ variantIdByOffer,+ currencyData,+ ready,+ isError,+ error,+ isProductsError,+ productError,+ } = usePriceListEditGrid(id!, productFilter)if (isError) {- throw error;+ throw error}if (isProductsError) {- throw productError;+ throw productError}return (- <RouteFocusModal>+ <RouteFocusModal prev={`/price-lists/${id}`}><RouteFocusModal.Title asChild><span className="sr-only">{t("priceLists.products.edit.title", { title: price_list?.title })}@@ -58,12 +49,13 @@ export const Component = () => {{ready && (<PriceListPricesEditFormpriceList={price_list}- products={products}- regions={regions}- currencies={currencies}- pricePreferences={pricePreferences}+ gridData={gridData}+ variantIdByOffer={variantIdByOffer}+ regions={currencyData.regions}+ currencies={currencyData.currencies}+ pricePreferences={currencyData.pricePreferences}/>)}</RouteFocusModal>- );-};+ )+}diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-data-table.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-data-table.tsxindex 7e79e50bd..1d67067d6 100644--- a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-data-table.tsx+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-data-table.tsx@@ -1,3 +1,4 @@+import { CurrencyDollar } from "@medusajs/icons";import { keepPreviousData } from "@tanstack/react-query";import { createColumnHelper, type ColumnDef } from "@tanstack/react-table";import { useMemo } from "react";@@ -56,7 +57,6 @@ 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"),@@ -66,10 +66,20 @@ export const PriceListListDataTable = () => {label: t("fields.updatedAt"),},]}+ defaultOrderBy="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/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-header.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-header.tsxindex 226570464..db8019edd 100644--- a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-header.tsx+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-header.tsx@@ -1,16 +1,13 @@import { Children, ReactNode } from "react";import { useTranslation } from "react-i18next";import { Link } from "react-router-dom";-import { Button, Heading, Text } from "@medusajs/ui";+import { Button, Heading } from "@medusajs/ui";export const PriceListListTitle = () => {const { t } = useTranslation();return (<div><Heading>{t("priceLists.domain")}</Heading>- <Text className="text-ui-fg-subtle" size="small">- {t("priceLists.subtitle")}- </Text></div>);};diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsxindex 6aee85429..148169b54 100644--- a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx@@ -23,21 +23,35 @@ export const usePricingTableColumns = () => {return row.original?.title || "-"},}),- columnHelper.accessor("status", {- header: t("priceLists.fields.status.label"),+ columnHelper.accessor("type", {+ header: () => <TextHeader text={t("priceLists.fields.type.label")} />,cell: ({ row }) => {- const { color, text } = getPriceListStatus(t, row.original)-- return <StatusCell color={color}>{text}</StatusCell>+ const type = row.original?.type+ const text = type+ ? t(`priceLists.fields.type.options.${type}.label`)+ : "-"+ return <TextCell text={text} />},}),columnHelper.accessor("prices", {- header: t("priceLists.fields.priceOverrides.header"),+ header: () => (+ <TextHeader text={t("priceLists.fields.priceOverrides.header")} />+ ),cell: ({ row }) => {const prices = row.original?.prices?.length || "-"return <TextCell text={prices} />},}),+ columnHelper.accessor("status", {+ header: () => (+ <TextHeader text={t("priceLists.fields.status.label")} />+ ),+ cell: ({ row }) => {+ const { color, text } = getPriceListStatus(t, row.original)++ return <StatusCell color={color}>{text}</StatusCell>+ },+ }),],[t])diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsxindex 74807c987..c1ee9f4be 100644--- a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx@@ -1,7 +1,43 @@-import { useDateTableFilters } from "@hooks/table/filters/use-date-table-filters"+import { useTranslation } from "react-i18next"+import { Filter } from "@components/table/data-table"export const usePricingTableFilters = () => {- const dateFilters = useDateTableFilters()+ const { t } = useTranslation()- return dateFilters+ const filters: Filter[] = [+ {+ 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 filters}diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsxindex a1cd546ca..04945d1d8 100644--- a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx@@ -8,13 +8,23 @@ export const usePricingTableQuery = ({pageSize?: numberprefix?: string}) => {- const raw = useQueryParams(["offset", "q", "order", "status"], prefix)+ const raw = useQueryParams(+ ["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[],+ 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/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/index.ts b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/index.tsnew file mode 100644index 000000000..00126ea25--- /dev/null+++ b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/index.ts@@ -0,0 +1 @@+export { PriceListCustomerAvailabilitySelector } from "./price-list-customer-availability-selector"diff --git a/packages/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/price-list-customer-availability-selector.tsx b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/price-list-customer-availability-selector.tsxnew file mode 100644index 000000000..a2fd02ea1--- /dev/null+++ b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-availability-selector/price-list-customer-availability-selector.tsx@@ -0,0 +1,122 @@+import { MagnifyingGlass, XMarkMini } from "@medusajs/icons"+import { Button, Divider, IconButton, Text, clx } from "@medusajs/ui"+import { Control, FieldValues, Path, useFieldArray } from "react-hook-form"+import { useTranslation } from "react-i18next"++import { StackedFocusModal, useStackedModal } from "@components/modals"+import { PriceListCustomerGroupRuleForm } from "../price-list-customer-group-rule-form"++type CustomerGroup = { id: string; name: string }++type PriceListCustomerAvailabilitySelectorProps<T extends FieldValues> = {+ control: Control<T>+ name: Path<T>+ stackedId?: string+}++/**+ * Reusable "Customer availability" builder (attribute · in · Browse · chips)+ * shared by the create wizard and the detail edit drawer. The bound field is+ * an array of `{ id, name }` customer groups.+ */+export const PriceListCustomerAvailabilitySelector = <T extends FieldValues>({+ control,+ name,+ stackedId = "cg",+}: PriceListCustomerAvailabilitySelectorProps<T>) => {+ const { t } = useTranslation()+ const { setIsOpen } = useStackedModal()++ const { fields, append, remove } = useFieldArray({+ control,+ name: name as never,+ keyName: "cg_id",+ })++ const selected = fields as unknown as (CustomerGroup & { cg_id: string })[]++ const handleAdd = (groups: CustomerGroup[]) => {+ const newIds = groups.map((group) => group.id)++ const fieldsToAdd = groups.filter(+ (group) => !selected.some((field) => field.id === group.id)+ )++ for (const field of selected) {+ if (!newIds.includes(field.id)) {+ remove(selected.indexOf(field))+ }+ }++ append(fieldsToAdd as never)+ setIsOpen(stackedId, false)+ }++ return (+ <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"+ >+ <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">+ <StackedFocusModal id={stackedId}>+ <StackedFocusModal.Trigger asChild>+ <button+ type="button"+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"+ >+ <MagnifyingGlass />+ {t("priceLists.fields.customerAvailability.placeholder")}+ </button>+ </StackedFocusModal.Trigger>+ <StackedFocusModal.Trigger asChild>+ <Button variant="secondary">{t("actions.browse")}</Button>+ </StackedFocusModal.Trigger>+ <StackedFocusModal.Content>+ <StackedFocusModal.Header />+ <PriceListCustomerGroupRuleForm+ state={selected}+ setState={handleAdd}+ type="focus"+ />+ </StackedFocusModal.Content>+ </StackedFocusModal>+ </div>+ {selected.length > 0 ? (+ <div className="flex flex-col gap-y-1.5">+ <Divider variant="dashed" />+ <div className="flex flex-col gap-y-1.5 px-1.5">+ {selected.map((field, index) => (+ <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"+ >+ <Text size="small" leading="compact">+ {field.name}+ </Text>+ <IconButton+ size="small"+ variant="transparent"+ type="button"+ onClick={() => remove(index)}+ >+ <XMarkMini />+ </IconButton>+ </div>+ ))}+ </div>+ </div>+ ) : null}+ </div>+ )+}diff --git a/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsxindex a0529a5e6..a3f7a07c8 100644--- a/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx+++ b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx@@ -76,7 +76,6 @@ export const PriceListCustomerGroupRuleForm = ({)const customerGroups = customerGroupsData- ?.map((item) => item.customer_group)const updater: OnChangeFn<RowSelectionState> = (value) => {const state = typeof value === "function" ? value(rowSelection) : valuediff --git a/packages/vendor/src/pages/price-lists/common/constants.ts b/packages/vendor/src/pages/price-lists/common/constants.tsindex aecee622a..96051692c 100644--- a/packages/vendor/src/pages/price-lists/common/constants.ts+++ b/packages/vendor/src/pages/price-lists/common/constants.ts@@ -1,20 +1,5 @@-/**- * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported- */-export enum PriceListStatus {- ACTIVE = "active",- DRAFT = "draft",-}--export enum PriceListDateStatus {- SCHEDULED = "scheduled",- EXPIRED = "expired",-}--/**- * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported- */-export enum PriceListType {- SALE = "sale",- OVERRIDE = "override",-}+export {+ PriceListDateStatus,+ PriceListStatus,+ PriceListType,+} from "@mercurjs/dashboard-shared"diff --git a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsxindex e40dbef9c..8f6ce941b 100644--- a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx+++ b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx@@ -3,24 +3,27 @@ import { ColumnDef } from "@tanstack/react-table"import { useMemo } from "react"import { useTranslation } from "react-i18next"-import { Thumbnail } from "@components/common/thumbnail"import {- createDataGridHelper,- DataGrid,-} from "@components/data-grid"+ isPriceListGroupRow,+ type PriceListGridRow,+} from "@mercurjs/dashboard-shared"++import { Thumbnail } from "@components/common/thumbnail"+import { createDataGridHelper, 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"-import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"-const columnHelper = createDataGridHelper<- ExtendedAdminProduct | ExtendedAdminProductVariant,- PricingCreateSchemaType->()+export type { PriceListGridRow } from "@mercurjs/dashboard-shared"++/**+ * The Prices grid is keyed by **offer**, not variant: the same product sold by+ * two sellers stays as two separate groups (product + seller) with their own+ * variant rows. Each offer row binds prices to `offers.<offer_id>`.+ */+const columnHelper = createDataGridHelper<PriceListGridRow, any>()export const usePriceListGridColumns = ({currencies = [],- regions: _regions = [],+ regions = [],pricePreferences = [],}: {currencies?: string[]@@ -29,21 +32,21 @@ export const usePriceListGridColumns = ({}) => {const { t } = useTranslation()- const colDefs: ColumnDef<- ExtendedAdminProduct | ExtendedAdminProductVariant- >[] = 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>)@@ -52,41 +55,46 @@ 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<- ExtendedAdminProduct | ExtendedAdminProductVariant,- PricingCreateSchemaType- >({+ 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,+ 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,- showCurrentPriceCell: true,}),]- }, [t, currencies, pricePreferences])+ }, [t, currencies, regions, pricePreferences])return colDefs}diff --git a/packages/vendor/src/pages/price-lists/common/schemas.ts b/packages/vendor/src/pages/price-lists/common/schemas.tsindex dceda6eb8..cf624f705 100644--- a/packages/vendor/src/pages/price-lists/common/schemas.ts+++ b/packages/vendor/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/vendor/src/pages/price-lists/common/utils.ts b/packages/vendor/src/pages/price-lists/common/utils.tsindex 2872a3285..2137eb91c 100644--- a/packages/vendor/src/pages/price-lists/common/utils.ts+++ b/packages/vendor/src/pages/price-lists/common/utils.ts@@ -1,126 +1,5 @@-import { HttpTypes } from "@medusajs/types"-import i18n, { TFunction } from "i18next"-import { castNumber } from "@lib/cast-number"-import { PriceListDateStatus, PriceListStatus } from "./constants"-import {- PriceListCreateCurrencyPrice,- PriceListCreateProductVariantSchema,- PriceListCreateProductsSchema,-} from "./schemas"-import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"--const getValues = (priceList: HttpTypes.AdminPriceList) => {- const startsAt = priceList.starts_at- const endsAt = priceList.ends_at-- const isExpired = endsAt ? new Date(endsAt) < new Date() : false- const isScheduled = startsAt ? new Date(startsAt) > new Date() : false- const isDraft = priceList.status === PriceListStatus.DRAFT-- return {- isExpired,- isScheduled,- isDraft,- }-}--export const getPriceListStatus = (- t: TFunction<"translation">,- priceList: HttpTypes.AdminPriceList-) => {- const { isExpired, isScheduled, isDraft } = getValues(priceList)-- let text = t("priceLists.fields.status.options.active")- let color: "red" | "grey" | "orange" | "green" = "green"- let status: string = PriceListStatus.ACTIVE-- if (isDraft) {- color = "grey"- text = t("priceLists.fields.status.options.draft")- status = PriceListStatus.DRAFT- }-- if (isExpired) {- color = "red"- text = t("priceLists.fields.status.options.expired")- status = PriceListDateStatus.EXPIRED- }-- if (isScheduled) {- color = "orange"- text = t("priceLists.fields.status.options.scheduled")- status = PriceListDateStatus.SCHEDULED- }-- return {- color,- text,- status,- }-}--export const isProductRow = (- row: ExtendedAdminProduct | ExtendedAdminProductVariant-): row is ExtendedAdminProduct => {- return "variants" in row-}--const extractPricesFromVariants = (- variantId: string,- variant: PriceListCreateProductVariantSchema,- 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 {- 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]-}--export const exctractPricesFromProducts = (- products: PriceListCreateProductsSchema,- regions: HttpTypes.AdminRegion[]-) => {- return Object.values(products).flatMap(({ variants }) =>- Object.entries(variants).flatMap(([variantId, variant]) =>- extractPricesFromVariants(variantId, variant, regions)- )- )-}+export {+ extractPricesFromOffers,+ getPriceListStatus,+ isProductRow,+} from "@mercurjs/dashboard-shared"diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsxindex be8272614..23819ed63 100644--- a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx@@ -12,7 +12,7 @@ import {} from "@components/modals"import { KeyboundForm } from "@components/utilities/keybound-form"import { useCreatePriceList } from "@hooks/api/price-lists"-import { exctractPricesFromProducts } from "@pages/price-lists/common/utils"+import { extractPricesFromOffers } from "@pages/price-lists/common/utils"import { PriceListDetailsForm } from "./price-list-details-form"import { PriceListPricesForm } from "./price-list-prices-form"import { PriceListProductsForm } from "./price-list-products-form"@@ -62,13 +62,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: [],},@@ -79,13 +80,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/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsxindex 133df2254..2979e99c8 100644--- a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx@@ -4,17 +4,15 @@ import {Heading,Input,RadioGroup,- Select,Text,Textarea,} from "@medusajs/ui"-import { useFieldArray, type UseFormReturn } from "react-hook-form"+import { type UseFormReturn } from "react-hook-form"import { useTranslation } from "react-i18next"import { Form } from "@components/common/form"-import type {- PricingCreateSchemaType,-} from "./schema"+import { PriceListCustomerAvailabilitySelector } from "@pages/price-lists/common/components/price-list-customer-availability-selector"+import type { PricingCreateSchemaType } from "./schema"type PriceListDetailsFormProps = {form: UseFormReturn<PricingCreateSchemaType>@@ -23,16 +21,6 @@ type PriceListDetailsFormProps = {export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {const { t } = useTranslation()- const { remove: _remove } = useFieldArray({- control: form.control,- name: "rules.customer_group_id",- keyName: "cg_id",- })-----return (<div className="flex flex-1 flex-col items-center overflow-y-auto"><div className="flex w-full max-w-[720px] flex-col gap-y-8 px-8 py-16">@@ -77,227 +65,137 @@ export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {/></RadioGroup></Form.Control>+ <Form.ErrorMessage /></div>- <Form.ErrorMessage /></Form.Item>)}}/><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 }) => {- return (- <Form.Item>- <Form.Label>{t("fields.title")}</Form.Label>- <Form.Control>- <Input {...field} />- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}- />- <Form.Field- control={form.control}- name="status"- render={({ field: { onChange, ref, ...field } }) => {- return (- <Form.Item>- <Form.Label>- {t("priceLists.fields.status.label")}- </Form.Label>- <Form.Control>- <Select {...field} onValueChange={onChange}>- <Select.Trigger ref={ref}>- <Select.Value />- </Select.Trigger>- <Select.Content>- <Select.Item value="active">- {t("priceLists.fields.status.options.active")}- </Select.Item>- <Select.Item value="draft">- {t("priceLists.fields.status.options.draft")}- </Select.Item>- </Select.Content>- </Select>- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}- />- </div>+ <Form.Field+ control={form.control}+ name="status"+ render={({ field: { onChange, ...rest } }) => (+ <Form.Item>+ <Form.Label>{t("priceLists.fields.status.label")}</Form.Label>+ <Form.Control>+ <RadioGroup+ onValueChange={onChange}+ {...rest}+ className="grid grid-cols-1 gap-4 md:grid-cols-2"+ >+ <RadioGroup.ChoiceBox+ value="draft"+ label={t("priceLists.fields.status.options.draft")}+ description={t(+ "priceLists.fields.status.descriptions.draft"+ )}+ />+ <RadioGroup.ChoiceBox+ value="active"+ label={t("priceLists.fields.status.options.active")}+ description={t(+ "priceLists.fields.status.descriptions.active"+ )}+ />+ </RadioGroup>+ </Form.Control>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ />+ <Form.Field+ control={form.control}+ name="title"+ render={({ field }) => (+ <Form.Item>+ <Form.Label>{t("fields.title")}</Form.Label>+ <Form.Control>+ <Input {...field} />+ </Form.Control>+ <Form.ErrorMessage />+ </Form.Item>+ )}+ /><Form.Fieldcontrol={form.control}name="description"- render={({ field }) => {- return (- <Form.Item>- <Form.Label>{t("fields.description")}</Form.Label>- <Form.Control>- <Textarea {...field} />- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}+ render={({ field }) => (+ <Form.Item>+ <Form.Label>{t("fields.description")}</Form.Label>+ <Form.Control>+ <Textarea {...field} />+ </Form.Control>+ <Form.ErrorMessage />+ </Form.Item>+ )}/></div><Divider />- <Form.Field- control={form.control}- name="starts_at"- render={({ field }) => {- return (+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <Form.Field+ control={form.control}+ name="starts_at"+ render={({ field }) => (<Form.Item>- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- <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.Control>- <DatePicker- granularity="minute"- shouldCloseOnSelect={false}- {...field}- />- </Form.Control>- </div>+ <Form.Label optional>+ {t("priceLists.fields.startsAt.label")}+ </Form.Label>+ <Form.Control>+ <DatePicker+ granularity="minute"+ shouldCloseOnSelect={false}+ {...field}+ />+ </Form.Control><Form.ErrorMessage /></Form.Item>- )- }}- />- <Divider />- <Form.Field- control={form.control}- name="ends_at"- render={({ field }) => {- return (+ )}+ />+ <Form.Field+ control={form.control}+ name="ends_at"+ render={({ field }) => (<Form.Item>- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">- <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.Control>- <DatePicker- granularity="minute"- shouldCloseOnSelect={false}- {...field}- />- </Form.Control>- </div>+ <Form.Label optional>+ {t("priceLists.fields.endsAt.label")}+ </Form.Label>+ <Form.Control>+ <DatePicker+ granularity="minute"+ shouldCloseOnSelect={false}+ {...field}+ />+ </Form.Control><Form.ErrorMessage /></Form.Item>- )- }}- />- {/* TODO: Customer group availability - vendor API does not support customer groups yet+ )}+ />+ </div><Divider /><Form.Fieldcontrol={form.control}name="rules.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">- <StackedFocusModal id="cg">- <StackedFocusModal.Trigger asChild>- <button- type="button"- className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"- >- <MagnifyingGlass />- {t(- "priceLists.fields.customerAvailability.placeholder"- )}- </button>- </StackedFocusModal.Trigger>- <StackedFocusModal.Trigger asChild>- <Button variant="secondary">- {t("actions.browse")}- </Button>- </StackedFocusModal.Trigger>- <StackedFocusModal.Content>- <StackedFocusModal.Header />- <PriceListCustomerGroupRuleForm- state={fields}- setState={handleAddCustomerGroup}- type="focus"- />- </StackedFocusModal.Content>- </StackedFocusModal>- </div>- {fields.length > 0 ? (- <div className="flex flex-col gap-y-1.5">- <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"- >- <Text size="small" leading="compact">- {field.name}- </Text>- <IconButton- size="small"- variant="transparent"- type="button"- onClick={() => remove(index)}- >- <XMarkMini />- </IconButton>- </div>- )- })}- </div>- </div>- ) : null}- </div>- </Form.Control>- <Form.ErrorMessage />- </Form.Item>- )- }}+ render={() => (+ <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>+ <PriceListCustomerAvailabilitySelector+ control={form.control}+ name="rules.customer_group_id"+ />+ </Form.Control>+ <Form.ErrorMessage />+ </Form.Item>+ )}/>- */}</div></div>)diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsxindex ab56d07b4..d4f49bb16 100644--- a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx@@ -1,12 +1,17 @@import { HttpTypes } from "@medusajs/types"-import { useEffect } from "react"+import { OfferDTO } from "@mercurjs/types"+import { buildOfferGridData } from "@mercurjs/dashboard-shared"+import { useEffect, useMemo } from "react"import { UseFormReturn, useWatch } from "react-hook-form"+import { DataGrid } from "@components/data-grid"import { useRouteModal } from "@components/modals"+import { useOffers } from "@hooks/api/offers"import { useProducts } from "@hooks/api/products"-import { usePriceListGridColumns } from "@pages/price-lists/common/hooks/use-price-list-grid-columns"-import { PriceListCreateProductVariantsSchema } from "@pages/price-lists/common/schemas"-import { isProductRow } from "@pages/price-lists/common/utils"+import {+ PriceListGridRow,+ usePriceListGridColumns,+} from "@pages/price-lists/common/hooks/use-price-list-grid-columns"import { PricingCreateSchemaType } from "./schema"type PriceListPricesFormProps = {@@ -16,61 +21,66 @@ type PriceListPricesFormProps = {pricePreferences: HttpTypes.AdminPricePreference[]}+const OFFER_GRID_FIELDS =+ "id,variant_id,product_id,sku,product.title,product.thumbnail"+export const PriceListPricesForm = ({form,currencies,regions,pricePreferences,}: PriceListPricesFormProps) => {- const ids = useWatch({- control: form.control,- name: "product_ids",- })+ const { setValue } = form+ const { setCloseOnEscape } = useRouteModal()- const existingProducts = useWatch({- control: form.control,- name: "products",- })+ const offerIds = useWatch({ control: form.control, name: "offer_ids" })+ const existingOffers = useWatch({ control: form.control, name: "offers" })- const {- products: productsRaw,- isLoading,- isError,- error,- } = useProducts({- fields: "title,thumbnail,*variants,+status,*variants.prices",- })+ const { offers: selectedOffers } = useOffers(+ {+ id: offerIds,+ limit: offerIds?.length || 1,+ fields: OFFER_GRID_FIELDS,+ },+ { enabled: (offerIds?.length ?? 0) > 0 }+ )- const products = productsRaw?.filter((product) =>- ids.some((id) => id.id === product.id)+ const productIds = useMemo(+ () =>+ Array.from(+ new Set(+ ((selectedOffers ?? []) as OfferDTO[]).map((o) => 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 ?? []) as { variants?: { id: string; title?: string | null }[] | null }[]+ ),+ [selectedOffers, products]+ )+ // Seed an empty price entry per offer so the grid cells bind.useEffect(() => {- if (!isLoading && products) {- products.forEach((product) => {- /**- * If the product already exists in the form, we don't want to overwrite it.- */- 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,@@ -78,21 +88,12 @@ export const PriceListPricesForm = ({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)}/>diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsxindex f2e3acc7a..939940ede 100644--- a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx@@ -1,23 +1,26 @@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 { useMemo, useRef, useState } from "react"import { UseFormReturn, useWatch } from "react-hook-form"-import { useTranslation } from "react-i18next"+import { _DataTable } from "@components/table/data-table"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 { useDataTable } from "@hooks/use-data-table"-import { PriceListCreateProductsSchema } from "../../../common/schemas"+import {+ collectOfferIds,+ useOfferTableColumns,+ useOfferTableFilters,+ useOfferTableQuery,+} from "@pages/offers/_components"+import { OfferProduct } from "@pages/offers/common/types"import { PricingCreateSchemaType } from "./schema"-import { ExtendedAdminProduct } from "@custom-types/products"type PriceListProductsFormProps = {form: UseFormReturn<PricingCreateSchemaType>@@ -37,75 +40,61 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {const { t } = useTranslation()const { control, setValue } = form- const selectedIds = useWatch({- control,- name: "product_ids",- })-- const productRecords = useWatch({- control,- name: "products",- })+ const selectedIds = useWatch({ control, name: "product_ids" })const [rowSelection, setRowSelection] = useState<RowSelectionState>(getInitialSelection(selectedIds))- const { searchParams, raw } = useProductTableQuery({+ const { searchParams, raw } = useOfferTableQuery({pageSize: PAGE_SIZE,prefix: PREFIX,})+ // One row per product (the seller's offered products). Each row's offers,+ // flattened via `collectOfferIds`, become the priceable offer ids; variant→+ // offer resolution happens in the Prices tab.const { products, count, isLoading, isError, error } = useProducts(- { ...searchParams, fields: "+thumbnail" },- {- placeholderData: keepPreviousData,- }+ searchParams,+ { placeholderData: keepPreviousData })- 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]- }+ const rows = (products ?? []) as OfferProduct[]- return acc- }, {} as PriceListCreateProductsSchema)+ // product id -> offer ids, kept across pages so a selection survives paging.+ const offerMeta = useRef<Record<string, string[]>>({})+ for (const row of rows) {+ offerMeta.current[row.id] = collectOfferIds(row)+ }- const update = ids.map((id) => ({ id }))+ const updater: OnChangeFn<RowSelectionState> = (fn) => {+ const state = typeof fn === "function" ? fn(rowSelection) : fn- setValue("product_ids", update, {- shouldDirty: true,- shouldTouch: true,- })+ const productIds = Object.keys(state).filter(+ (id) => offerMeta.current[id]+ )+ const offerIds = Array.from(+ new Set(productIds.flatMap((id) => offerMeta.current[id] ?? []))+ )- /**- * Update the product records to ensure that all unselected products- * are removed from the form state.- */- setValue("products", updatedRecords, {- shouldDirty: true,- shouldTouch: true,- })+ setValue(+ "product_ids",+ productIds.map((id) => ({ id })),+ { shouldDirty: true, shouldTouch: true }+ )+ setValue("offer_ids", offerIds, { shouldDirty: true, shouldTouch: true })setRowSelection(state)}const columns = useColumns()- const filters = useProductTableFilters()+ const filters = useOfferTableFilters()const { table } = useDataTable({- data: products || [],+ data: rows,columns,count,enablePagination: true,- enableRowSelection: (row) => {- return !!row.original.variants?.length- },+ enableRowSelection: (row) => collectOfferIds(row.original).length > 0,getRowId: (row) => row.id,rowSelection: {state: rowSelection,@@ -131,15 +120,8 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {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"),- },+ { key: "created_at", label: t("fields.createdAt") },+ { key: "updated_at", label: t("fields.updatedAt") },]}paginationsearch@@ -152,44 +134,37 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {)}-const columnHelper = createColumnHelper<ExtendedAdminProduct>()+const columnHelper = createColumnHelper<OfferProduct>()const useColumns = () => {- 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 }) => {- return (- <Checkbox- checked={row.getIsSelected()}- disabled={!row.getCanSelect()}- onCheckedChange={(value) => row.toggleSelected(!!value)}- onClick={(e) => {- e.stopPropagation()- }}- />- )- },- }),- ...base,- ],- [base]- )+ const base = useOfferTableColumns()++ return useMemo(() => {+ const selectColumn = columnHelper.display({+ id: "select",+ header: ({ table }) => (+ <Checkbox+ checked={+ table.getIsSomePageRowsSelected()+ ? "indeterminate"+ : table.getIsAllPageRowsSelected()+ }+ onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}+ />+ ),+ cell: ({ row }) => (+ <Checkbox+ checked={row.getIsSelected()}+ disabled={!row.getCanSelect()}+ onCheckedChange={(value) => row.toggleSelected(!!value)}+ onClick={(e) => e.stopPropagation()}+ />+ ),+ })++ // The offers columns end with an OfferActions menu; drop it in the picker.+ const informative = base.slice(0, -1) as ColumnDef<OfferProduct>[]++ return [selectColumn, ...informative] as ColumnDef<OfferProduct>[]+ }, [base])}diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts b/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.tsindex 4c3b64cdc..a5030d857 100644--- a/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts@@ -1,6 +1,7 @@+import i18n from "i18next"import { z } from "zod"import {- PriceListCreateProductsSchema,+ PriceListCreateOffersSchema,PriceListRulesSchema,} from "@pages/price-lists/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 products).+ // The Prices tab hydrates `offers` from these.+ offer_ids: z.array(z.string()).default([]),+ // Offer-keyed prices (offer_id -> { variant_id, prices }), so every price+ // carries its offer_id rule and stays scoped to that offer.+ offers: PriceListCreateOffersSchema.default({}),rules: PriceListRulesSchema.nullish(),})@@ -35,7 +43,6 @@ export const PricingDetailsSchema = PricingCreateSchema.pick({description: true,starts_at: true,ends_at: true,- customer_group_ids: true,})export const PricingDetailsFields = Object.keys(@@ -51,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(