Skip to content

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

feat(seller): assign sellers to regions and scope vendor pricing (#1665)

Viktor Holik526a7d96fbdc
diff --git a/claude-progress.md b/claude-progress.md
index f9d0fb7d9..a02226d42 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,20 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Seller ↔ Region assignment (SPEC-001), branch `feat/seller-regions`
+
+Spec: `docs/specs/SPEC-001-seller-regions.md`. New `region_seller` link; `linkSellerRegionsWorkflow`;
+seller creation (admin + vendor registration) links `region_ids` or the store default region.
+Admin: `POST /admin/sellers/:id/regions`, `POST /admin/regions/:id/sellers`, `GET /admin/sellers?region_id=`,
+`seller.regions` on retrieve. Vendor: `/vendor/regions` scoped to assigned regions; offer + shipping-option
+prices validated against assigned regions (400). Admin UI: region detail *Sellers* section + add modal,
+store detail *Regions* sidebar + add modal, Create Seller regions picker. Vendor UI: offer price grids gain
+a column per assigned region (`rules.region_id`); offer pricing sections list region prices.
+Verified: `test:integration:http -- "regions|offer-region-prices|shipping-options/vendor|seller/(admin|vendor)/seller"`
+(10 suites, 238 tests). `bun run build` see spec Evidence. Not verified in a browser. Uncommitted.
+Known pre-existing: admin `validate-translations.spec.ts` fails on `sellers.*` schema keys missing from
+`en.json` (unrelated); `bun run lint` tsc noise in untouched files.
+
## Session — Panel auth collision, branch `fix/panel-auth-session-collision`
Admin and vendor panels shared one API session cookie, so logging in to one logged the other out.
diff --git a/integration-tests/helpers/create-seller-user.ts b/integration-tests/helpers/create-seller-user.ts
index ea56774ad..986298e08 100644
--- a/integration-tests/helpers/create-seller-user.ts
+++ b/integration-tests/helpers/create-seller-user.ts
@@ -1,5 +1,7 @@
import {
IAuthModuleService,
+ IRegionModuleService,
+ IStoreModuleService,
MedusaContainer,
} from "@medusajs/framework/types"
import {
@@ -13,6 +15,32 @@ export const vendorHeaders = {
headers: { "x-medusa-access-token": "test_token" },
}
+export const ensureDefaultRegion = async (container: MedusaContainer) => {
+ const storeModule: IStoreModuleService = container.resolve(Modules.STORE)
+ const regionModule: IRegionModuleService = container.resolve(Modules.REGION)
+
+ const [store] = await storeModule.listStores()
+ if (store.default_region_id) {
+ return store.default_region_id
+ }
+
+ let [region] = await regionModule.listRegions(
+ { currency_code: "usd" },
+ { take: 1 }
+ )
+ if (!region) {
+ region = await regionModule.createRegions({
+ name: "Default",
+ currency_code: "usd",
+ countries: [],
+ })
+ }
+
+ await storeModule.updateStores(store.id, { default_region_id: region.id })
+
+ return region.id
+}
+
export const createSellerUser = async (
container: MedusaContainer,
options?: { email?: string; name?: string }
@@ -22,6 +50,8 @@ export const createSellerUser = async (
const authModule: IAuthModuleService = container.resolve(Modules.AUTH)
+ await ensureDefaultRegion(container)
+
// Low scrypt work factor: this is throwaway test data, and the helper runs
// on every seller-creating spec. scrypt-kdf embeds the params in the hash,
// so emailpass login still verifies against the cheaper cost factor.
diff --git a/integration-tests/helpers/link-seller-regions.ts b/integration-tests/helpers/link-seller-regions.ts
new file mode 100644
index 000000000..057fea304
--- /dev/null
+++ b/integration-tests/helpers/link-seller-regions.ts
@@ -0,0 +1,45 @@
+import {
+ IRegionModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+export const linkSellerRegions = async (
+ container: MedusaContainer,
+ sellerId: string,
+ regionIds: string[]
+) => {
+ const remoteLink = container.resolve(ContainerRegistrationKeys.LINK)
+
+ await remoteLink.create(
+ regionIds.map((regionId) => ({
+ [Modules.REGION]: { region_id: regionId },
+ [MercurModules.SELLER]: { seller_id: sellerId },
+ }))
+ )
+}
+
+export const linkSellerCurrencyRegions = async (
+ container: MedusaContainer,
+ sellerId: string,
+ currencyCodes: string[]
+) => {
+ const regionModule: IRegionModuleService = container.resolve(Modules.REGION)
+
+ const regions = await regionModule.createRegions(
+ currencyCodes.map((currency_code) => ({
+ name: `${currency_code.toUpperCase()} region ${sellerId}`,
+ currency_code,
+ countries: [],
+ }))
+ )
+
+ await linkSellerRegions(
+ container,
+ sellerId,
+ regions.map((region) => region.id)
+ )
+
+ return regions
+}
diff --git a/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts b/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts
index af3fb6bab..8bdd55bb2 100644
--- a/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts
+++ b/integration-tests/http/offer/vendor/offer-change-hooks.spec.ts
@@ -11,6 +11,7 @@ import { OfferDTO, OfferPriceDTO } from "@mercurjs/types"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
import { createVendorProduct } from "../../../helpers/create-product"
+import { linkSellerCurrencyRegions } from "../../../helpers/link-seller-regions"
jest.setTimeout(120000)
@@ -87,6 +88,9 @@ medusaIntegrationTestRunner({
})
headers = seller.headers
memberId = seller.member.id
+ await linkSellerCurrencyRegions(appContainer, seller.seller.id, [
+ "eur",
+ ])
const product = await createVendorProduct(api, headers, {
title: "Hooked Product",
diff --git a/integration-tests/http/offer/vendor/offer-region-prices.spec.ts b/integration-tests/http/offer/vendor/offer-region-prices.spec.ts
new file mode 100644
index 000000000..0b8a8f616
--- /dev/null
+++ b/integration-tests/http/offer/vendor/offer-region-prices.spec.ts
@@ -0,0 +1,280 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+
+import { createVendorProduct } from "../../../helpers/create-product"
+import { createShippingProfile } from "../../../helpers/create-shipping-profile"
+import { linkSellerRegions } from "../../../helpers/link-seller-regions"
+import { seedSellerOfferWithShipping } from "../../../helpers/split-order-checkout"
+
+jest.setTimeout(120000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Vendor - Offer region prices", () => {
+ let appContainer: MedusaContainer
+ let regionModuleService: IRegionModuleService
+ let salesChannelId: string
+ let sellerId: string
+ let headers: any
+ let offer: any
+ let usRegion: any
+ let euRegion: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ regionModuleService = appContainer.resolve(Modules.REGION)
+ })
+
+ beforeEach(async () => {
+ const salesChannelModule = appContainer.resolve(Modules.SALES_CHANNEL)
+ const [salesChannel] = await salesChannelModule.createSalesChannels([
+ { name: `SC ${Date.now()}` },
+ ])
+ salesChannelId = salesChannel.id
+
+ ;[usRegion, euRegion] = await regionModuleService.createRegions([
+ { name: "United States", currency_code: "usd", countries: ["us"] },
+ { name: "Europe", currency_code: "eur", countries: ["de"] },
+ ])
+
+ const seeded = await seedSellerOfferWithShipping({
+ container: appContainer,
+ api,
+ salesChannelId,
+ email: "[email protected]",
+ name: "RegionSeller",
+ stocked: 10,
+ offerPrice: 1000,
+ })
+ sellerId = seeded.sellerId
+ headers = seeded.headers
+ offer = seeded.offer
+
+ await linkSellerRegions(appContainer, sellerId, [usRegion.id])
+ })
+
+ const regionPriceOf = (prices: any[], regionId: string) =>
+ prices.find((p) =>
+ (p.price_rules ?? []).some(
+ (r: any) => r.attribute === "region_id" && r.value === regionId
+ )
+ )
+
+ describe("POST /vendor/offers/:id", () => {
+ it("stores a price scoped to an assigned region", async () => {
+ const response = await api.post(
+ `/vendor/offers/${offer.id}`,
+ {
+ prices: [
+ { amount: 1000, currency_code: "usd" },
+ {
+ amount: 1200,
+ currency_code: "usd",
+ rules: { region_id: usRegion.id },
+ },
+ ],
+ },
+ headers
+ )
+
+ expect(response.status).toEqual(200)
+ const regionPrice = regionPriceOf(
+ response.data.offer.prices,
+ usRegion.id
+ )
+ expect(regionPrice).toEqual(
+ expect.objectContaining({ amount: 1200, currency_code: "usd" })
+ )
+ })
+
+ it("rejects a price for a region not assigned to the seller", async () => {
+ const response = await api
+ .post(
+ `/vendor/offers/${offer.id}`,
+ {
+ prices: [
+ { amount: 1000, currency_code: "usd" },
+ {
+ amount: 900,
+ currency_code: "eur",
+ rules: { region_id: euRegion.id },
+ },
+ ],
+ },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain(euRegion.id)
+ })
+
+ it("rejects a base price in a currency no assigned region uses", async () => {
+ const response = await api
+ .post(
+ `/vendor/offers/${offer.id}`,
+ { prices: [{ amount: 900, currency_code: "eur" }] },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain("eur")
+ })
+
+ it("unlocks a currency once a region using it is assigned", async () => {
+ await linkSellerRegions(appContainer, sellerId, [euRegion.id])
+
+ const response = await api.post(
+ `/vendor/offers/${offer.id}`,
+ { prices: [{ amount: 900, currency_code: "eur" }] },
+ headers
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.offer.prices).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ amount: 900, currency_code: "eur" }),
+ ])
+ )
+ })
+
+ it("rejects a region price whose currency does not match the region", async () => {
+ const response = await api
+ .post(
+ `/vendor/offers/${offer.id}`,
+ {
+ prices: [
+ {
+ amount: 900,
+ currency_code: "eur",
+ rules: { region_id: usRegion.id },
+ },
+ ],
+ },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain("currency")
+ })
+ })
+
+ describe("POST /vendor/offers", () => {
+ it("creates an offer with an assigned-region price and rejects an unassigned one", async () => {
+ const shippingProfile = await createShippingProfile(appContainer, {
+ name: `SP region ${Date.now()}`,
+ })
+ const product = await createVendorProduct(api, headers, {
+ title: `Region product ${Date.now()}`,
+ sku: `REG-${Date.now()}`,
+ })
+
+ const base = {
+ variant_id: product.variants[0].id,
+ shipping_profile_id: shippingProfile.id,
+ inventory_items: [{ title: "Inv", required_quantity: 1 }],
+ }
+
+ const rejected = await api
+ .post(
+ `/vendor/offers`,
+ {
+ ...base,
+ sku: `OF-REJECT-${Date.now()}`,
+ prices: [
+ {
+ amount: 500,
+ currency_code: "eur",
+ rules: { region_id: euRegion.id },
+ },
+ ],
+ },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(rejected.status).toEqual(400)
+
+ const created = await api.post(
+ `/vendor/offers`,
+ {
+ ...base,
+ sku: `OF-OK-${Date.now()}`,
+ prices: [
+ { amount: 500, currency_code: "usd" },
+ {
+ amount: 650,
+ currency_code: "usd",
+ rules: { region_id: usRegion.id },
+ },
+ ],
+ },
+ headers
+ )
+
+ expect(created.status).toEqual(201)
+ expect(
+ regionPriceOf(created.data.offer.prices, usRegion.id)
+ ).toEqual(expect.objectContaining({ amount: 650 }))
+ })
+ })
+
+ describe("POST /vendor/shipping-options", () => {
+ it("rejects a shipping option price for an unassigned region", async () => {
+ const listed = await api.get(`/vendor/shipping-options`, headers)
+ const existing = listed.data.shipping_options[0]
+
+ const response = await api
+ .post(
+ `/vendor/shipping-options/${existing.id}`,
+ {
+ prices: [{ region_id: euRegion.id, amount: 700 }],
+ },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain(euRegion.id)
+ })
+
+ it("rejects a shipping option currency price no assigned region uses", async () => {
+ const listed = await api.get(`/vendor/shipping-options`, headers)
+ const existing = listed.data.shipping_options[0]
+
+ const response = await api
+ .post(
+ `/vendor/shipping-options/${existing.id}`,
+ { prices: [{ currency_code: "eur", amount: 700 }] },
+ headers
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+ expect(response.data.message).toContain("eur")
+ })
+
+ it("accepts a shipping option price for an assigned region", async () => {
+ const listed = await api.get(`/vendor/shipping-options`, headers)
+ const existing = listed.data.shipping_options[0]
+
+ const response = await api.post(
+ `/vendor/shipping-options/${existing.id}?fields=*prices`,
+ {
+ prices: [{ region_id: usRegion.id, amount: 700 }],
+ },
+ headers
+ )
+
+ expect(response.status).toEqual(200)
+ })
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/offer/vendor/offer.spec.ts b/integration-tests/http/offer/vendor/offer.spec.ts
index 91e42ca2c..2faa9f34c 100644
--- a/integration-tests/http/offer/vendor/offer.spec.ts
+++ b/integration-tests/http/offer/vendor/offer.spec.ts
@@ -4,6 +4,7 @@ import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
import { createVendorProduct } from "../../../helpers/create-product"
+import { linkSellerCurrencyRegions } from "../../../helpers/link-seller-regions"
jest.setTimeout(50000)
@@ -51,6 +52,10 @@ medusaIntegrationTestRunner({
name: "Seller One",
})
seller1Headers = result1.headers
+ await linkSellerCurrencyRegions(appContainer, result1.seller.id, [
+ "eur",
+ "gbp",
+ ])
const result2 = await createSellerUser(appContainer, {
diff --git a/integration-tests/http/regions/admin/region-sellers.spec.ts b/integration-tests/http/regions/admin/region-sellers.spec.ts
new file mode 100644
index 000000000..49e1a5c58
--- /dev/null
+++ b/integration-tests/http/regions/admin/region-sellers.spec.ts
@@ -0,0 +1,163 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Region sellers", () => {
+ let appContainer: MedusaContainer
+ let regionModuleService: IRegionModuleService
+ let sellerA: any
+ let sellerB: any
+ let usRegion: any
+ let euRegion: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ regionModuleService = appContainer.resolve(Modules.REGION)
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+
+ sellerA = (
+ await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Alpha Store",
+ })
+ ).seller
+ sellerB = (
+ await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Beta Store",
+ })
+ ).seller
+
+ ;[usRegion, euRegion] = await regionModuleService.createRegions([
+ { name: "United States", currency_code: "usd", countries: ["us"] },
+ { name: "Europe", currency_code: "eur", countries: ["de"] },
+ ])
+ })
+
+ describe("POST /admin/regions/:id/sellers", () => {
+ it("adds and removes sellers on a region", async () => {
+ const addResponse = await api.post(
+ `/admin/regions/${usRegion.id}/sellers`,
+ { add: [sellerA.id, sellerB.id] },
+ adminHeaders
+ )
+
+ expect(addResponse.status).toEqual(200)
+ expect(addResponse.data).toEqual({
+ id: usRegion.id,
+ object: "region",
+ })
+
+ const listResponse = await api.get(
+ `/admin/sellers?region_id=${usRegion.id}`,
+ adminHeaders
+ )
+
+ expect(listResponse.status).toEqual(200)
+ expect(listResponse.data.count).toEqual(2)
+ expect(
+ listResponse.data.sellers.map((s: any) => s.id).sort()
+ ).toEqual([sellerA.id, sellerB.id].sort())
+
+ const removeResponse = await api.post(
+ `/admin/regions/${usRegion.id}/sellers`,
+ { remove: [sellerB.id] },
+ adminHeaders
+ )
+
+ expect(removeResponse.status).toEqual(200)
+
+ const afterRemove = await api.get(
+ `/admin/sellers?region_id=${usRegion.id}`,
+ adminHeaders
+ )
+
+ expect(afterRemove.data.sellers.map((s: any) => s.id)).toEqual([
+ sellerA.id,
+ ])
+ })
+
+ it("returns an empty seller list for a region with no sellers", async () => {
+ const response = await api.get(
+ `/admin/sellers?region_id=${euRegion.id}`,
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.sellers).toEqual([])
+ expect(response.data.count).toEqual(0)
+ })
+
+ it("returns 404 when adding an unknown seller", async () => {
+ const response = await api
+ .post(
+ `/admin/regions/${usRegion.id}/sellers`,
+ { add: ["sel_does_not_exist"] },
+ adminHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+
+ it("returns 404 when the region does not exist", async () => {
+ const response = await api
+ .post(
+ `/admin/regions/reg_does_not_exist/sellers`,
+ { add: [sellerA.id] },
+ adminHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+ })
+
+ describe("GET /admin/sellers/:id", () => {
+ it("exposes the assigned regions on the seller", async () => {
+ await api.post(
+ `/admin/regions/${usRegion.id}/sellers`,
+ { add: [sellerA.id] },
+ adminHeaders
+ )
+ await api.post(
+ `/admin/regions/${euRegion.id}/sellers`,
+ { add: [sellerA.id] },
+ adminHeaders
+ )
+
+ const response = await api.get(
+ `/admin/sellers/${sellerA.id}`,
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.seller.regions.map((r: any) => r.id)).toEqual(
+ expect.arrayContaining([usRegion.id, euRegion.id])
+ )
+ expect(response.data.seller.regions[0]).toEqual(
+ expect.objectContaining({
+ name: expect.any(String),
+ currency_code: expect.any(String),
+ })
+ )
+ })
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/regions/vendor/regions.spec.ts b/integration-tests/http/regions/vendor/regions.spec.ts
index e64bb9ad6..782022f01 100644
--- a/integration-tests/http/regions/vendor/regions.spec.ts
+++ b/integration-tests/http/regions/vendor/regions.spec.ts
@@ -1,7 +1,11 @@
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
import { IRegionModuleService, MedusaContainer } from "@medusajs/framework/types"
import { Modules } from "@medusajs/framework/utils"
-import { createSellerUser } from "../../../helpers/create-seller-user"
+import {
+ createSellerUser,
+ ensureDefaultRegion,
+} from "../../../helpers/create-seller-user"
+import { linkSellerRegions } from "../../../helpers/link-seller-regions"
jest.setTimeout(50000)
@@ -10,24 +14,40 @@ medusaIntegrationTestRunner({
describe("Vendor - Regions", () => {
let appContainer: MedusaContainer
let sellerHeaders: any
+ let sellerId: string
+ let defaultRegionId: string
let regionModuleService: IRegionModuleService
+ const createAssignedRegions = async (
+ data: { name: string; currency_code: string; countries: string[] }[]
+ ) => {
+ const regions = await regionModuleService.createRegions(data)
+ await linkSellerRegions(
+ appContainer,
+ sellerId,
+ regions.map((r) => r.id)
+ )
+ return regions
+ }
+
beforeAll(async () => {
appContainer = getContainer()
regionModuleService = appContainer.resolve(Modules.REGION)
})
beforeEach(async () => {
+ defaultRegionId = await ensureDefaultRegion(appContainer)
const result = await createSellerUser(appContainer, {
name: "Test Seller",
})
sellerHeaders = result.headers
+ sellerId = result.seller.id
})
describe("GET /vendor/regions", () => {
it("should list regions", async () => {
- await regionModuleService.createRegions([
+ await createAssignedRegions([
{ name: "United States", currency_code: "usd", countries: ["us"] },
{ name: "Europe", currency_code: "eur", countries: ["de", "fr"] },
])
@@ -47,7 +67,7 @@ medusaIntegrationTestRunner({
})
it("should filter regions by name", async () => {
- await regionModuleService.createRegions([
+ await createAssignedRegions([
{ name: "unique-region-123", currency_code: "usd", countries: ["us"] },
])
@@ -62,7 +82,7 @@ medusaIntegrationTestRunner({
})
it("should filter regions by currency_code", async () => {
- await regionModuleService.createRegions([
+ await createAssignedRegions([
{ name: "GBP Region", currency_code: "gbp", countries: ["gb"] },
])
@@ -79,7 +99,7 @@ medusaIntegrationTestRunner({
})
it("should search regions with q parameter", async () => {
- await regionModuleService.createRegions([
+ await createAssignedRegions([
{ name: "Searchable Region", currency_code: "usd", countries: ["us"] },
])
@@ -97,8 +117,39 @@ medusaIntegrationTestRunner({
).toBe(true)
})
- it("should support pagination", async () => {
+ it("should hide regions that are not assigned to the seller", async () => {
+ const [assigned] = await createAssignedRegions([
+ { name: "Assigned Region", currency_code: "usd", countries: ["us"] },
+ ])
await regionModuleService.createRegions([
+ { name: "Unassigned Region", currency_code: "eur", countries: ["de"] },
+ ])
+
+ const response = await api.get(`/vendor/regions`, sellerHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data.regions.map((r: any) => r.id).sort()).toEqual(
+ [defaultRegionId, assigned.id].sort()
+ )
+ expect(response.data.count).toEqual(2)
+ })
+
+ it("should list only the store default region for a freshly registered seller", async () => {
+ await regionModuleService.createRegions([
+ { name: "Unassigned Region", currency_code: "eur", countries: ["de"] },
+ ])
+
+ const response = await api.get(`/vendor/regions`, sellerHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data.regions.map((r: any) => r.id)).toEqual([
+ defaultRegionId,
+ ])
+ expect(response.data.count).toEqual(1)
+ })
+
+ it("should support pagination", async () => {
+ await createAssignedRegions([
{ name: "Region A", currency_code: "usd", countries: ["us"] },
{ name: "Region B", currency_code: "eur", countries: ["de"] },
{ name: "Region C", currency_code: "gbp", countries: ["gb"] },
@@ -118,7 +169,7 @@ medusaIntegrationTestRunner({
describe("GET /vendor/regions/:id", () => {
it("should get a region by id", async () => {
- const [region] = await regionModuleService.createRegions([
+ const [region] = await createAssignedRegions([
{ name: "Get By Id Region", currency_code: "usd", countries: ["us"] },
])
@@ -134,6 +185,18 @@ medusaIntegrationTestRunner({
expect(response.data.region.currency_code).toEqual("usd")
})
+ it("should return 404 for a region not assigned to the seller", async () => {
+ const [region] = await regionModuleService.createRegions([
+ { name: "Other Seller Region", currency_code: "usd", countries: ["us"] },
+ ])
+
+ const response = await api
+ .get(`/vendor/regions/${region.id}`, sellerHeaders)
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+
it("should return 404 for non-existent region", async () => {
const response = await api
.get(`/vendor/regions/non-existent-id`, sellerHeaders)
diff --git a/integration-tests/http/seller/admin/seller-regions.spec.ts b/integration-tests/http/seller/admin/seller-regions.spec.ts
new file mode 100644
index 000000000..9a66ff3d3
--- /dev/null
+++ b/integration-tests/http/seller/admin/seller-regions.spec.ts
@@ -0,0 +1,213 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ IStoreModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Seller regions", () => {
+ let appContainer: MedusaContainer
+ let regionModuleService: IRegionModuleService
+ let storeModuleService: IStoreModuleService
+ let usRegion: any
+ let euRegion: any
+
+ const sellerPayload = (suffix: string) => ({
+ name: `Seller ${suffix}`,
+ email: `seller-${suffix}@test.com`,
+ currency_code: "usd",
+ member: { email: `member-${suffix}@test.com` },
+ })
+
+ const setDefaultRegion = async (regionId: string | null) => {
+ const [store] = await storeModuleService.listStores()
+ await storeModuleService.updateStores(store.id, {
+ default_region_id: regionId,
+ })
+ }
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ regionModuleService = appContainer.resolve(Modules.REGION)
+ storeModuleService = appContainer.resolve(Modules.STORE)
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+ ;[usRegion, euRegion] = await regionModuleService.createRegions([
+ { name: "United States", currency_code: "usd", countries: ["us"] },
+ { name: "Europe", currency_code: "eur", countries: ["de"] },
+ ])
+ })
+
+ describe("POST /admin/sellers", () => {
+ it("links the given region_ids together with the store default region", async () => {
+ await setDefaultRegion(usRegion.id)
+
+ const response = await api.post(
+ `/admin/sellers`,
+ { ...sellerPayload("explicit"), region_ids: [euRegion.id] },
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(201)
+ expect(response.data.seller.regions.map((r: any) => r.id).sort()).toEqual(
+ [usRegion.id, euRegion.id].sort()
+ )
+ })
+
+ it("links the given region_ids when the store has no default region", async () => {
+ await setDefaultRegion(null)
+
+ const response = await api.post(
+ `/admin/sellers`,
+ { ...sellerPayload("explicit-only"), region_ids: [euRegion.id] },
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(201)
+ expect(response.data.seller.regions.map((r: any) => r.id)).toEqual([
+ euRegion.id,
+ ])
+ })
+
+ it("links the store default region when region_ids is omitted", async () => {
+ await setDefaultRegion(usRegion.id)
+
+ const response = await api.post(
+ `/admin/sellers`,
+ sellerPayload("default"),
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(201)
+ expect(response.data.seller.regions.map((r: any) => r.id)).toEqual([
+ usRegion.id,
+ ])
+ })
+
+ it("returns 404 for an unknown region id", async () => {
+ const response = await api
+ .post(
+ `/admin/sellers`,
+ { ...sellerPayload("bad"), region_ids: ["reg_missing"] },
+ adminHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+ })
+
+ describe("seller account registration", () => {
+ it("links the store default region to a self-registered seller", async () => {
+ await setDefaultRegion(euRegion.id)
+
+ const { seller } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Registered Seller",
+ })
+
+ const response = await api.get(
+ `/admin/sellers/${seller.id}`,
+ adminHeaders
+ )
+
+ expect(response.data.seller.regions.map((r: any) => r.id)).toEqual([
+ euRegion.id,
+ ])
+ })
+ })
+
+ describe("POST /admin/sellers/:id/regions", () => {
+ it("adds and removes regions on a seller", async () => {
+ await setDefaultRegion(usRegion.id)
+ const { seller } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Linked Seller",
+ })
+
+ const addResponse = await api.post(
+ `/admin/sellers/${seller.id}/regions`,
+ { add: [euRegion.id] },
+ adminHeaders
+ )
+
+ expect(addResponse.status).toEqual(200)
+ expect(addResponse.data).toEqual({ id: seller.id, object: "seller" })
+
+ let detail = await api.get(`/admin/sellers/${seller.id}`, adminHeaders)
+ expect(detail.data.seller.regions.map((r: any) => r.id).sort()).toEqual(
+ [usRegion.id, euRegion.id].sort()
+ )
+
+ const removeResponse = await api.post(
+ `/admin/sellers/${seller.id}/regions`,
+ { remove: [usRegion.id] },
+ adminHeaders
+ )
+
+ expect(removeResponse.status).toEqual(200)
+
+ detail = await api.get(`/admin/sellers/${seller.id}`, adminHeaders)
+ expect(detail.data.seller.regions.map((r: any) => r.id)).toEqual([
+ euRegion.id,
+ ])
+ })
+
+ it("refuses to remove the last region of a seller", async () => {
+ await setDefaultRegion(usRegion.id)
+ const { seller } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Last Region Seller",
+ })
+
+ const response = await api
+ .post(
+ `/admin/sellers/${seller.id}/regions`,
+ { remove: [usRegion.id] },
+ adminHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(400)
+
+ const swap = await api.post(
+ `/admin/sellers/${seller.id}/regions`,
+ { add: [euRegion.id], remove: [usRegion.id] },
+ adminHeaders
+ )
+
+ expect(swap.status).toEqual(200)
+ })
+
+ it("returns 404 for an unknown region", async () => {
+ const { seller } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Unknown Region Seller",
+ })
+
+ const response = await api
+ .post(
+ `/admin/sellers/${seller.id}/regions`,
+ { add: ["reg_missing"] },
+ adminHeaders
+ )
+ .catch((e) => e.response)
+
+ expect(response.status).toEqual(404)
+ })
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/shipping-options/vendor/shipping-options.spec.ts b/integration-tests/http/shipping-options/vendor/shipping-options.spec.ts
index 1b8769ad5..4aac0df20 100644
--- a/integration-tests/http/shipping-options/vendor/shipping-options.spec.ts
+++ b/integration-tests/http/shipping-options/vendor/shipping-options.spec.ts
@@ -3,6 +3,7 @@ import { IFulfillmentModuleService, MedusaContainer } from "@medusajs/framework/
import { Modules } from "@medusajs/framework/utils"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
+import { linkSellerCurrencyRegions } from "../../../helpers/link-seller-regions"
jest.setTimeout(60000)
@@ -28,6 +29,9 @@ medusaIntegrationTestRunner({
})
_seller1 = result1.seller
seller1Headers = result1.headers
+ await linkSellerCurrencyRegions(appContainer, result1.seller.id, [
+ "eur",
+ ])
const result2 = await createSellerUser(appContainer, {
diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.ts
index bf2e98d93..047acb2fa 100644
--- a/packages/admin/src/extension-targets.d.ts
+++ b/packages/admin/src/extension-targets.d.ts
@@ -295,7 +295,7 @@ declare module "@mercurjs/dashboard-sdk" {
"seller": {
formZones: "create" | "edit"
formTabs: { "create": "details" | "users" }
- displayZones: "address" | "company-details" | "configuration" | "general" | "members" | "offers" | "orders" | "payment-details" | "requests"
+ displayZones: "address" | "company-details" | "configuration" | "general" | "members" | "offers" | "orders" | "payment-details" | "regions" | "requests"
displayFieldIds: "currency_code" | "description" | "email" | "handle" | "phone" | "website_url"
}
"user": {
diff --git a/packages/admin/src/get-route-map.tsx b/packages/admin/src/get-route-map.tsx
index f5a12bce2..fd21d8cf3 100644
--- a/packages/admin/src/get-route-map.tsx
+++ b/packages/admin/src/get-route-map.tsx
@@ -1011,6 +1011,12 @@ export function getRouteMap({
lazy: () =>
import("./pages/stores/store-member-invite"),
},
+ {
+ path: "regions/add",
+ handle: { permissions: "sellers:edit" },
+ lazy: () =>
+ import("./pages/stores/store-add-regions"),
+ },
],
},
],
@@ -1372,6 +1378,12 @@ export function getRouteMap({
lazy: () =>
import("./pages/regions/region-add-countries"),
},
+ {
+ path: "sellers/add",
+ handle: { permissions: "regions:edit" },
+ lazy: () =>
+ import("./pages/regions/region-add-sellers"),
+ },
{
path: "metadata/edit",
handle: { permissions: "regions:edit" },
diff --git a/packages/admin/src/hooks/api/regions.tsx b/packages/admin/src/hooks/api/regions.tsx
index 2e4f3bbbf..eb44ac262 100644
--- a/packages/admin/src/hooks/api/regions.tsx
+++ b/packages/admin/src/hooks/api/regions.tsx
@@ -14,6 +14,7 @@ import { sdk } from "../../lib/client"
import { queryClient } from "../../lib/query-client"
import { queryKeysFactory } from "../../lib/query-key-factory"
import { pricePreferencesQueryKeys } from "./price-preferences"
+import { sellersQueryKeys } from "./sellers"
const REGIONS_QUERY_KEY = "regions" as const
export const regionsQueryKeys = queryKeysFactory(REGIONS_QUERY_KEY)
@@ -139,3 +140,25 @@ export const useDeleteRegion = (
...options,
})
}
+
+export const useBatchRegionSellers = (
+ id: string,
+ options?: UseMutationOptions<
+ InferClientOutput<typeof sdk.admin.regions.$id.sellers.mutate>,
+ ClientError,
+ Omit<InferClientInput<typeof sdk.admin.regions.$id.sellers.mutate>, "$id">
+ >
+) => {
+ return useMutation({
+ mutationFn: (payload) =>
+ sdk.admin.regions.$id.sellers.mutate({ $id: id, ...payload }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: regionsQueryKeys.detail(id) })
+ queryClient.invalidateQueries({ queryKey: sellersQueryKeys.lists() })
+ queryClient.invalidateQueries({ queryKey: sellersQueryKeys.details() })
+
+ options?.onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/packages/admin/src/hooks/api/sellers.tsx b/packages/admin/src/hooks/api/sellers.tsx
index a4e6c333c..2d35644f0 100644
--- a/packages/admin/src/hooks/api/sellers.tsx
+++ b/packages/admin/src/hooks/api/sellers.tsx
@@ -13,6 +13,7 @@ import {
import { sdk } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
+import { regionsQueryKeys } from "./regions";
const SELLERS_QUERY_KEY = "sellers" as const;
export const sellersQueryKeys = queryKeysFactory(SELLERS_QUERY_KEY);
@@ -542,3 +543,25 @@ export const useSellerInvites = (
return { ...data, ...rest };
};
+
+export const useBatchSellerRegions = (
+ id: string,
+ options?: UseMutationOptions<
+ InferClientOutput<typeof sdk.admin.sellers.$id.regions.mutate>,
+ ClientError,
+ Omit<InferClientInput<typeof sdk.admin.sellers.$id.regions.mutate>, "$id">
+ >,
+) => {
+ return useMutation({
+ mutationFn: (payload) =>
+ sdk.admin.sellers.$id.regions.mutate({ $id: id, ...payload }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: sellersQueryKeys.detail(id) });
+ queryClient.invalidateQueries({ queryKey: sellersQueryKeys.lists() });
+ queryClient.invalidateQueries({ queryKey: regionsQueryKeys.details() });
+
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
diff --git a/packages/admin/src/i18n/translations/$schema.json b/packages/admin/src/i18n/translations/$schema.json
index 981f80e00..f87082223 100644
--- a/packages/admin/src/i18n/translations/$schema.json
+++ b/packages/admin/src/i18n/translations/$schema.json
@@ -12451,6 +12451,63 @@
"requirements"
],
"additionalProperties": false
+ },
+ "sellers": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "add": {
+ "type": "string"
+ },
+ "hint": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "string"
+ },
+ "noSellersToAdd": {
+ "type": "string"
+ },
+ "alreadyAssigned": {
+ "type": "string"
+ },
+ "removeWarning_one": {
+ "type": "string"
+ },
+ "removeWarning_other": {
+ "type": "string"
+ },
+ "toast": {
+ "type": "object",
+ "properties": {
+ "added": {
+ "type": "string"
+ },
+ "removed": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "added",
+ "removed"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "header",
+ "add",
+ "hint",
+ "empty",
+ "noSellersToAdd",
+ "alreadyAssigned",
+ "removeWarning_one",
+ "removeWarning_other",
+ "toast"
+ ],
+ "additionalProperties": false
}
},
"required": [
@@ -12477,7 +12534,8 @@
"calculated",
"list",
"toast",
- "shippingOption"
+ "shippingOption",
+ "sellers"
],
"additionalProperties": false
},
@@ -16554,6 +16612,9 @@
"out_of_stock"
],
"additionalProperties": false
+ },
+ "regionPrices": {
+ "type": "string"
}
},
"required": [
@@ -16566,7 +16627,8 @@
"bulkDelete",
"bulkDeleteAll",
"sellerSection",
- "stockStatus"
+ "stockStatus",
+ "regionPrices"
],
"additionalProperties": false
},
@@ -16861,6 +16923,102 @@
"redo"
],
"additionalProperties": false
+ },
+ "stores": {
+ "type": "object",
+ "properties": {
+ "regions": {
+ "type": "object",
+ "properties": {
+ "header": {
+ "type": "string"
+ },
+ "add": {
+ "type": "string"
+ },
+ "empty": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "message"
+ ],
+ "additionalProperties": false
+ },
+ "noRegionsToAdd": {
+ "type": "string"
+ },
+ "alreadyAssigned": {
+ "type": "string"
+ },
+ "removeWarning": {
+ "type": "string"
+ },
+ "toast": {
+ "type": "object",
+ "properties": {
+ "added": {
+ "type": "string"
+ },
+ "removed": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "added",
+ "removed"
+ ],
+ "additionalProperties": false
+ },
+ "hint": {
+ "type": "string"
+ },
+ "lastRegion": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "header",
+ "add",
+ "empty",
+ "noRegionsToAdd",
+ "alreadyAssigned",
+ "removeWarning",
+ "toast",
+ "hint",
+ "lastRegion"
+ ],
+ "additionalProperties": false
+ },
+ "create": {
+ "type": "object",
+ "properties": {
+ "regions": {
+ "type": "string"
+ },
+ "regionsHint": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "regions",
+ "regionsHint"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "regions",
+ "create"
+ ],
+ "additionalProperties": false
}
},
"required": [
@@ -16933,7 +17091,8 @@
"offers",
"roles",
"permissions",
- "richTextEditor"
+ "richTextEditor",
+ "stores"
],
"additionalProperties": false
}
diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.json
index c2511b946..e36698819 100644
--- a/packages/admin/src/i18n/translations/en.json
+++ b/packages/admin/src/i18n/translations/en.json
@@ -3170,6 +3170,20 @@
"label": "Requirements",
"hint": "Specify the requirements for the shipping option."
}
+ },
+ "sellers": {
+ "header": "Stores",
+ "add": "Add stores",
+ "hint": "Stores assigned to this region can see it and price offers and shipping in its currency.",
+ "empty": "No stores are assigned to this region.",
+ "noSellersToAdd": "There are no stores to add.",
+ "alreadyAssigned": "This store is already assigned to the region.",
+ "removeWarning_one": "You are about to remove {{count}} store from this region. The store will no longer be able to price offers or shipping in it.",
+ "removeWarning_other": "You are about to remove {{count}} stores from this region. They will no longer be able to price offers or shipping in it.",
+ "toast": {
+ "added": "Stores added to region successfully",
+ "removed": "Stores removed from region successfully"
+ }
}
},
"taxes": {
@@ -3570,10 +3584,10 @@
},
"offerConditions": {
"domain": "Offer Conditions",
- "subtitle": "Manage the conditions sellers can list offers under.",
+ "subtitle": "Manage the conditions stores can list offers under.",
"create": {
"header": "Create Offer Condition",
- "subtitle": "Specify the conditions sellers can list their offers under.",
+ "subtitle": "Specify the conditions stores can list their offers under.",
"successToast": "Offer condition {{label}} was successfully created."
},
"edit": {
@@ -3601,7 +3615,7 @@
},
"isActive": {
"label": "Enabled",
- "hint": "When disabled, sellers can't list new offers under this condition."
+ "hint": "When disabled, stores can't list new offers under this condition."
}
}
},
@@ -4196,7 +4210,9 @@
"emailRequired": "Please enter an email",
"emailInvalid": "Please enter a valid email",
"currencyRequired": "Please select a currency"
- }
+ },
+ "regions": "Regions",
+ "regionsHint": "The store default region is always assigned. Each assigned region unlocks its currency for pricing."
},
"request": {
"title": "Store request",
@@ -4243,6 +4259,23 @@
"successToast": "{{count}} store(s) updated",
"emptyHeading": "No stores selected",
"emptyDescription": "Select stores from the list to edit them here."
+ },
+ "regions": {
+ "header": "Regions",
+ "add": "Add regions",
+ "empty": {
+ "title": "No regions assigned",
+ "message": "Assign regions so the seller can price offers and shipping in them."
+ },
+ "noRegionsToAdd": "There are no regions to add.",
+ "alreadyAssigned": "This region is already assigned to the seller.",
+ "removeWarning": "You are about to remove the region {{name}} from this seller. The seller will no longer be able to price offers or shipping in it.",
+ "toast": {
+ "added": "Regions added successfully",
+ "removed": "Region removed successfully"
+ },
+ "hint": "Assigned regions decide which currencies this store can price in. The default region is assigned on creation.",
+ "lastRegion": "A store must stay assigned to at least one region."
}
},
"messages": {
@@ -4477,7 +4510,8 @@
"in_stock": "In stock",
"low_stock": "Low stock",
"out_of_stock": "Out of stock"
- }
+ },
+ "regionPrices": "Region prices"
},
"permissions": {
"noAccess": "You don't have permission to view this.",
diff --git a/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx b/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
index 528634ada..4e155c87b 100644
--- a/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
+++ b/packages/admin/src/pages/offers/[id]/_components/offer-pricing-section.tsx
@@ -2,7 +2,9 @@ import { Button, Container, Heading } from "@medusajs/ui"
import { useState } from "react"
import { useTranslation } from "react-i18next"
+import { useCan } from "@mercurjs/dashboard-shared"
import { NoRecords } from "../../../../components/common/empty-table-content"
+import { useRegions } from "../../../../hooks/api/regions"
import { getLocaleAmount } from "../../../../lib/money-amount-helpers"
import { OfferDetail, OfferPrice } from "../../common/types"
@@ -10,15 +12,25 @@ type Props = { offer: OfferDetail }
const PAGE_STEP = 3
+const getPriceRegionId = (price: OfferPrice): string | null =>
+ price.price_rules?.find((r) => r.attribute === "region_id")?.value ?? null
+
const isBaseRow = (price: OfferPrice) => {
if (!price) return false
const rules = price.price_rules ?? []
- const extraRules = rules.filter((r) => r.attribute !== "offer_id")
- return extraRules.length === 0
+ return rules.every((r) => r.attribute === "offer_id")
}
export const OfferPricingSection = ({ offer }: Props) => {
const { t } = useTranslation()
+ const canViewRegions = useCan("regions")
+ const { regions } = useRegions(
+ { fields: "id,name", limit: 999 },
+ { enabled: canViewRegions },
+ )
+
+ const regionName = (regionId: string) =>
+ regions?.find((r) => r.id === regionId)?.name ?? regionId
const prices = (offer.prices ?? [])
.filter((p): p is OfferPrice => Boolean(p) && isBaseRow(p))
@@ -26,6 +38,14 @@ export const OfferPricingSection = ({ offer }: Props) => {
(a.currency_code ?? "").localeCompare(b.currency_code ?? ""),
)
+ const regionPrices = (offer.prices ?? [])
+ .filter((p): p is OfferPrice => Boolean(p) && getPriceRegionId(p) !== null)
+ .sort((a, b) =>
+ regionName(getPriceRegionId(a)!).localeCompare(
+ regionName(getPriceRegionId(b)!),
+ ),
+ )
+
const hasPrices = prices.length > 0
const [pageSize, setPageSize] = useState(PAGE_STEP)
const displayPrices = prices.slice(0, pageSize)
@@ -51,6 +71,23 @@ export const OfferPricingSection = ({ offer }: Props) => {
<span>{getLocaleAmount(price.amount, price.currency_code)}</span>
</div>
))}
+ {regionPrices.length > 0 && (
+ <div className="txt-small text-ui-fg-muted px-6 py-2">
+ {t("offers.regionPrices")}
+ </div>
+ )}
+ {regionPrices.map((price) => (
+ <div
+ key={price.id ?? `${getPriceRegionId(price)}-${price.amount}`}
+ className="txt-small text-ui-fg-subtle flex justify-between px-6 py-4"
+ data-testid={`offer-detail-region-price-${getPriceRegionId(price)}`}
+ >
+ <span className="font-medium">
+ {regionName(getPriceRegionId(price)!)}
+ </span>
+ <span>{getLocaleAmount(price.amount, price.currency_code)}</span>
+ </div>
+ ))}
{hasPrices && prices.length > PAGE_STEP && (
<div className="txt-small text-ui-fg-subtle flex items-center justify-end px-6 py-4">
<Button
diff --git a/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/add-sellers-form.tsx b/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/add-sellers-form.tsx
new file mode 100644
index 000000000..a37838430
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/add-sellers-form.tsx
@@ -0,0 +1,238 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import type { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ type OnChangeFn,
+ type RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { SellerDTO } from "@mercurjs/types"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "../../../../../components/modals"
+import { _DataTable } from "../../../../../components/table/data-table"
+import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
+import { useBatchRegionSellers } from "../../../../../hooks/api/regions"
+import { useSellers } from "../../../../../hooks/api/sellers"
+import { useSellersTableColumns } from "../../../../../hooks/table/columns/use-seller-table-columns"
+import { useSellersTableQuery } from "../../../../../hooks/table/query"
+import { useDataTable } from "../../../../../hooks/use-data-table"
+
+type AddSellersFormProps = {
+ region: HttpTypes.AdminRegion
+}
+
+const AddSellersSchema = zod.object({
+ seller_ids: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "as"
+
+const isAssigned = (seller: SellerDTO, regionId: string) =>
+ (seller.regions ?? []).some((r) => r.id === regionId)
+
+export const AddSellersForm = ({ region }: AddSellersFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof AddSellersSchema>>({
+ defaultValues: {
+ seller_ids: [],
+ },
+ resolver: zodResolver(AddSellersSchema),
+ })
+
+ const { setValue } = form
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+
+ setValue("seller_ids", Object.keys(state), {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const { searchParams, raw } = useSellersTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { sellers, count, isPending, isError, error } = useSellers(
+ { ...searchParams, fields: "+regions.id" },
+ { placeholderData: keepPreviousData }
+ )
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: sellers ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ enableRowSelection: (row) => !isAssigned(row.original, region.id),
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ prefix: PREFIX,
+ meta: {
+ regionId: region.id,
+ },
+ })
+
+ const { mutateAsync, isPending: isMutating } = useBatchRegionSellers(
+ region.id
+ )
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ { add: values.seller_ids },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.sellers.toast.added"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form} data-testid="region-add-sellers-form">
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header data-testid="region-add-sellers-form-header">
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.seller_ids && (
+ <Hint variant="error" data-testid="region-add-sellers-form-error">
+ {form.formState.errors.seller_ids.message}
+ </Hint>
+ )}
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body
+ className="overflow-hidden"
+ data-testid="region-add-sellers-form-body"
+ >
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count ?? 0}
+ isLoading={isPending}
+ search="autofocus"
+ pagination
+ layout="fill"
+ queryObject={raw}
+ prefix={PREFIX}
+ noRecords={{
+ message: t("regions.sellers.noSellersToAdd"),
+ }}
+ data-testid="region-add-sellers-form-table"
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer data-testid="region-add-sellers-form-footer">
+ <RouteFocusModal.Close asChild>
+ <Button
+ size="small"
+ variant="secondary"
+ data-testid="region-add-sellers-form-cancel-button"
+ >
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ isLoading={isMutating}
+ type="submit"
+ data-testid="region-add-sellers-form-add-button"
+ >
+ {t("actions.add")}
+ </Button>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<SellerDTO>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const base = useSellersTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ data-testid="region-add-sellers-form-select-all-checkbox"
+ />
+ ),
+ cell: ({ row, table }) => {
+ const { regionId } = table.options.meta as { regionId: string }
+ const assigned = isAssigned(row.original, regionId)
+
+ const checkbox = (
+ <Checkbox
+ checked={row.getIsSelected() || assigned}
+ disabled={assigned}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ data-testid={`region-add-sellers-form-select-checkbox-${row.original.id}`}
+ />
+ )
+
+ if (assigned) {
+ return (
+ <Tooltip
+ content={t("regions.sellers.alreadyAssigned")}
+ side="right"
+ >
+ {checkbox}
+ </Tooltip>
+ )
+ }
+
+ return checkbox
+ },
+ }),
+ ...base,
+ ],
+ [t, base]
+ )
+}
diff --git a/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/index.ts b/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/index.ts
new file mode 100644
index 000000000..b9a163fb5
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-add-sellers/components/add-sellers-form/index.ts
@@ -0,0 +1 @@
+export * from "./add-sellers-form"
diff --git a/packages/admin/src/pages/regions/region-add-sellers/index.ts b/packages/admin/src/pages/regions/region-add-sellers/index.ts
new file mode 100644
index 000000000..30bb0c450
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-add-sellers/index.ts
@@ -0,0 +1 @@
+export { RegionAddSellers as Component } from "./region-add-sellers"
diff --git a/packages/admin/src/pages/regions/region-add-sellers/region-add-sellers.tsx b/packages/admin/src/pages/regions/region-add-sellers/region-add-sellers.tsx
new file mode 100644
index 000000000..8deca0854
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-add-sellers/region-add-sellers.tsx
@@ -0,0 +1,25 @@
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "../../../components/modals"
+import { useRegion } from "../../../hooks/api/regions"
+import { AddSellersForm } from "./components/add-sellers-form"
+
+export const RegionAddSellers = () => {
+ const { id } = useParams()
+
+ const {
+ region,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useRegion(id!, { fields: "id,name" })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal data-testid="region-add-sellers-modal">
+ {!isLoading && region && <AddSellersForm region={region} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/admin/src/pages/regions/region-detail/components/region-seller-section/index.ts b/packages/admin/src/pages/regions/region-detail/components/region-seller-section/index.ts
new file mode 100644
index 000000000..73e205d95
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-detail/components/region-seller-section/index.ts
@@ -0,0 +1 @@
+export * from "./region-seller-section"
diff --git a/packages/admin/src/pages/regions/region-detail/components/region-seller-section/region-seller-section.tsx b/packages/admin/src/pages/regions/region-detail/components/region-seller-section/region-seller-section.tsx
new file mode 100644
index 000000000..b4e5d78d7
--- /dev/null
+++ b/packages/admin/src/pages/regions/region-detail/components/region-seller-section/region-seller-section.tsx
@@ -0,0 +1,256 @@
+import { PlusMini, Trash } from "@medusajs/icons"
+import type { HttpTypes } from "@medusajs/types"
+import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ type RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+
+import { SellerDTO } from "@mercurjs/types"
+import { ActionMenu } from "../../../../../components/common/action-menu"
+import { _DataTable } from "../../../../../components/table/data-table"
+import { useBatchRegionSellers } from "../../../../../hooks/api/regions"
+import { useSellers } from "../../../../../hooks/api/sellers"
+import { useSellersTableColumns } from "../../../../../hooks/table/columns/use-seller-table-columns"
+import { useSellersTableQuery } from "../../../../../hooks/table/query"
+import { useDataTable } from "../../../../../hooks/use-data-table"
+
+type RegionSellerSectionProps = {
+ region: HttpTypes.AdminRegion
+}
+
+const PREFIX = "rs"
+const PAGE_SIZE = 10
+
+export const RegionSellerSection = ({ region }: RegionSellerSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const { searchParams, raw } = useSellersTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { sellers, count, isPending, isError, error } = useSellers(
+ { ...searchParams, region_id: region.id },
+ { placeholderData: keepPreviousData }
+ )
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: sellers ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ prefix: PREFIX,
+ meta: {
+ regionId: region.id,
+ },
+ })
+
+ const { mutateAsync } = useBatchRegionSellers(region.id)
+
+ const handleRemoveSellers = async () => {
+ const ids = Object.keys(rowSelection).filter((k) => rowSelection[k])
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.sellers.removeWarning", {
+ count: ids.length,
+ }),
+ cancelText: t("actions.cancel"),
+ confirmText: t("actions.remove"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(
+ { remove: ids },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.sellers.toast.removed"))
+ setRowSelection({})
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container
+ className="divide-y p-0"
+ data-testid="region-seller-section-container"
+ >
+ <div
+ className="flex items-center justify-between px-6 py-4"
+ data-testid="region-seller-section-header"
+ >
+ <Heading level="h2" data-testid="region-seller-section-heading">
+ {t("regions.sellers.header")}
+ </Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ permission: "regions:edit",
+ label: t("regions.sellers.add"),
+ icon: <PlusMini />,
+ to: "sellers/add",
+ },
+ ],
+ },
+ ]}
+ data-testid="region-seller-section-action-menu"
+ />
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count ?? 0}
+ isLoading={isPending}
+ search
+ pagination
+ queryObject={raw}
+ prefix={PREFIX}
+ navigateTo={(row) => `/stores/${row.original.id}`}
+ commands={[
+ {
+ action: handleRemoveSellers,
+ permission: "regions:edit",
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ noRecords={{
+ message: t("regions.sellers.empty"),
+ }}
+ data-testid="region-seller-section-table"
+ />
+ </Container>
+ )
+}
+
+const SellerActions = ({
+ seller,
+ regionId,
+}: {
+ seller: SellerDTO
+ regionId: string
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useBatchRegionSellers(regionId)
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.sellers.removeWarning", { count: 1 }),
+ cancelText: t("actions.cancel"),
+ confirmText: t("actions.remove"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(
+ { remove: [seller.id] },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.sellers.toast.removed"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ permission: "regions:edit",
+ label: t("actions.remove"),
+ onClick: handleRemove,
+ },
+ ],
+ },
+ ]}
+ data-testid={`region-seller-section-row-action-menu-${seller.id}`}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<SellerDTO>()
+
+const useColumns = () => {
+ const base = useSellersTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ data-testid="region-seller-section-select-all-checkbox"
+ />
+ ),
+ cell: ({ row }) => (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ data-testid={`region-seller-section-select-checkbox-${row.original.id}`}
+ />
+ ),
+ }),
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row, table }) => {
+ const { regionId } = table.options.meta as { regionId: string }
+
+ return <SellerActions seller={row.original} regionId={regionId} />
+ },
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/admin/src/pages/regions/region-detail/region-detail.tsx b/packages/admin/src/pages/regions/region-detail/region-detail.tsx
index c5a34269e..3fa7978a0 100644
--- a/packages/admin/src/pages/regions/region-detail/region-detail.tsx
+++ b/packages/admin/src/pages/regions/region-detail/region-detail.tsx
@@ -4,6 +4,7 @@ import { useLoaderData, useParams } from "react-router-dom";
import { useRegion } from "../../../hooks/api/regions";
import { RegionCountrySection } from "./components/region-country-section";
import { RegionGeneralSection } from "./components/region-general-section";
+import { RegionSellerSection } from "./components/region-seller-section";
import { regionLoader } from "./loader";
import { WidgetZone, isForbidden, useCan } from "@mercurjs/dashboard-shared";
@@ -53,7 +54,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
(!preferencesForbidden && isLoadingPreferences) ||
!region
) {
- return <SingleColumnPageSkeleton sections={2} showJSON showMetadata />
+ return <SingleColumnPageSkeleton sections={3} showJSON showMetadata />
}
if (isRegionError) {
@@ -78,6 +79,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
}
/>
<RegionCountrySection region={region} />
+ <RegionSellerSection region={region} />
</WidgetZone>
</SingleColumnPage>
);
@@ -86,4 +88,5 @@ const Root = ({ children }: { children?: ReactNode }) => {
export const RegionDetailPage = Object.assign(Root, {
GeneralSection: RegionGeneralSection,
CountrySection: RegionCountrySection,
+ SellerSection: RegionSellerSection,
});
diff --git a/packages/admin/src/pages/stores/store-add-regions/components/add-regions-form.tsx b/packages/admin/src/pages/stores/store-add-regions/components/add-regions-form.tsx
new file mode 100644
index 000000000..be751f1cb
--- /dev/null
+++ b/packages/admin/src/pages/stores/store-add-regions/components/add-regions-form.tsx
@@ -0,0 +1,241 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import type { HttpTypes } from "@medusajs/types";
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui";
+import { keepPreviousData } from "@tanstack/react-query";
+import {
+ type OnChangeFn,
+ type RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table";
+import { useMemo, useState } from "react";
+import { useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import * as zod from "zod";
+
+import { InferClientOutput } from "@mercurjs/client";
+import { SellerRegionDTO } from "@mercurjs/types";
+import { sdk } from "@lib/client";
+
+import { RouteFocusModal, useRouteModal } from "../../../../components/modals";
+import { _DataTable } from "../../../../components/table/data-table";
+import { KeyboundForm } from "../../../../components/utilities/keybound-form";
+import { useRegions } from "../../../../hooks/api/regions";
+import { useBatchSellerRegions } from "../../../../hooks/api/sellers";
+import { useRegionTableColumns } from "../../../../hooks/table/columns/use-region-table-columns";
+import { useRegionTableQuery } from "../../../../hooks/table/query/use-region-table-query";
+import { useDataTable } from "../../../../hooks/use-data-table";
+
+type Seller = InferClientOutput<typeof sdk.admin.sellers.$id.query>["seller"];
+
+type AddRegionsFormProps = {
+ seller: Seller;
+};
+
+const AddRegionsSchema = zod.object({
+ region_ids: zod.array(zod.string()).min(1),
+});
+
+const PAGE_SIZE = 50;
+const PREFIX = "ar";
+
+export const AddRegionsForm = ({ seller }: AddRegionsFormProps) => {
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+
+ const assignedIds = useMemo(
+ () => new Set(((seller.regions ?? []) as SellerRegionDTO[]).map((r) => r.id)),
+ [seller.regions],
+ );
+
+ const form = useForm<zod.infer<typeof AddRegionsSchema>>({
+ defaultValues: {
+ region_ids: [],
+ },
+ resolver: zodResolver(AddRegionsSchema),
+ });
+
+ const { setValue } = form;
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn;
+
+ setValue("region_ids", Object.keys(state), {
+ shouldDirty: true,
+ shouldTouch: true,
+ });
+
+ setRowSelection(state);
+ };
+
+ const { searchParams, raw } = useRegionTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ });
+
+ const { regions, count, isPending, isError, error } = useRegions(
+ { ...searchParams, fields: "id,name,currency_code,*countries,*payment_providers" },
+ { placeholderData: keepPreviousData },
+ );
+
+ const columns = useColumns();
+
+ const { table } = useDataTable({
+ data: regions ?? [],
+ columns,
+ count: count ?? 0,
+ enablePagination: true,
+ enableRowSelection: (row) => !assignedIds.has(row.original.id),
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ prefix: PREFIX,
+ meta: {
+ assignedIds,
+ },
+ });
+
+ const { mutateAsync, isPending: isMutating } = useBatchSellerRegions(seller.id);
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ { add: values.region_ids },
+ {
+ onSuccess: () => {
+ toast.success(t("stores.regions.toast.added"));
+ handleSuccess();
+ },
+ onError: (e) => {
+ toast.error(e.message);
+ },
+ },
+ );
+ });
+
+ if (isError) {
+ throw error;
+ }
+
+ return (
+ <RouteFocusModal.Form form={form} data-testid="store-add-regions-form">
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header data-testid="store-add-regions-form-header">
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.region_ids && (
+ <Hint variant="error" data-testid="store-add-regions-form-error">
+ {form.formState.errors.region_ids.message}
+ </Hint>
+ )}
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body
+ className="overflow-hidden"
+ data-testid="store-add-regions-form-body"
+ >
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count ?? 0}
+ isLoading={isPending}
+ search="autofocus"
+ pagination
+ layout="fill"
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ ]}
+ queryObject={raw}
+ prefix={PREFIX}
+ noRecords={{
+ message: t("stores.regions.noRegionsToAdd"),
+ }}
+ data-testid="store-add-regions-form-table"
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer data-testid="store-add-regions-form-footer">
+ <RouteFocusModal.Close asChild>
+ <Button
+ size="small"
+ variant="secondary"
+ data-testid="store-add-regions-form-cancel-button"
+ >
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ isLoading={isMutating}
+ type="submit"
+ data-testid="store-add-regions-form-add-button"
+ >
+ {t("actions.add")}
+ </Button>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ );
+};
+
+const columnHelper = createColumnHelper<HttpTypes.AdminRegion>();
+
+const useColumns = () => {
+ const { t } = useTranslation();
+ const base = useRegionTableColumns();
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
+ data-testid="store-add-regions-form-select-all-checkbox"
+ />
+ ),
+ cell: ({ row, table }) => {
+ const { assignedIds } = table.options.meta as {
+ assignedIds: Set<string>;
+ };
+ const assigned = assignedIds.has(row.original.id);
+
+ const checkbox = (
+ <Checkbox
+ checked={row.getIsSelected() || assigned}
+ disabled={assigned}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation();
+ }}
+ data-testid={`store-add-regions-form-select-checkbox-${row.original.id}`}
+ />
+ );
+
+ if (assigned) {
+ return (
+ <Tooltip content={t("stores.regions.alreadyAssigned")} side="right">
+ {checkbox}
+ </Tooltip>
+ );
+ }
+
+ return checkbox;
+ },
+ }),
+ ...base,
+ ],
+ [t, base],
+ );
+};
diff --git a/packages/admin/src/pages/stores/store-add-regions/index.ts b/packages/admin/src/pages/stores/store-add-regions/index.ts
new file mode 100644
index 000000000..c467160c0
--- /dev/null
+++ b/packages/admin/src/pages/stores/store-add-regions/index.ts
@@ -0,0 +1 @@
+export { StoreAddRegions as Component } from "./store-add-regions";
diff --git a/packages/admin/src/pages/stores/store-add-regions/store-add-regions.tsx b/packages/admin/src/pages/stores/store-add-regions/store-add-regions.tsx
new file mode 100644
index 000000000..f4c85ab3a
--- /dev/null
+++ b/packages/admin/src/pages/stores/store-add-regions/store-add-regions.tsx
@@ -0,0 +1,25 @@
+import { useParams } from "react-router-dom";
+import { RouteFocusModal } from "../../../components/modals";
+import { useSeller } from "../../../hooks/api/sellers";
+import { AddRegionsForm } from "./components/add-regions-form";
+
+export const StoreAddRegions = () => {
+ const { id } = useParams();
+
+ const {
+ seller,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useSeller(id!, { fields: "+regions.id" });
+
+ if (isError) {
+ throw error;
+ }
+
+ return (
+ <RouteFocusModal data-testid="store-add-regions-modal">
+ {!isLoading && seller && <AddRegionsForm seller={seller} />}
+ </RouteFocusModal>
+ );
+};
diff --git a/packages/admin/src/pages/stores/store-create/components/schema.ts b/packages/admin/src/pages/stores/store-create/components/schema.ts
index 036e0e006..156e7ff2c 100644
--- a/packages/admin/src/pages/stores/store-create/components/schema.ts
+++ b/packages/admin/src/pages/stores/store-create/components/schema.ts
@@ -14,6 +14,7 @@ export const CreateStoreSchema = z.object({
.string()
.min(1, { message: i18n.t("stores.create.validation.currencyRequired") }),
handle: z.string().optional().or(z.literal("")),
+ region_ids: z.array(z.string()),
member_email: z
.string()
.min(1, { message: i18n.t("stores.create.validation.emailRequired") })
diff --git a/packages/admin/src/pages/stores/store-create/components/store-create-details-tab.tsx b/packages/admin/src/pages/stores/store-create/components/store-create-details-tab.tsx
index 86ef39c8f..cfa2de80e 100644
--- a/packages/admin/src/pages/stores/store-create/components/store-create-details-tab.tsx
+++ b/packages/admin/src/pages/stores/store-create/components/store-create-details-tab.tsx
@@ -1,12 +1,15 @@
import { usePermissionGate } from "@mercurjs/dashboard-shared";
import { Heading, Input, Select } from "@medusajs/ui";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Form } from "../../../../components/common/form";
+import { Combobox } from "../../../../components/inputs/combobox";
import { HandleInput } from "../../../../components/inputs/handle-input";
import { useTabbedForm } from "../../../../components/tabbed-form/tabbed-form";
import { defineTabMeta } from "../../../../components/tabbed-form/types";
import { useStore } from "../../../../hooks/api";
+import { useRegions } from "../../../../hooks/api/regions";
import { CreateStoreSchemaType } from "./schema";
import { ConditionalTooltip } from "../../../../components/common/conditional-tooltip";
@@ -15,6 +18,20 @@ const Root = () => {
const form = useTabbedForm<CreateStoreSchemaType>();
const storeGate = usePermissionGate("store:view");
const { store } = useStore(undefined, { enabled: storeGate.allowed });
+ const regionsGate = usePermissionGate("regions:view");
+ const { regions } = useRegions(
+ { fields: "id,name,currency_code", limit: 100 },
+ { enabled: regionsGate.allowed },
+ );
+
+ const defaultRegionId = store?.default_region_id ?? null;
+ const { getValues, setValue } = form;
+
+ useEffect(() => {
+ if (defaultRegionId && getValues("region_ids").length === 0) {
+ setValue("region_ids", [defaultRegionId]);
+ }
+ }, [defaultRegionId, getValues, setValue]);
return (
<div className="flex flex-1 flex-col items-center overflow-y-auto px-3">
@@ -115,6 +132,37 @@ const Root = () => {
</Form.Item>
)}
/>
+ <Form.Field
+ control={form.control}
+ name="region_ids"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label optional tooltip={t("stores.create.regionsHint")}>
+ {t("stores.create.regions")}
+ </Form.Label>
+ <ConditionalTooltip
+ showTooltip={regionsGate.denied}
+ content={regionsGate.tooltip}
+ >
+ <div>
+ <Form.Control>
+ <Combobox
+ {...field}
+ disabled={field.disabled || regionsGate.denied}
+ options={(regions ?? []).map((region) => ({
+ label: `${region.name} (${region.currency_code.toUpperCase()})`,
+ value: region.id,
+ }))}
+ placeholder={t("fields.selectPlaceholder")}
+ data-testid="store-create-form-regions-combobox"
+ />
+ </Form.Control>
+ </div>
+ </ConditionalTooltip>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
</div>
</div>
</div>
diff --git a/packages/admin/src/pages/stores/store-create/components/store-create-form.tsx b/packages/admin/src/pages/stores/store-create/components/store-create-form.tsx
index 96aa5fd27..5a469880c 100644
--- a/packages/admin/src/pages/stores/store-create/components/store-create-form.tsx
+++ b/packages/admin/src/pages/stores/store-create/components/store-create-form.tsx
@@ -27,6 +27,7 @@ export const StoreCreateForm = ({ children }: StoreCreateFormProps) => {
phone: "",
currency_code: "",
handle: "",
+ region_ids: [],
member_email: "",
},
mode: "onSubmit",
@@ -44,6 +45,7 @@ export const StoreCreateForm = ({ children }: StoreCreateFormProps) => {
phone: values.phone || undefined,
currency_code: values.currency_code,
handle: values.handle || undefined,
+ region_ids: values.region_ids,
member: {
email: values.member_email,
},
diff --git a/packages/admin/src/pages/stores/store-details/components/store-details.tsx b/packages/admin/src/pages/stores/store-details/components/store-details.tsx
index 7d2bbe0a3..1608fb7b2 100644
--- a/packages/admin/src/pages/stores/store-details/components/store-details.tsx
+++ b/packages/admin/src/pages/stores/store-details/components/store-details.tsx
@@ -21,6 +21,7 @@ import { StorePaymentDetailsSection } from "./store-payment-details-section";
import { StoreCompanyDetailsSection } from "./store-company-details-section";
import { StoreConfigurationSection } from "./store-configuration-section";
import { StoreAddressSection } from "./store-address-section";
+import { StoreRegionsSection } from "./store-regions-section";
import { StoreMembersSection } from "./store-members-section";
import { StoreRequestSection } from "./store-request-section";
import { StoreOrdersSection } from "./store-orders-section";
@@ -94,7 +95,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
const { seller, isLoading, isError, error } = useSeller(id!, query);
if (isLoading || !seller) {
- return <TwoColumnPageSkeleton mainSections={3} sidebarSections={3} />;
+ return <TwoColumnPageSkeleton mainSections={3} sidebarSections={4} />;
}
if (isError) {
@@ -177,6 +178,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
<TwoColumnPage.Sidebar>
<WidgetZone id="stores.detail.side" data={seller}>
<StoreAddressSection seller={seller} />
+ <StoreRegionsSection seller={seller} />
<StoreCompanyDetailsSection seller={seller} />
<StorePaymentDetailsSection seller={seller} />
</WidgetZone>
@@ -193,6 +195,7 @@ export const StoreDetailPage = Object.assign(Root, {
MainPaymentDetailsSection: StorePaymentDetailsSection,
MainCompanyDetailsSection: StoreCompanyDetailsSection,
SidebarAddressSection: StoreAddressSection,
+ SidebarRegionsSection: StoreRegionsSection,
SidebarMembersSection: StoreMembersSection,
Header: StoreDetailHeader,
HeaderTitle: StoreDetailTitle,
diff --git a/packages/admin/src/pages/stores/store-details/components/store-regions-section.tsx b/packages/admin/src/pages/stores/store-details/components/store-regions-section.tsx
new file mode 100644
index 000000000..340b92461
--- /dev/null
+++ b/packages/admin/src/pages/stores/store-details/components/store-regions-section.tsx
@@ -0,0 +1,151 @@
+import { MapPin, PlusMini, Trash } from "@medusajs/icons";
+import { Badge, Container, Heading, Text, toast, usePrompt } from "@medusajs/ui";
+import { useTranslation } from "react-i18next";
+
+import { InferClientOutput } from "@mercurjs/client";
+import { DisplayExtensionZone } from "@mercurjs/dashboard-shared";
+import { SellerRegionDTO } from "@mercurjs/types";
+import { sdk } from "@lib/client";
+
+import { ActionMenu } from "../../../../components/common/action-menu";
+import { IconAvatar } from "../../../../components/common/icon-avatar";
+import { useBatchSellerRegions } from "../../../../hooks/api/sellers";
+
+type Seller = InferClientOutput<typeof sdk.admin.sellers.$id.query>["seller"];
+
+type StoreRegionsSectionProps = {
+ seller: Seller;
+};
+
+export const StoreRegionsSection = ({ seller }: StoreRegionsSectionProps) => {
+ const { t } = useTranslation();
+ const regions = (seller.regions ?? []) as SellerRegionDTO[];
+
+ return (
+ <Container className="divide-y p-0" data-testid="store-regions-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div className="flex flex-col gap-y-1">
+ <Heading level="h2">{t("stores.regions.header")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("stores.regions.hint")}
+ </Text>
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("stores.regions.add"),
+ icon: <PlusMini />,
+ to: `/stores/${seller.id}/regions/add`,
+ permission: "sellers:edit",
+ },
+ ],
+ },
+ ]}
+ data-testid="store-regions-section-action-menu"
+ />
+ </div>
+ {regions.length > 0 ? (
+ regions.map((region) => (
+ <RegionRow
+ key={region.id}
+ sellerId={seller.id}
+ region={region}
+ isLast={regions.length === 1}
+ />
+ ))
+ ) : (
+ <div className="flex flex-col items-center gap-y-1 px-6 py-6">
+ <Text size="small" leading="compact" weight="plus">
+ {t("stores.regions.empty.title")}
+ </Text>
+ <Text size="small" className="text-ui-fg-muted">
+ {t("stores.regions.empty.message")}
+ </Text>
+ </div>
+ )}
+ <DisplayExtensionZone model="seller" zone="regions" data={seller} />
+ </Container>
+ );
+};
+
+const RegionRow = ({
+ sellerId,
+ region,
+ isLast,
+}: {
+ sellerId: string;
+ region: SellerRegionDTO;
+ isLast: boolean;
+}) => {
+ const { t } = useTranslation();
+ const prompt = usePrompt();
+ const { mutateAsync } = useBatchSellerRegions(sellerId);
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("stores.regions.removeWarning", { name: region.name }),
+ cancelText: t("actions.cancel"),
+ confirmText: t("actions.remove"),
+ });
+
+ if (!res) {
+ return;
+ }
+
+ await mutateAsync(
+ { remove: [region.id] },
+ {
+ onSuccess: () => {
+ toast.success(t("stores.regions.toast.removed"));
+ },
+ onError: (e) => {
+ toast.error(e.message);
+ },
+ },
+ );
+ };
+
+ return (
+ <div
+ className="flex items-center justify-between gap-x-4 px-6 py-4"
+ data-testid={`store-regions-section-row-${region.id}`}
+ >
+ <div className="flex items-center gap-x-3">
+ <IconAvatar>
+ <MapPin className="text-ui-fg-subtle" />
+ </IconAvatar>
+ <div className="flex flex-col">
+ <Text size="small" leading="compact" weight="plus">
+ {region.name}
+ </Text>
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {region.currency_code.toUpperCase()}
+ </Text>
+ </div>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <Badge size="2xsmall">{region.currency_code.toUpperCase()}</Badge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.remove"),
+ icon: <Trash />,
+ onClick: handleRemove,
+ permission: "sellers:edit",
+ disabled: isLast,
+ disabledTooltip: t("stores.regions.lastRegion"),
+ },
+ ],
+ },
+ ]}
+ data-testid={`store-regions-section-row-action-menu-${region.id}`}
+ />
+ </div>
+ </div>
+ );
+};
diff --git a/packages/admin/src/pages/stores/store-details/loader.ts b/packages/admin/src/pages/stores/store-details/loader.ts
index b3780427f..541732435 100644
--- a/packages/admin/src/pages/stores/store-details/loader.ts
+++ b/packages/admin/src/pages/stores/store-details/loader.ts
@@ -6,7 +6,7 @@ import { sdk } from "../../../lib/client"
import { queryClient } from "../../../lib/query-client"
export const STORE_DETAIL_FIELDS =
- "+address.*,+payment_details.*,+professional_details.*"
+ "+address.*,+payment_details.*,+professional_details.*,+regions.*"
const sellerDetailQuery = (id: string) => {
const query = getLinkQuery("seller", STORE_DETAIL_FIELDS)
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index c4cac0dc2..c3a1578c1 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -218,6 +218,7 @@
"/admin/refund-reasons/:id": "typeof import(\"@medusajs/medusa/api/admin/refund-reasons/[id]/route\")",
"/admin/regions": "typeof import(\"@medusajs/medusa/api/admin/regions/route\")",
"/admin/regions/:id": "typeof import(\"@medusajs/medusa/api/admin/regions/[id]/route\")",
+ "/admin/regions/:id/sellers": "typeof import(\"@mercurjs/core/api/admin/regions/[id]/sellers/route\")",
"/admin/reservations": "typeof import(\"@medusajs/medusa/api/admin/reservations/route\")",
"/admin/reservations/:id": "typeof import(\"@medusajs/medusa/api/admin/reservations/[id]/route\")",
"/admin/return-reasons": "typeof import(\"@medusajs/medusa/api/admin/return-reasons/route\")",
@@ -259,6 +260,7 @@
"/admin/sellers/:id/payment-details": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/payment-details/route\")",
"/admin/sellers/:id/products": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/products/route\")",
"/admin/sellers/:id/professional-details": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/professional-details/route\")",
+ "/admin/sellers/:id/regions": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/regions/route\")",
"/admin/sellers/:id/suspend": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/suspend/route\")",
"/admin/sellers/:id/terminate": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/terminate/route\")",
"/admin/sellers/:id/unsuspend": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/unsuspend/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 7694ad987..78cd99e4b 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -376,7 +376,9 @@ export type Routes = {
$id: typeof import("@medusajs/medusa/api/admin/refund-reasons/[id]/route");
};
regions: typeof import("@medusajs/medusa/api/admin/regions/route") & {
- $id: typeof import("@medusajs/medusa/api/admin/regions/[id]/route");
+ $id: typeof import("@medusajs/medusa/api/admin/regions/[id]/route") & {
+ sellers: typeof import("../src/api/admin/regions/[id]/sellers/route");
+ };
};
reservations: typeof import("@medusajs/medusa/api/admin/reservations/route") & {
$id: typeof import("@medusajs/medusa/api/admin/reservations/[id]/route");
@@ -430,6 +432,7 @@ export type Routes = {
terminate: typeof import("../src/api/admin/sellers/[id]/terminate/route");
unsuspend: typeof import("../src/api/admin/sellers/[id]/unsuspend/route");
unterminate: typeof import("../src/api/admin/sellers/[id]/unterminate/route");
+ regions: typeof import("../src/api/admin/sellers/[id]/regions/route");
};
statistics: typeof import("../src/api/admin/sellers/statistics/route");
};
diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.ts
index 6764a072a..94698e220 100644
--- a/packages/core/src/api/admin/middlewares.ts
+++ b/packages/core/src/api/admin/middlewares.ts
@@ -12,6 +12,7 @@ import { adminOffersMiddlewares } from "./offers/middlewares"
import { adminOfferConditionsMiddlewares } from "./offer-conditions/middlewares"
import { adminPayoutsMiddlewares } from "./payouts/middlewares"
import { adminSellersMiddlewares } from "./sellers/middlewares"
+import { adminRegionsMiddlewares } from "./regions/middlewares"
import { adminMembersMiddlewares } from "./members/middlewares"
import { adminCommissionRatesMiddlewares } from "./commission-rates/middlewares"
@@ -56,6 +57,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [
...adminOfferConditionsMiddlewares,
...adminPayoutsMiddlewares,
...adminSellersMiddlewares,
+ ...adminRegionsMiddlewares,
...adminMembersMiddlewares,
...adminCommissionRatesMiddlewares,
...adminProductsMiddlewares,
diff --git a/packages/core/src/api/admin/regions/[id]/sellers/route.ts b/packages/core/src/api/admin/regions/[id]/sellers/route.ts
new file mode 100644
index 000000000..116dbc24e
--- /dev/null
+++ b/packages/core/src/api/admin/regions/[id]/sellers/route.ts
@@ -0,0 +1,28 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { HttpTypes as MedusaHttpTypes } from "@medusajs/framework/types"
+import { HttpTypes } from "@mercurjs/types"
+
+import { linkSellerRegionsWorkflow } from "../../../../../workflows/seller"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<MedusaHttpTypes.AdminBatchLink>,
+ res: MedusaResponse<HttpTypes.AdminRegionSellersBatchResponse>
+) => {
+ const { add, remove } = req.validatedBody
+ const regionId = req.params.id
+
+ await linkSellerRegionsWorkflow(req.scope).run({
+ input: {
+ add: (add ?? []).map((seller_id) => ({ seller_id, region_id: regionId })),
+ remove: (remove ?? []).map((seller_id) => ({
+ seller_id,
+ region_id: regionId,
+ })),
+ },
+ })
+
+ res.status(200).json({ id: regionId, object: "region" })
+}
diff --git a/packages/core/src/api/admin/regions/middlewares.ts b/packages/core/src/api/admin/regions/middlewares.ts
new file mode 100644
index 000000000..dc7fa7c03
--- /dev/null
+++ b/packages/core/src/api/admin/regions/middlewares.ts
@@ -0,0 +1,16 @@
+import { MiddlewareRoute } from "@medusajs/framework/http"
+import { validateAndTransformBody } from "@medusajs/framework"
+import { createLinkBody } from "@medusajs/medusa/api/utils/validators"
+
+import { requirePermission } from "../../utils"
+
+export const adminRegionsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["POST"],
+ matcher: "/admin/regions/:id/sellers",
+ middlewares: [
+ requirePermission("regions", "edit"),
+ validateAndTransformBody(createLinkBody()),
+ ],
+ },
+]
diff --git a/packages/core/src/api/admin/sellers/[id]/regions/route.ts b/packages/core/src/api/admin/sellers/[id]/regions/route.ts
new file mode 100644
index 000000000..d56f668c6
--- /dev/null
+++ b/packages/core/src/api/admin/sellers/[id]/regions/route.ts
@@ -0,0 +1,28 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { HttpTypes as MedusaHttpTypes } from "@medusajs/framework/types"
+import { HttpTypes } from "@mercurjs/types"
+
+import { linkSellerRegionsWorkflow } from "../../../../../workflows/seller"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<MedusaHttpTypes.AdminBatchLink>,
+ res: MedusaResponse<HttpTypes.AdminSellerRegionsBatchResponse>
+) => {
+ const { add, remove } = req.validatedBody
+ const sellerId = req.params.id
+
+ await linkSellerRegionsWorkflow(req.scope).run({
+ input: {
+ add: (add ?? []).map((region_id) => ({ seller_id: sellerId, region_id })),
+ remove: (remove ?? []).map((region_id) => ({
+ seller_id: sellerId,
+ region_id,
+ })),
+ },
+ })
+
+ res.status(200).json({ id: sellerId, object: "seller" })
+}
diff --git a/packages/core/src/api/admin/sellers/middlewares.ts b/packages/core/src/api/admin/sellers/middlewares.ts
index 99decf0d0..9b8a897d1 100644
--- a/packages/core/src/api/admin/sellers/middlewares.ts
+++ b/packages/core/src/api/admin/sellers/middlewares.ts
@@ -5,6 +5,8 @@ import {
validateAndTransformQuery,
} from "@medusajs/framework"
import { z } from "zod"
+import { createLinkBody } from "@medusajs/medusa/api/utils/validators"
+import { maybeApplyLinkFilter } from "@medusajs/framework"
import {
adminSellerQueryConfig,
@@ -50,6 +52,19 @@ export const adminSellersMiddlewares: MiddlewareRoute[] = [
AdminGetSellersParams,
adminSellerQueryConfig.list
),
+ maybeApplyLinkFilter({
+ entryPoint: "region_seller",
+ resourceId: "seller_id",
+ filterableField: "region_id",
+ }),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/sellers/:id/regions",
+ middlewares: [
+ requirePermission("sellers", "edit"),
+ validateAndTransformBody(createLinkBody()),
],
},
{
diff --git a/packages/core/src/api/admin/sellers/query-config.ts b/packages/core/src/api/admin/sellers/query-config.ts
index 31366e24a..22de5e76d 100644
--- a/packages/core/src/api/admin/sellers/query-config.ts
+++ b/packages/core/src/api/admin/sellers/query-config.ts
@@ -37,6 +37,9 @@ export const adminSellerFields = [
export const adminSellerRetrieveFields = [
...adminSellerFields,
"*members",
+ "regions.id",
+ "regions.name",
+ "regions.currency_code",
]
export const adminSellerQueryConfig = {
diff --git a/packages/core/src/api/admin/sellers/validators.ts b/packages/core/src/api/admin/sellers/validators.ts
index 652848bca..36325f949 100644
--- a/packages/core/src/api/admin/sellers/validators.ts
+++ b/packages/core/src/api/admin/sellers/validators.ts
@@ -24,6 +24,7 @@ export const AdminGetSellersParams = createFindParams({
email: z.string().optional(),
status: z.union([z.string(), z.array(z.string())]).optional(),
is_premium: booleanString().optional(),
+ region_id: z.union([z.string(), z.array(z.string())]).optional(),
created_at: createOperatorMap().optional(),
updated_at: createOperatorMap().optional(),
})
@@ -72,6 +73,7 @@ export const CreateSeller = z.object({
member: z.object({
email: z.string().email(),
}),
+ region_ids: z.array(z.string()).optional(),
})
export const AdminCreateSeller = WithAdditionalData(CreateSeller)
diff --git a/packages/core/src/api/vendor/offers/[id]/route.ts b/packages/core/src/api/vendor/offers/[id]/route.ts
index 26049f6be..7ef7f7de0 100644
--- a/packages/core/src/api/vendor/offers/[id]/route.ts
+++ b/packages/core/src/api/vendor/offers/[id]/route.ts
@@ -9,6 +9,7 @@ import {
updateOffersWorkflow,
} from "../../../../workflows/offer"
import { refetchOffer, validateSellerOffer } from "../helpers"
+import { validateSellerRegionPrices } from "../../regions/helpers"
import { VendorUpdateOfferType } from "../validators"
export const GET = async (
@@ -40,6 +41,14 @@ export const POST = async (
const { additional_data, ...update } = req.validatedBody
+ if (update.prices) {
+ await validateSellerRegionPrices(
+ req.scope,
+ req.seller_context!.seller_id,
+ update.prices
+ )
+ }
+
await updateOffersWorkflow(req.scope).run({
input: {
offers: [{ id, ...update }],
diff --git a/packages/core/src/api/vendor/offers/batch/route.ts b/packages/core/src/api/vendor/offers/batch/route.ts
index 8552586ac..bdb657c3b 100644
--- a/packages/core/src/api/vendor/offers/batch/route.ts
+++ b/packages/core/src/api/vendor/offers/batch/route.ts
@@ -7,6 +7,7 @@ import { CreateOfferDTO } from "@mercurjs/types"
import { createOffersWorkflow } from "../../../../workflows/offer"
import { validateSellerStockLocations } from "../../stock-locations/helpers"
+import { validateSellerRegionPrices } from "../../regions/helpers"
import { VendorCreateOffersBatchType } from "../validators"
export const POST = async (
@@ -42,6 +43,12 @@ export const POST = async (
)
)
+ await validateSellerRegionPrices(
+ req.scope,
+ sellerId,
+ offers.flatMap((offer) => offer.prices ?? [])
+ )
+
const { result } = await createOffersWorkflow(req.scope).run({
input: { offers, additional_data },
})
diff --git a/packages/core/src/api/vendor/offers/route.ts b/packages/core/src/api/vendor/offers/route.ts
index 91aebdfca..6d24de785 100644
--- a/packages/core/src/api/vendor/offers/route.ts
+++ b/packages/core/src/api/vendor/offers/route.ts
@@ -9,6 +9,7 @@ import {
import { createOffersWorkflow } from "../../../workflows/offer"
import { refetchOffer } from "./helpers"
import { validateSellerStockLocations } from "../stock-locations/helpers"
+import { validateSellerRegionPrices } from "../regions/helpers"
import { VendorCreateOfferType, VendorGetOffersParamsType } from "./validators"
export const GET = async (
@@ -49,6 +50,8 @@ export const POST = async (
)
)
+ await validateSellerRegionPrices(req.scope, sellerId, offerData.prices)
+
const { result } = await createOffersWorkflow(req.scope).run({
input: {
offers: [
diff --git a/packages/core/src/api/vendor/regions/[id]/route.ts b/packages/core/src/api/vendor/regions/[id]/route.ts
index d49575ee9..d3aed623c 100644
--- a/packages/core/src/api/vendor/regions/[id]/route.ts
+++ b/packages/core/src/api/vendor/regions/[id]/route.ts
@@ -8,12 +8,21 @@ import {
} from "@medusajs/framework/utils"
import { HttpTypes } from "@medusajs/framework/types"
+import { validateSellerRegions } from "../helpers"
+
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse<HttpTypes.AdminRegionResponse>
) => {
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ await validateSellerRegions(
+ req.scope,
+ req.seller_context!.seller_id,
+ [req.params.id],
+ MedusaError.Types.NOT_FOUND
+ )
+
const {
data: [region],
} = await query.graph({
diff --git a/packages/core/src/api/vendor/regions/helpers.ts b/packages/core/src/api/vendor/regions/helpers.ts
new file mode 100644
index 000000000..c0242a16b
--- /dev/null
+++ b/packages/core/src/api/vendor/regions/helpers.ts
@@ -0,0 +1,159 @@
+import { MedusaContainer } from "@medusajs/framework"
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+} from "@medusajs/framework/utils"
+
+export const listSellerRegionIds = async (
+ scope: MedusaContainer,
+ sellerId: string
+): Promise<string[]> => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: links } = await query.graph({
+ entity: "region_seller",
+ filters: { seller_id: sellerId },
+ fields: ["region_id"],
+ })
+
+ return links.map((link) => (link as { region_id: string }).region_id)
+}
+
+export const listSellerCurrencyCodes = async (
+ scope: MedusaContainer,
+ sellerId: string
+): Promise<string[]> => {
+ const regionIds = await listSellerRegionIds(scope, sellerId)
+ if (!regionIds.length) {
+ return []
+ }
+
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: regions } = await query.graph({
+ entity: "region",
+ filters: { id: regionIds },
+ fields: ["currency_code"],
+ })
+
+ return Array.from(
+ new Set(regions.map((r) => (r.currency_code as string).toLowerCase()))
+ )
+}
+
+export const validateSellerRegions = async (
+ scope: MedusaContainer,
+ sellerId: string,
+ regionIds: string[],
+ errorType: string = MedusaError.Types.INVALID_DATA
+) => {
+ const ids = Array.from(new Set(regionIds))
+ if (!ids.length) {
+ return
+ }
+
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: links } = await query.graph({
+ entity: "region_seller",
+ filters: {
+ seller_id: sellerId,
+ region_id: ids,
+ },
+ fields: ["region_id"],
+ })
+
+ const assigned = new Set(
+ links.map((link) => (link as { region_id?: string }).region_id)
+ )
+ const missing = ids.find((id) => !assigned.has(id))
+
+ if (missing) {
+ throw new MedusaError(
+ errorType,
+ errorType === MedusaError.Types.NOT_FOUND
+ ? `Region with id: ${missing} was not found`
+ : `Region with id: ${missing} is not assigned to this seller`
+ )
+ }
+}
+
+type RegionScopedPrice = {
+ currency_code?: string
+ region_id?: string
+ rules?: unknown
+}
+
+const regionIdFromRules = (rules: unknown): string | undefined => {
+ if (!rules || typeof rules !== "object" || Array.isArray(rules)) {
+ return undefined
+ }
+ const value = (rules as Record<string, unknown>).region_id
+ return typeof value === "string" ? value : undefined
+}
+
+type RegionPrice = { region_id: string; currency_code?: string }
+
+export const validateSellerRegionPrices = async (
+ scope: MedusaContainer,
+ sellerId: string,
+ prices: RegionScopedPrice[]
+) => {
+ const regionPrices: RegionPrice[] = []
+ const currencyCodes = new Set<string>()
+ for (const price of prices) {
+ const regionId = price.region_id ?? regionIdFromRules(price.rules)
+ if (regionId) {
+ regionPrices.push({ region_id: regionId, currency_code: price.currency_code })
+ } else if (price.currency_code) {
+ currencyCodes.add(price.currency_code.toLowerCase())
+ }
+ }
+
+ if (currencyCodes.size) {
+ const unlocked = new Set(await listSellerCurrencyCodes(scope, sellerId))
+ const locked = Array.from(currencyCodes).find((code) => !unlocked.has(code))
+ if (locked) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Currency ${locked} is not available to this seller. Assign a region using it first`
+ )
+ }
+ }
+
+ if (!regionPrices.length) {
+ return
+ }
+
+ const regionIds = Array.from(new Set(regionPrices.map((p) => p.region_id)))
+
+ await validateSellerRegions(scope, sellerId, regionIds)
+
+ const withCurrency = regionPrices.filter((p) => p.currency_code)
+ if (!withCurrency.length) {
+ return
+ }
+
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: regions } = await query.graph({
+ entity: "region",
+ filters: { id: regionIds },
+ fields: ["id", "currency_code"],
+ })
+
+ const currencyByRegion = new Map(
+ regions.map((r) => [r.id, r.currency_code as string])
+ )
+
+ const mismatch = withCurrency.find(
+ (p) =>
+ currencyByRegion.get(p.region_id)?.toLowerCase() !==
+ p.currency_code!.toLowerCase()
+ )
+
+ if (mismatch) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Price currency ${mismatch.currency_code} does not match the currency of region ${mismatch.region_id}`
+ )
+ }
+}
diff --git a/packages/core/src/api/vendor/regions/route.ts b/packages/core/src/api/vendor/regions/route.ts
index c24055007..8f3d79b39 100644
--- a/packages/core/src/api/vendor/regions/route.ts
+++ b/packages/core/src/api/vendor/regions/route.ts
@@ -5,16 +5,44 @@ import {
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { HttpTypes } from "@medusajs/framework/types"
+import { listSellerRegionIds } from "./helpers"
+
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse<HttpTypes.AdminRegionListResponse>
) => {
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const assignedIds = await listSellerRegionIds(
+ req.scope,
+ req.seller_context!.seller_id
+ )
+
+ const requested = req.filterableFields.id as string | string[] | undefined
+ const requestedIds = requested
+ ? Array.isArray(requested)
+ ? requested
+ : [requested]
+ : null
+
+ const ids = requestedIds
+ ? assignedIds.filter((id) => requestedIds.includes(id))
+ : assignedIds
+
+ if (!ids.length) {
+ res.json({
+ regions: [],
+ count: 0,
+ offset: req.queryConfig.pagination?.skip ?? 0,
+ limit: req.queryConfig.pagination?.take ?? 0,
+ })
+ return
+ }
+
const { data: regions, metadata } = await query.graph({
entity: "region",
fields: req.queryConfig.fields,
- filters: req.filterableFields,
+ filters: { ...req.filterableFields, id: ids },
pagination: req.queryConfig.pagination,
})
diff --git a/packages/core/src/api/vendor/shipping-options/[id]/route.ts b/packages/core/src/api/vendor/shipping-options/[id]/route.ts
index 2b5894f6a..56b14d5c6 100644
--- a/packages/core/src/api/vendor/shipping-options/[id]/route.ts
+++ b/packages/core/src/api/vendor/shipping-options/[id]/route.ts
@@ -11,6 +11,7 @@ import { MedusaError } from "@medusajs/framework/utils"
import { HttpTypes } from "@mercurjs/types"
import { refetchShippingOption, validateSellerShippingOption } from "../helpers"
+import { validateSellerRegionPrices } from "../../regions/helpers"
import { VendorUpdateShippingOptionType } from "../validators"
export const GET = async (
@@ -47,6 +48,12 @@ export const POST = async (
const shippingOptionPayload = req.validatedBody
+ await validateSellerRegionPrices(
+ req.scope,
+ sellerId,
+ shippingOptionPayload.prices ?? []
+ )
+
const workflow = updateShippingOptionsWorkflow(req.scope)
const workflowInput: FulfillmentWorkflow.UpdateShippingOptionsWorkflowInput =
diff --git a/packages/core/src/api/vendor/shipping-options/route.ts b/packages/core/src/api/vendor/shipping-options/route.ts
index 9455566fb..29082f034 100644
--- a/packages/core/src/api/vendor/shipping-options/route.ts
+++ b/packages/core/src/api/vendor/shipping-options/route.ts
@@ -7,6 +7,7 @@ import { HttpTypes } from "@mercurjs/types"
import { createSellerShippingOptionsWorkflow } from "../../../workflows/shipping-option"
import { refetchShippingOption } from "./helpers"
+import { validateSellerRegionPrices } from "../regions/helpers"
import { VendorCreateShippingOptionType } from "./validators"
export const GET = async (
@@ -36,6 +37,12 @@ export const POST = async (
) => {
const sellerId = req.seller_context!.seller_id
+ await validateSellerRegionPrices(
+ req.scope,
+ sellerId,
+ req.validatedBody.prices ?? []
+ )
+
const { result } = await createSellerShippingOptionsWorkflow(req.scope).run({
input: {
seller_id: sellerId,
diff --git a/packages/core/src/links/region-seller-link.ts b/packages/core/src/links/region-seller-link.ts
new file mode 100644
index 000000000..911c220ca
--- /dev/null
+++ b/packages/core/src/links/region-seller-link.ts
@@ -0,0 +1,19 @@
+import { defineLink } from "@medusajs/framework/utils"
+import RegionModule from "@medusajs/medusa/region"
+import SellerModule from "../modules/seller"
+
+export default defineLink(
+ {
+ linkable: RegionModule.linkable.region,
+ isList: true,
+ },
+ {
+ linkable: SellerModule.linkable.seller,
+ isList: true,
+ },
+ {
+ database: {
+ table: "region_seller",
+ },
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/associate-sellers-with-regions.ts b/packages/core/src/workflows/seller/steps/associate-sellers-with-regions.ts
new file mode 100644
index 000000000..77935be4a
--- /dev/null
+++ b/packages/core/src/workflows/seller/steps/associate-sellers-with-regions.ts
@@ -0,0 +1,43 @@
+import { Link } from "@medusajs/framework/modules-sdk"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { MercurModules } from "@mercurjs/types"
+
+export type SellerRegionLink = {
+ region_id: string
+ seller_id: string
+}
+
+export interface AssociateSellersWithRegionsStepInput {
+ links: SellerRegionLink[]
+}
+
+export const associateSellersWithRegionsStepId =
+ "associate-sellers-with-regions"
+
+export const associateSellersWithRegionsStep = createStep(
+ associateSellersWithRegionsStepId,
+ async (input: AssociateSellersWithRegionsStepInput, { container }) => {
+ if (!input.links?.length) {
+ return new StepResponse([], [])
+ }
+
+ const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
+
+ const links = input.links.map((link) => ({
+ [Modules.REGION]: { region_id: link.region_id },
+ [MercurModules.SELLER]: { seller_id: link.seller_id },
+ }))
+
+ const created = await remoteLink.create(links)
+ return new StepResponse(created, links)
+ },
+ async (links, { container }) => {
+ if (!links?.length) {
+ return
+ }
+
+ const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
+ await remoteLink.dismiss(links)
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/detach-sellers-from-regions.ts b/packages/core/src/workflows/seller/steps/detach-sellers-from-regions.ts
new file mode 100644
index 000000000..fc0bf44f9
--- /dev/null
+++ b/packages/core/src/workflows/seller/steps/detach-sellers-from-regions.ts
@@ -0,0 +1,39 @@
+import { Link } from "@medusajs/framework/modules-sdk"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { MercurModules } from "@mercurjs/types"
+
+import { SellerRegionLink } from "./associate-sellers-with-regions"
+
+export interface DetachSellersFromRegionsStepInput {
+ links: SellerRegionLink[]
+}
+
+export const detachSellersFromRegionsStepId = "detach-sellers-from-regions"
+
+export const detachSellersFromRegionsStep = createStep(
+ detachSellersFromRegionsStepId,
+ async (input: DetachSellersFromRegionsStepInput, { container }) => {
+ if (!input.links?.length) {
+ return new StepResponse(void 0, [])
+ }
+
+ const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
+
+ const links = input.links.map((link) => ({
+ [Modules.REGION]: { region_id: link.region_id },
+ [MercurModules.SELLER]: { seller_id: link.seller_id },
+ }))
+
+ await remoteLink.dismiss(links)
+ return new StepResponse(void 0, links)
+ },
+ async (links, { container }) => {
+ if (!links?.length) {
+ return
+ }
+
+ const remoteLink: Link = container.resolve(ContainerRegistrationKeys.LINK)
+ await remoteLink.create(links)
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/index.ts b/packages/core/src/workflows/seller/steps/index.ts
index 2b18ce6f8..be74a4f6e 100644
--- a/packages/core/src/workflows/seller/steps/index.ts
+++ b/packages/core/src/workflows/seller/steps/index.ts
@@ -22,3 +22,8 @@ export * from "./update-seller-address"
export * from "./update-seller-professional-details"
export * from "./delete-seller-professional-details"
export * from "./update-payment-details"
+export * from "./associate-sellers-with-regions"
+export * from "./detach-sellers-from-regions"
+export * from "./resolve-seller-region-ids"
+export * from "./validate-seller-region-links"
+export * from "./validate-sellers-keep-regions"
diff --git a/packages/core/src/workflows/seller/steps/resolve-seller-region-ids.ts b/packages/core/src/workflows/seller/steps/resolve-seller-region-ids.ts
new file mode 100644
index 000000000..89e1125ef
--- /dev/null
+++ b/packages/core/src/workflows/seller/steps/resolve-seller-region-ids.ts
@@ -0,0 +1,44 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+
+import { SellerRegionLink } from "./associate-sellers-with-regions"
+
+export interface ResolveSellerRegionIdsStepInput {
+ requests: {
+ seller_id: string
+ region_ids?: string[] | null
+ }[]
+}
+
+export const resolveSellerRegionIdsStepId = "resolve-seller-region-ids"
+
+export const resolveSellerRegionIdsStep = createStep(
+ resolveSellerRegionIdsStepId,
+ async (input: ResolveSellerRegionIdsStepInput, { container }) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const {
+ data: [store],
+ } = await query.graph({
+ entity: "store",
+ fields: ["default_region_id"],
+ })
+
+ const defaultRegionId =
+ (store as { default_region_id?: string | null } | undefined)
+ ?.default_region_id ?? null
+
+ const links: SellerRegionLink[] = input.requests.flatMap((request) => {
+ const regionIds = [
+ ...(defaultRegionId ? [defaultRegionId] : []),
+ ...(request.region_ids ?? []),
+ ]
+
+ return Array.from(new Set(regionIds)).map((region_id) => ({
+ seller_id: request.seller_id,
+ region_id,
+ }))
+ })
+
+ return new StepResponse(links)
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/validate-seller-region-links.ts b/packages/core/src/workflows/seller/steps/validate-seller-region-links.ts
new file mode 100644
index 000000000..f98157a54
--- /dev/null
+++ b/packages/core/src/workflows/seller/steps/validate-seller-region-links.ts
@@ -0,0 +1,58 @@
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+} from "@medusajs/framework/utils"
+import { createStep } from "@medusajs/framework/workflows-sdk"
+
+import { SellerRegionLink } from "./associate-sellers-with-regions"
+
+export interface ValidateSellerRegionLinksStepInput {
+ links: SellerRegionLink[]
+}
+
+export const validateSellerRegionLinksStepId = "validate-seller-region-links"
+
+export const validateSellerRegionLinksStep = createStep(
+ validateSellerRegionLinksStepId,
+ async (input: ValidateSellerRegionLinksStepInput, { container }) => {
+ if (!input.links.length) {
+ return
+ }
+
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ const regionIds = Array.from(new Set(input.links.map((l) => l.region_id)))
+ const sellerIds = Array.from(new Set(input.links.map((l) => l.seller_id)))
+
+ const [{ data: regions }, { data: sellers }] = await Promise.all([
+ query.graph({
+ entity: "region",
+ fields: ["id"],
+ filters: { id: regionIds },
+ }),
+ query.graph({
+ entity: "seller",
+ fields: ["id"],
+ filters: { id: sellerIds },
+ }),
+ ])
+
+ const foundRegions = new Set(regions.map((r) => r.id))
+ const missingRegion = regionIds.find((id) => !foundRegions.has(id))
+ if (missingRegion) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Region with id: ${missingRegion} was not found`
+ )
+ }
+
+ const foundSellers = new Set(sellers.map((s) => s.id))
+ const missingSeller = sellerIds.find((id) => !foundSellers.has(id))
+ if (missingSeller) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Seller with id: ${missingSeller} was not found`
+ )
+ }
+ }
+)
diff --git a/packages/core/src/workflows/seller/steps/validate-sellers-keep-regions.ts b/packages/core/src/workflows/seller/steps/validate-sellers-keep-regions.ts
new file mode 100644
index 000000000..8460805f2
--- /dev/null
+++ b/packages/core/src/workflows/seller/steps/validate-sellers-keep-regions.ts
@@ -0,0 +1,52 @@
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+} from "@medusajs/framework/utils"
+import { createStep } from "@medusajs/framework/workflows-sdk"
+
+import { SellerRegionLink } from "./associate-sellers-with-regions"
+
+export interface ValidateSellersKeepRegionsStepInput {
+ add: SellerRegionLink[]
+ remove: SellerRegionLink[]
+}
+
+export const validateSellersKeepRegionsStepId = "validate-sellers-keep-regions"
+
+export const validateSellersKeepRegionsStep = createStep(
+ validateSellersKeepRegionsStepId,
+ async (input: ValidateSellersKeepRegionsStepInput, { container }) => {
+ const sellerIds = Array.from(new Set(input.remove.map((l) => l.seller_id)))
+ if (!sellerIds.length) {
+ return
+ }
+
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const { data: links } = await query.graph({
+ entity: "region_seller",
+ filters: { seller_id: sellerIds },
+ fields: ["seller_id", "region_id"],
+ })
+
+ for (const sellerId of sellerIds) {
+ const remaining = new Set(
+ links
+ .filter((l) => l.seller_id === sellerId)
+ .map((l) => l.region_id as string)
+ )
+ input.add
+ .filter((l) => l.seller_id === sellerId)
+ .forEach((l) => remaining.add(l.region_id))
+ input.remove
+ .filter((l) => l.seller_id === sellerId)
+ .forEach((l) => remaining.delete(l.region_id))
+
+ if (!remaining.size) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Seller with id: ${sellerId} must stay assigned to at least one region`
+ )
+ }
+ }
+ }
+)
diff --git a/packages/core/src/workflows/seller/workflows/create-seller-account.ts b/packages/core/src/workflows/seller/workflows/create-seller-account.ts
index 3dfc2199c..03e5177ea 100644
--- a/packages/core/src/workflows/seller/workflows/create-seller-account.ts
+++ b/packages/core/src/workflows/seller/workflows/create-seller-account.ts
@@ -20,9 +20,12 @@ import {
import { AdditionalData } from "@medusajs/framework/types"
import {
+ associateSellersWithRegionsStep,
createSellersStep,
upsertMembersStep,
createSellerMembersStep,
+ resolveSellerRegionIdsStep,
+ validateSellerRegionLinksStep,
} from "../steps"
import { SellerWorkflowEvents } from "../../events"
import { updateSellerAddressWorkflow } from "./update-seller-address"
@@ -41,6 +44,7 @@ type CreateSellerAccountWorkflowInput = {
address?: UpdateSellerAddressDTO
professional_details?: UpdateProfessionalDetailsDTO
payment_details?: UpdatePaymentDetailsDTO
+ region_ids?: string[]
} & AdditionalData
export const createSellerAccountWorkflow = createWorkflow(
@@ -57,6 +61,15 @@ export const createSellerAccountWorkflow = createWorkflow(
const sellers = createSellersStep(sellerData)
const seller = transform({ sellers }, ({ sellers }) => sellers[0])
+ const regionLinks = resolveSellerRegionIdsStep({
+ requests: transform({ seller, input }, ({ seller, input }) => [
+ { seller_id: seller.id, region_ids: input.region_ids },
+ ]),
+ })
+
+ validateSellerRegionLinksStep({ links: regionLinks })
+ associateSellersWithRegionsStep({ links: regionLinks })
+
const newMember = when('no-existing-member', input, ({ member_id }) => !member_id).then(() => {
const members = upsertMembersStep(
transform(input, ({ member_email, first_name, last_name }) => [
diff --git a/packages/core/src/workflows/seller/workflows/create-sellers.ts b/packages/core/src/workflows/seller/workflows/create-sellers.ts
index 59cbe3471..972e64e5e 100644
--- a/packages/core/src/workflows/seller/workflows/create-sellers.ts
+++ b/packages/core/src/workflows/seller/workflows/create-sellers.ts
@@ -15,14 +15,22 @@ import {
} from "@mercurjs/types"
import { AdditionalData } from "@medusajs/framework/types"
-import { createSellersStep } from "../steps"
+import {
+ associateSellersWithRegionsStep,
+ createSellersStep,
+ resolveSellerRegionIdsStep,
+ validateSellerRegionLinksStep,
+} from "../steps"
import { SellerWorkflowEvents } from "../../events"
import { createMemberInvitesWorkflow } from "./create-member-invites"
export const createSellersWorkflowId = "create-sellers"
export type CreateSellersWorkflowInput = {
- sellers: (CreateSellerDTO & { member: { email: string } })[]
+ sellers: (CreateSellerDTO & {
+ member: { email: string }
+ region_ids?: string[]
+ })[]
} & AdditionalData
export type CreateSellersWorkflowHooks = [
@@ -50,13 +58,25 @@ export const createSellersWorkflow: ReturnWorkflow<
const sellers = createSellersStep(
transform(input, ({ sellers }) =>
- sellers.map(({ member: _member, ...seller }) => ({
+ sellers.map(({ member: _member, region_ids: _regionIds, ...seller }) => ({
...seller,
status: seller.status ?? SellerStatus.PENDING_APPROVAL,
}))
)
)
+ const regionLinks = resolveSellerRegionIdsStep({
+ requests: transform({ sellers, input }, ({ sellers, input }) =>
+ sellers.map((seller, i) => ({
+ seller_id: seller.id,
+ region_ids: input.sellers[i].region_ids,
+ }))
+ ),
+ })
+
+ validateSellerRegionLinksStep({ links: regionLinks })
+ associateSellersWithRegionsStep({ links: regionLinks })
+
createMemberInvitesWorkflow.runAsStep({
input: transform(
{ sellers, input },
diff --git a/packages/core/src/workflows/seller/workflows/index.ts b/packages/core/src/workflows/seller/workflows/index.ts
index 0277c07e4..638f83ddd 100644
--- a/packages/core/src/workflows/seller/workflows/index.ts
+++ b/packages/core/src/workflows/seller/workflows/index.ts
@@ -20,3 +20,4 @@ export * from "./update-seller-address"
export * from "./update-seller-professional-details"
export * from "./delete-seller-professional-details"
export * from "./create-seller-account"
+export * from "./link-seller-regions"
diff --git a/packages/core/src/workflows/seller/workflows/link-seller-regions.ts b/packages/core/src/workflows/seller/workflows/link-seller-regions.ts
new file mode 100644
index 000000000..859ca851a
--- /dev/null
+++ b/packages/core/src/workflows/seller/workflows/link-seller-regions.ts
@@ -0,0 +1,33 @@
+import {
+ createWorkflow,
+ transform,
+ WorkflowData,
+} from "@medusajs/framework/workflows-sdk"
+
+import {
+ associateSellersWithRegionsStep,
+ detachSellersFromRegionsStep,
+ SellerRegionLink,
+ validateSellerRegionLinksStep,
+ validateSellersKeepRegionsStep,
+} from "../steps"
+
+export type LinkSellerRegionsWorkflowInput = {
+ add?: SellerRegionLink[]
+ remove?: SellerRegionLink[]
+}
+
+export const linkSellerRegionsWorkflowId = "link-seller-regions"
+
+export const linkSellerRegionsWorkflow = createWorkflow(
+ linkSellerRegionsWorkflowId,
+ (input: WorkflowData<LinkSellerRegionsWorkflowInput>): WorkflowData<void> => {
+ const toAdd = transform({ input }, ({ input }) => input.add ?? [])
+ const toRemove = transform({ input }, ({ input }) => input.remove ?? [])
+
+ validateSellerRegionLinksStep({ links: toAdd })
+ validateSellersKeepRegionsStep({ add: toAdd, remove: toRemove })
+ associateSellersWithRegionsStep({ links: toAdd })
+ detachSellersFromRegionsStep({ links: toRemove })
+ }
+)
diff --git a/packages/types/src/http/seller.ts b/packages/types/src/http/seller.ts
index 7054d0c9b..e36378434 100644
--- a/packages/types/src/http/seller.ts
+++ b/packages/types/src/http/seller.ts
@@ -84,3 +84,13 @@ export type AdminSellerListResponse = PaginatedResponse<{
export interface AdminSellerStatisticsResponse {
statistics: SellerStatisticsOutput
}
+
+export interface AdminSellerRegionsBatchResponse {
+ id: string
+ object: "seller"
+}
+
+export interface AdminRegionSellersBatchResponse {
+ id: string
+ object: "region"
+}
diff --git a/packages/types/src/seller/common.ts b/packages/types/src/seller/common.ts
index b4e91437d..35a5244bc 100644
--- a/packages/types/src/seller/common.ts
+++ b/packages/types/src/seller/common.ts
@@ -181,6 +181,12 @@ export interface CreateMemberInviteDTO {
metadata?: Record<string, unknown> | null
}
+export interface SellerRegionDTO {
+ id: string
+ name: string
+ currency_code: string
+}
+
export interface SellerDTO {
id: string
name: string
@@ -206,6 +212,7 @@ export interface SellerDTO {
address: SellerAddressDTO | null
payment_details: PaymentDetailsDTO | null
members: MemberDTO[]
+ regions?: SellerRegionDTO[]
metadata: Record<string, unknown> | null
created_at: Date
updated_at: Date
diff --git a/packages/vendor/src/i18n/translations/$schema.json b/packages/vendor/src/i18n/translations/$schema.json
index d62e984eb..bc382c1fb 100644
--- a/packages/vendor/src/i18n/translations/$schema.json
+++ b/packages/vendor/src/i18n/translations/$schema.json
@@ -5335,6 +5335,9 @@
},
"duplicateBatchEntry": {
"type": "string"
+ },
+ "noCurrencies": {
+ "type": "string"
}
},
"required": [
@@ -5347,9 +5350,13 @@
"noPublishableRows",
"priceRequired",
"noPricedRows",
- "duplicateBatchEntry"
+ "duplicateBatchEntry",
+ "noCurrencies"
],
"additionalProperties": false
+ },
+ "regionPrices": {
+ "type": "string"
}
},
"required": [
@@ -5369,7 +5376,8 @@
"stockStatus",
"empty",
"filtered",
- "validation"
+ "validation",
+ "regionPrices"
],
"additionalProperties": false
},
diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.json
index 0b677d41d..7bf8fbcf9 100644
--- a/packages/vendor/src/i18n/translations/en.json
+++ b/packages/vendor/src/i18n/translations/en.json
@@ -1303,8 +1303,10 @@
"noPublishableRows": "Add a SKU, enable a stock location, or set a price to publish.",
"priceRequired": "Enter a price to publish this row, or clear its stock and shipping profile to skip it.",
"noPricedRows": "Enter a price for at least one variant. Variants without a price are skipped.",
- "duplicateBatchEntry": "An inventory item can only appear in one bucket (create, update, or delete)."
- }
+ "duplicateBatchEntry": "An inventory item can only appear in one bucket (create, update, or delete).",
+ "noCurrencies": "No regions are assigned to your store yet, so no currencies are available for pricing."
+ },
+ "regionPrices": "Region prices"
},
"giftCards": {
"domain": "Gift Cards",
diff --git a/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx b/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
index 50c87135e..cf7915d16 100644
--- a/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
+++ b/packages/vendor/src/pages/offers/[id]/_components/offer-pricing-section.tsx
@@ -5,29 +5,38 @@ import { useTranslation } from "react-i18next"
import { ActionMenu } from "../../../../components/common/action-menu"
import { NoRecords } from "../../../../components/common/empty-table-content"
-import { DisplayExtensionZone } from "@mercurjs/dashboard-shared"
+import { DisplayExtensionZone, useCan } from "@mercurjs/dashboard-shared"
+import { useRegions } from "../../../../hooks/api/regions"
import { getLocaleAmount } from "../../../../lib/money-amount-helpers"
+import { getPriceRegionId, isBasePrice } from "../../common/region-prices"
import { OfferDetail, OfferPrice } from "../../common/types"
type Props = { offer: OfferDetail }
const PAGE_STEP = 3
-const isBaseRow = (price: OfferPrice) => {
- if (!price) return false
- const rules = price.price_rules ?? []
- const extraRules = rules.filter((r) => r.attribute !== "offer_id")
- return extraRules.length === 0
-}
-
export const OfferPricingSection = ({ offer }: Props) => {
const { t } = useTranslation()
+ const canViewRegions = useCan("regions")
+ const { regions } = useRegions(
+ { fields: "id,name", limit: 999 },
+ { enabled: canViewRegions },
+ )
+
+ const regionName = (regionId: string) =>
+ regions?.find((r) => r.id === regionId)?.name ?? regionId
const prices = (offer.prices ?? [])
- .filter((p): p is OfferPrice => Boolean(p) && isBaseRow(p))
+ .filter((p): p is OfferPrice => isBasePrice(p))
.sort((a, b) => (a.currency_code ?? "").localeCompare(b.currency_code ?? ""))
+ const regionPrices = (offer.prices ?? [])
+ .filter((p): p is OfferPrice => Boolean(p) && getPriceRegionId(p) !== null)
+ .sort((a, b) =>
+ regionName(getPriceRegionId(a)!).localeCompare(regionName(getPriceRegionId(b)!)),
+ )
+
const hasPrices = prices.length > 0
const [pageSize, setPageSize] = useState(PAGE_STEP)
const displayPrices = prices.slice(0, pageSize)
@@ -67,6 +76,21 @@ export const OfferPricingSection = ({ offer }: Props) => {
<span>{getLocaleAmount(price.amount, price.currency_code)}</span>
</div>
))}
+ {regionPrices.length > 0 && (
+ <div className="txt-small text-ui-fg-muted px-6 py-2">
+ {t("offers.regionPrices")}
+ </div>
+ )}
+ {regionPrices.map((price) => (
+ <div
+ key={price.id ?? `${getPriceRegionId(price)}-${price.amount}`}
+ className="txt-small text-ui-fg-subtle flex justify-between px-6 py-4"
+ data-testid={`offer-detail-region-price-${getPriceRegionId(price)}`}
+ >
+ <span className="font-medium">{regionName(getPriceRegionId(price)!)}</span>
+ <span>{getLocaleAmount(price.amount, price.currency_code)}</span>
+ </div>
+ ))}
{hasPrices && prices.length > PAGE_STEP && (
<div className="txt-small text-ui-fg-subtle flex items-center justify-end px-6 py-4">
<Button
diff --git a/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx b/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
index 7f9ede60e..b96dfa3fc 100644
--- a/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
+++ b/packages/vendor/src/pages/offers/[id]/edit-price/index.tsx
@@ -18,19 +18,24 @@ import { KeyboundForm } from "../../../../components/utilities/keybound-form"
import { usePricePreferences } from "../../../../hooks/api/price-preferences"
import { useProduct, productsQueryKeys } from "../../../../hooks/api/products"
import { offerQueryKeys } from "../../../../hooks/api/offers"
-import { useCurrentSeller } from "../../../../hooks/api/sellers"
import { castNumber } from "../../../../lib/cast-number"
import { sdk } from "../../../../lib/client"
import { queryClient } from "../../../../lib/query-client"
import { OFFER_PRODUCT_DETAIL_FIELDS } from "../../common/constants"
+import { isBasePrice, isRegionPrice } from "../../common/region-prices"
+import { useSellerCurrencies } from "../../common/use-seller-currencies"
+import { OfferPrice } from "../../common/types"
type EditPriceRow = {
offer_id: string
variant_title: string
product_thumbnail?: string | null
prices: Record<string, number | string>
+ region_prices: Record<string, number | string>
}
+type Region = HttpTypes.AdminRegion
+
type FormValues = { rows: EditPriceRow[] }
type PriceProduct = HttpTypes.AdminProduct & {
@@ -42,21 +47,32 @@ type PriceProduct = HttpTypes.AdminProduct & {
const numericOrZero = (v: number | string | undefined | null): number =>
v === "" || v === null || v === undefined ? 0 : castNumber(v) || 0
-const buildRows = (product: PriceProduct, currencies: string[]): EditPriceRow[] =>
+const buildRows = (
+ product: PriceProduct,
+ currencies: string[],
+ regions: Region[],
+): EditPriceRow[] =>
(product.variants ?? []).flatMap((variant) =>
(variant.offers ?? []).map((offer) => {
+ const offerPrices = (offer.prices ?? []) as OfferPrice[]
const prices: Record<string, number | ""> = {}
for (const code of currencies) {
- const match = (offer.prices ?? []).find(
- (p) => p.currency_code === code,
+ const match = offerPrices.find(
+ (p) => isBasePrice(p) && p.currency_code === code,
)
prices[code] = match?.amount ?? ""
}
+ const region_prices: Record<string, number | ""> = {}
+ for (const region of regions) {
+ const match = offerPrices.find((p) => isRegionPrice(p, region.id))
+ region_prices[region.id] = match?.amount ?? ""
+ }
return {
offer_id: offer.id,
variant_title: variant.title ?? "",
product_thumbnail: product.thumbnail ?? null,
prices,
+ region_prices,
}
}),
)
@@ -65,15 +81,21 @@ const columnHelper = createDataGridHelper<EditPriceRow, FormValues>()
const useColumns = ({
currencies,
+ regions,
pricePreferences,
}: {
currencies: string[]
+ regions: Region[]
pricePreferences?: HttpTypes.AdminPricePreference[]
}) => {
const { t } = useTranslation()
- return useMemo(
- () => [
+ return useMemo(() => {
+ const cellCurrencies = Array.from(
+ new Set([...currencies, ...regions.map((r) => r.currency_code)]),
+ )
+
+ return [
columnHelper.column({
id: "title",
header: t("fields.title"),
@@ -95,17 +117,20 @@ const useColumns = ({
...createDataGridPriceColumns<EditPriceRow, FormValues>({
currencies,
pricePreferences: pricePreferences ?? [],
- getFieldName: (context, value) => {
- if (context.column.id?.startsWith("currency_prices")) {
- return `rows.${context.row.index}.prices.${value}`
- }
- return null
- },
+ getFieldName: (context, value) =>
+ `rows.${context.row.index}.prices.${value}`,
t,
}),
- ],
- [t, currencies, pricePreferences],
- )
+ ...createDataGridPriceColumns<EditPriceRow, FormValues>({
+ currencies: cellCurrencies,
+ regions,
+ pricePreferences: pricePreferences ?? [],
+ getFieldName: (context, value) =>
+ `rows.${context.row.index}.region_prices.${value}`,
+ t,
+ }).filter((column) => column.id?.startsWith("region_prices")),
+ ]
+ }, [t, currencies, regions, pricePreferences])
}
const EditPriceGrid = ({
@@ -117,34 +142,44 @@ const EditPriceGrid = ({
}) => {
const { t } = useTranslation()
const { handleSuccess, setCloseOnEscape } = useRouteModal()
- const { currency_code } = useCurrentSeller()
+ const { currencies, regions } = useSellerCurrencies()
const canViewPricePreferences = useCan("price_preferences")
const { price_preferences: pricePreferences } = usePricePreferences(
{},
{ enabled: canViewPricePreferences }
)
- const currencies = useMemo(
- () => (currency_code ? [currency_code] : []),
- [currency_code],
- )
-
const rows = useMemo(
- () => buildRows(product, currencies),
- [product, currencies],
+ () => buildRows(product, currencies, regions),
+ [product, currencies, regions],
)
const form = useForm<FormValues>({ defaultValues: { rows } })
- const columns = useColumns({ currencies, pricePreferences })
+ const columns = useColumns({ currencies, regions, pricePreferences })
const handleSubmit = form.handleSubmit(async (values) => {
try {
await Promise.all(
values.rows.map((row) => {
- const prices = currencies.map((code) => ({
- amount: numericOrZero(row.prices?.[code]),
- currency_code: code,
- }))
+ const prices: {
+ amount: number
+ currency_code: string
+ rules?: Record<string, string>
+ }[] = []
+ for (const code of currencies) {
+ const value = row.prices?.[code]
+ if (value === "" || value === null || value === undefined) continue
+ prices.push({ amount: numericOrZero(value), currency_code: code })
+ }
+ for (const region of regions) {
+ const value = row.region_prices?.[region.id]
+ if (value === "" || value === null || value === undefined) continue
+ prices.push({
+ amount: numericOrZero(value),
+ currency_code: region.currency_code,
+ rules: { region_id: region.id },
+ })
+ }
return sdk.vendor.offers.$id.mutate({ $id: row.offer_id, prices })
}),
)
diff --git a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
index 10925f1e8..cdf6b3206 100644
--- a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
+++ b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/pricing-form.tsx
@@ -18,9 +18,10 @@ import {
import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
import { useUpdateOffer } from "../../../../../hooks/api/offers"
import { usePricePreferences } from "../../../../../hooks/api/price-preferences"
-import { useCurrentSeller } from "../../../../../hooks/api/sellers"
import { castNumber } from "../../../../../lib/cast-number"
-import { OfferDetail, OfferPrice } from "../../../common/types"
+import { isBasePrice, isRegionPrice } from "../../../common/region-prices"
+import { useSellerCurrencies } from "../../../common/use-seller-currencies"
+import { OfferDetail } from "../../../common/types"
import {
PricingFormSchema,
PricingFormValues,
@@ -31,53 +32,56 @@ type Props = {
offer: OfferDetail
}
-const isBaseRow = (price: OfferPrice) => {
- if (!price) return false
- const rules = price.price_rules ?? []
- const extraRules = rules.filter((r) => r.attribute !== "offer_id")
- return extraRules.length === 0
-}
+type Region = HttpTypes.AdminRegion
const buildDefaults = (
offer: OfferDetail,
currencies: string[],
+ regions: Region[],
): PricingFormValues => {
const basePrice: PricingRow = {
id: offer.id,
currency_prices: currencies.reduce<Record<string, number | "">>(
(acc, code) => {
const existing = offer.prices?.find(
- (p) => Boolean(p) && isBaseRow(p) && p.currency_code === code,
+ (p) => isBasePrice(p) && p.currency_code === code,
)
acc[code] = existing?.amount ?? ""
return acc
},
{},
),
+ region_prices: regions.reduce<Record<string, number | "">>(
+ (acc, region) => {
+ const existing = offer.prices?.find((p) => isRegionPrice(p, region.id))
+ acc[region.id] = existing?.amount ?? ""
+ return acc
+ },
+ {},
+ ),
}
return { prices: [basePrice] }
}
export const PricingForm = ({ offer }: Props) => {
- const { currency_code, isPending: isSellerPending } = useCurrentSeller()
-
- const currencies = useMemo(
- () => (currency_code ? [currency_code] : []),
- [currency_code],
- )
+ const { currencies, regions, isPending } = useSellerCurrencies()
- if (isSellerPending || !currencies.length) return null
+ if (isPending) return null
- return <PricingFormInner offer={offer} currencies={currencies} />
+ return (
+ <PricingFormInner offer={offer} currencies={currencies} regions={regions} />
+ )
}
const PricingFormInner = ({
offer,
currencies,
+ regions,
}: {
offer: OfferDetail
currencies: string[]
+ regions: Region[]
}) => {
const { t } = useTranslation()
const { handleSuccess, setCloseOnEscape } = useRouteModal()
@@ -88,8 +92,8 @@ const PricingFormInner = ({
)
const defaults = useMemo(
- () => buildDefaults(offer, currencies),
- [offer, currencies],
+ () => buildDefaults(offer, currencies, regions),
+ [offer, currencies, regions],
)
const form = useForm<PricingFormValues>({
@@ -99,6 +103,7 @@ const PricingFormInner = ({
const columns = usePriceGridColumns({
currencies,
+ regions,
pricePreferences,
})
@@ -112,7 +117,12 @@ const PricingFormInner = ({
const handleSubmit = form.handleSubmit(async (values) => {
const row = values.prices[0]
- const submitted: { id?: string; amount: number; currency_code: string }[] = []
+ const submitted: {
+ id?: string
+ amount: number
+ currency_code: string
+ rules?: Record<string, string>
+ }[] = []
for (const [currency_code, amount] of Object.entries(
row.currency_prices ?? {},
)) {
@@ -120,7 +130,7 @@ const PricingFormInner = ({
const num = castNumber(amount)
if (!Number.isFinite(num)) continue
const existing = offer.prices?.find(
- (p) => Boolean(p) && isBaseRow(p) && p.currency_code === currency_code,
+ (p) => isBasePrice(p) && p.currency_code === currency_code,
)
submitted.push({
...(existing?.id ? { id: existing.id } : {}),
@@ -128,6 +138,20 @@ const PricingFormInner = ({
currency_code,
})
}
+ for (const [regionId, amount] of Object.entries(row.region_prices ?? {})) {
+ if (amount === "" || amount === undefined || amount === null) continue
+ const region = regions.find((r) => r.id === regionId)
+ if (!region) continue
+ const num = castNumber(amount)
+ if (!Number.isFinite(num)) continue
+ const existing = offer.prices?.find((p) => isRegionPrice(p, regionId))
+ submitted.push({
+ ...(existing?.id ? { id: existing.id } : {}),
+ amount: num,
+ currency_code: region.currency_code,
+ rules: { region_id: regionId },
+ })
+ }
await mutateAsync(
{ prices: submitted },
@@ -174,14 +198,20 @@ const columnHelper = createDataGridHelper<PricingRow, PricingFormValues>()
const usePriceGridColumns = ({
currencies = [],
+ regions = [],
pricePreferences = [],
}: {
currencies?: string[]
+ regions?: Region[]
pricePreferences?: HttpTypes.AdminPricePreference[]
}) => {
const { t } = useTranslation()
return useMemo(() => {
+ const cellCurrencies = Array.from(
+ new Set([...currencies, ...regions.map((r) => r.currency_code)]),
+ )
+
return [
columnHelper.column({
id: "title",
@@ -199,14 +229,18 @@ const usePriceGridColumns = ({
...createDataGridPriceColumns<PricingRow, PricingFormValues>({
currencies,
pricePreferences,
- getFieldName: (context, value) => {
- if (context.column.id?.startsWith("currency_prices")) {
- return `prices.${context.row.index}.currency_prices.${value}`
- }
- return null
- },
+ getFieldName: (context, value) =>
+ `prices.${context.row.index}.currency_prices.${value}`,
t,
}),
+ ...createDataGridPriceColumns<PricingRow, PricingFormValues>({
+ currencies: cellCurrencies,
+ regions,
+ pricePreferences,
+ getFieldName: (context, value) =>
+ `prices.${context.row.index}.region_prices.${value}`,
+ t,
+ }).filter((column) => column.id?.startsWith("region_prices")),
]
- }, [t, currencies, pricePreferences])
+ }, [t, currencies, regions, pricePreferences])
}
diff --git a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/schema.ts b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/schema.ts
index 189c3cfaa..eaccad485 100644
--- a/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/schema.ts
+++ b/packages/vendor/src/pages/offers/[id]/pricing/pricing-form/schema.ts
@@ -7,6 +7,7 @@ const PriceCellSchema = optionalFloat
const PriceRowSchema = z.object({
id: z.string(),
currency_prices: z.record(z.string(), PriceCellSchema).default({}),
+ region_prices: z.record(z.string(), PriceCellSchema).default({}),
})
export const PricingFormSchema = z.object({
diff --git a/packages/vendor/src/pages/offers/common/constants.ts b/packages/vendor/src/pages/offers/common/constants.ts
index 08036437a..e9fbaf6a1 100644
--- a/packages/vendor/src/pages/offers/common/constants.ts
+++ b/packages/vendor/src/pages/offers/common/constants.ts
@@ -177,8 +177,11 @@ export const OFFER_PRODUCT_DETAIL_FIELDS = [
"variants.offers.sku",
"variants.offers.created_at",
"variants.offers.updated_at",
+ "variants.offers.prices.id",
"variants.offers.prices.amount",
"variants.offers.prices.currency_code",
+ "variants.offers.prices.price_rules.attribute",
+ "variants.offers.prices.price_rules.value",
"variants.offers.shipping_profile.id",
"variants.offers.shipping_profile.name",
"variants.offers.inventory_items.id",
diff --git a/packages/vendor/src/pages/offers/common/region-prices.ts b/packages/vendor/src/pages/offers/common/region-prices.ts
new file mode 100644
index 000000000..f89eea552
--- /dev/null
+++ b/packages/vendor/src/pages/offers/common/region-prices.ts
@@ -0,0 +1,22 @@
+import { OfferPrice } from "./types"
+
+export const getPriceRegionId = (price: OfferPrice): string | null =>
+ price.price_rules?.find((r) => r.attribute === "region_id")?.value ?? null
+
+export const isBasePrice = (price: OfferPrice | null | undefined): price is OfferPrice => {
+ if (!price) return false
+ const rules = price.price_rules ?? []
+ return rules.every((r) => r.attribute === "offer_id")
+}
+
+export const isRegionPrice = (
+ price: OfferPrice | null | undefined,
+ regionId: string,
+): price is OfferPrice => {
+ if (!price) return false
+ const rules = price.price_rules ?? []
+ return (
+ rules.every((r) => r.attribute === "offer_id" || r.attribute === "region_id") &&
+ getPriceRegionId(price) === regionId
+ )
+}
diff --git a/packages/vendor/src/pages/offers/common/use-seller-currencies.ts b/packages/vendor/src/pages/offers/common/use-seller-currencies.ts
new file mode 100644
index 000000000..2deaec753
--- /dev/null
+++ b/packages/vendor/src/pages/offers/common/use-seller-currencies.ts
@@ -0,0 +1,31 @@
+import { useCan } from "@mercurjs/dashboard-shared"
+import { HttpTypes } from "@medusajs/types"
+import { useMemo } from "react"
+
+import { useRegions } from "../../../hooks/api/regions"
+
+export const useSellerCurrencies = () => {
+ const canViewRegions = useCan("regions")
+ const { regions: fetchedRegions, isPending, isError, error } = useRegions(
+ { fields: "id,name,currency_code", limit: 999 },
+ { enabled: canViewRegions },
+ )
+
+ const regions = useMemo<HttpTypes.AdminRegion[]>(
+ () => (canViewRegions ? (fetchedRegions ?? []) : []),
+ [canViewRegions, fetchedRegions],
+ )
+
+ const currencies = useMemo(
+ () => Array.from(new Set(regions.map((r) => r.currency_code))),
+ [regions],
+ )
+
+ return {
+ regions,
+ currencies,
+ isPending: canViewRegions && isPending,
+ isError,
+ error,
+ }
+}
diff --git a/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-form.tsx b/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-form.tsx
index f591a4448..cbed77383 100644
--- a/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-form.tsx
+++ b/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-form.tsx
@@ -11,8 +11,8 @@ import { useOfferConditions } from "../../../../hooks/api/offer-conditions";
import { useBulkCreateOffers } from "../../../../hooks/api/offers";
import { castNumber } from "../../../../lib/cast-number";
import { useProducts } from "../../../../hooks/api/products";
-import { useCurrentSeller } from "../../../../hooks/api/sellers";
import { useStockLocations } from "../../../../hooks/api/stock-locations";
+import { useSellerCurrencies } from "../../common/use-seller-currencies";
import { CreateOfferCatalogueTab } from "./create-offer-catalogue";
import { CreateOfferStockLevelsAndPricesTab } from "./create-offer-stock-levels-and-prices";
import {
@@ -71,7 +71,7 @@ export const CreateOfferForm = () => {
});
const { mutateAsync: bulkCreateOffers } = useBulkCreateOffers();
- const { currency_code } = useCurrentSeller();
+ const { currencies, regions } = useSellerCurrencies();
const canViewLocations = useCan("stock_locations");
const { stock_locations } = useStockLocations(
{ limit: 100 },
@@ -86,6 +86,7 @@ export const CreateOfferForm = () => {
const selectedProductIds = form.watch("selected_product_ids") ?? [];
const selectedProductIdsKey = selectedProductIds.join(",");
const locationsKey = locationIds.join(",");
+ const currenciesKey = currencies.join(",");
// Fetch the selected products with their variants — the stock & prices
// tab fans each product out to one row per variant (SPEC-009).
@@ -104,9 +105,9 @@ export const CreateOfferForm = () => {
useEffect(() => {
const locIds = locationsKey ? locationsKey.split(",") : [];
- const emptyPrices: Record<string, number | ""> = currency_code
- ? { [currency_code]: "" }
- : {};
+ const emptyPrices: Record<string, number | ""> = Object.fromEntries(
+ (currenciesKey ? currenciesKey.split(",") : []).map((code) => [code, ""]),
+ );
const emptyInventory = locIds.reduce<
Record<
string,
@@ -148,6 +149,7 @@ export const CreateOfferForm = () => {
shipping_profile_id: "",
condition_id: defaultConditionId,
prices: { ...emptyPrices },
+ region_prices: {},
inventory: { ...emptyInventory },
});
}
@@ -160,7 +162,7 @@ export const CreateOfferForm = () => {
}, [
selectedProductIdsKey,
fetchedProducts,
- currency_code,
+ currenciesKey,
locationsKey,
defaultConditionId,
form,
@@ -173,7 +175,8 @@ export const CreateOfferForm = () => {
return;
}
- if (!currency_code) {
+ if (!currencies.length) {
+ toast.error(t("offers.validation.noCurrencies"));
return;
}
@@ -184,9 +187,9 @@ export const CreateOfferForm = () => {
for (let i = 0; i < variants.length; i++) {
const row = variants[i];
- if (!variantRowHasPrice(row, currency_code)) {
+ if (!variantRowHasPrice(row, currencies)) {
if (variantRowHasPartialInput(row)) {
- form.setError(`variants.${i}.prices.${currency_code}`, {
+ form.setError(`variants.${i}.prices.${currencies[0]}`, {
type: "manual",
message: t("offers.validation.priceRequired"),
});
@@ -233,12 +236,25 @@ export const CreateOfferForm = () => {
setIsSubmitting(true);
const payloadOffers = rows.map(({ row, sku }) => {
- const prices = [
- {
- amount: numericOrZero(row.prices?.[currency_code]),
- currency_code,
- },
- ];
+ const prices: {
+ amount: number;
+ currency_code: string;
+ rules?: Record<string, string>;
+ }[] = [];
+ for (const code of currencies) {
+ const value = row.prices?.[code];
+ if (value === "" || value === null || value === undefined) continue;
+ prices.push({ amount: numericOrZero(value), currency_code: code });
+ }
+ for (const region of regions) {
+ const value = row.region_prices?.[region.id];
+ if (value === "" || value === null || value === undefined) continue;
+ prices.push({
+ amount: numericOrZero(value),
+ currency_code: region.currency_code,
+ rules: { region_id: region.id },
+ });
+ }
const stock_levels: { location_id: string; stocked_quantity: number }[] = [];
for (const [locationId, level] of Object.entries(row.inventory ?? {})) {
diff --git a/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-stock-levels-and-prices.tsx b/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-stock-levels-and-prices.tsx
index 6369dfbf4..a569c9d11 100644
--- a/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-stock-levels-and-prices.tsx
+++ b/packages/vendor/src/pages/offers/create/create-offer-form/create-offer-stock-levels-and-prices.tsx
@@ -15,9 +15,9 @@ import { useRouteModal } from "../../../../components/modals";
import { defineTabMeta } from "../../../../components/tabbed-form/types";
import { usePricePreferences } from "../../../../hooks/api/price-preferences";
import { useOfferConditions } from "../../../../hooks/api/offer-conditions";
-import { useCurrentSeller } from "../../../../hooks/api/sellers";
import { useShippingProfiles } from "../../../../hooks/api/shipping-profiles";
import { useStockLocations } from "../../../../hooks/api/stock-locations";
+import { useSellerCurrencies } from "../../common/use-seller-currencies";
import { CreateOfferFormValues, OfferVariantRow } from "./schema";
type ShippingProfileLite = { id: string; name?: string | null };
@@ -48,7 +48,7 @@ const Root = () => {
const form = useFormContext<CreateOfferFormValues>();
const { setCloseOnEscape } = useRouteModal();
- const { currency_code } = useCurrentSeller();
+ const { currencies, regions } = useSellerCurrencies();
const { can } = usePermissions();
const { stock_locations } = useStockLocations(
{ limit: 100 },
@@ -65,7 +65,6 @@ const Root = () => {
{},
{ enabled: can("price_preferences") }
);
-
const variants = useWatch({
control: form.control,
name: "variants",
@@ -89,13 +88,14 @@ const Root = () => {
}, [variants]);
const columns = useColumns({
- currencyCode: currency_code,
+ currencies,
stockLocations: stock_locations as
| HttpTypes.AdminStockLocation[]
| undefined,
shippingProfiles: shipping_profiles ?? [],
offerConditions: offer_conditions ?? [],
pricePreferences,
+ regions,
});
return (
@@ -114,21 +114,23 @@ const Root = () => {
};
type ColumnArgs = {
- currencyCode?: string;
+ currencies?: string[];
stockLocations?: HttpTypes.AdminStockLocation[];
shippingProfiles?: ShippingProfileLite[];
offerConditions?: OfferConditionLite[];
pricePreferences?: HttpTypes.AdminPricePreference[];
+ regions?: HttpTypes.AdminRegion[];
};
const columnHelper = createDataGridHelper<GridRow, CreateOfferFormValues>();
const useColumns = ({
- currencyCode,
+ currencies = [],
stockLocations = [],
shippingProfiles = [],
offerConditions = [],
pricePreferences = [],
+ regions = [],
}: ColumnArgs) => {
const { t } = useTranslation();
@@ -141,7 +143,9 @@ const useColumns = ({
value: c.id,
label: c.label,
}));
- const currencies = currencyCode ? [currencyCode] : [];
+ const cellCurrencies = Array.from(
+ new Set([...currencies, ...regions.map((r) => r.currency_code)])
+ );
return [
columnHelper.column({
@@ -252,21 +256,31 @@ const useColumns = ({
getFieldName: (context, value) => {
const row = context.row.original;
if (isGroup(row)) return null;
- if (context.column.id?.startsWith("currency_prices")) {
- return `variants.${row.__formIndex}.prices.${value}`;
- }
- return null;
+ return `variants.${row.__formIndex}.prices.${value}`;
},
t,
}),
+ ...createDataGridPriceColumns<GridRow, CreateOfferFormValues>({
+ currencies: cellCurrencies,
+ regions,
+ pricePreferences,
+ isReadyOnly: (context) => isGroup(context.row.original),
+ getFieldName: (context, value) => {
+ const row = context.row.original;
+ if (isGroup(row)) return null;
+ return `variants.${row.__formIndex}.region_prices.${value}`;
+ },
+ t,
+ }).filter((column) => column.id?.startsWith("region_prices")),
];
}, [
t,
- currencyCode,
+ currencies,
stockLocations,
shippingProfiles,
offerConditions,
pricePreferences,
+ regions,
]);
};
diff --git a/packages/vendor/src/pages/offers/create/create-offer-form/schema.ts b/packages/vendor/src/pages/offers/create/create-offer-form/schema.ts
index 6ce036b8f..2e7dc31f4 100644
--- a/packages/vendor/src/pages/offers/create/create-offer-form/schema.ts
+++ b/packages/vendor/src/pages/offers/create/create-offer-form/schema.ts
@@ -14,6 +14,7 @@ const VariantRowSchema = z.object({
shipping_profile_id: z.string().default(""),
condition_id: z.string().default(""),
prices: z.record(z.string(), optionalFloat).default({}),
+ region_prices: z.record(z.string(), optionalFloat).default({}),
inventory: z
.record(
z.string(),
@@ -44,8 +45,10 @@ const numericOrZero = (v: number | string | undefined | null): number => {
export const variantRowHasPrice = (
row: OfferVariantRow,
- currencyCode: string,
-): boolean => numericOrZero(row.prices?.[currencyCode]) > 0
+ currencyCodes: string[],
+): boolean =>
+ currencyCodes.some((code) => numericOrZero(row.prices?.[code]) > 0) ||
+ Object.values(row.region_prices ?? {}).some((v) => numericOrZero(v) > 0)
// SKU is prefilled from the master variant, so it can't signal intent.
export const variantRowHasPartialInput = (row: OfferVariantRow): boolean =>
diff --git a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx
index 1a7922a06..470c084c9 100644
--- a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx
+++ b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx
@@ -1,22 +1,13 @@
import { isForbidden, usePermissions } from "@mercurjs/dashboard-shared"
import { useRegions } from "../../../../hooks/api/regions"
-import { useCurrentSeller } from "../../../../hooks/api/sellers"
import { usePricePreferences } from "../../../../hooks/api/price-preferences"
export const usePriceListCurrencyData = () => {
- const {
- currency_code,
- isPending: isSellerPending,
- isError: isSellerError,
- error: sellerError,
- } = useCurrentSeller()
const { can } = usePermissions()
const canViewRegions = can("regions")
const canViewPreferences = can("price_preferences")
- const currencies = currency_code ? [currency_code] : undefined
-
const {
regions,
isPending: isRegionsPending,
@@ -37,11 +28,14 @@ export const usePriceListCurrencyData = () => {
error: preferencesError,
} = usePricePreferences({}, { enabled: canViewPreferences })
+ const currencies = regions
+ ? Array.from(new Set(regions.map((r) => r.currency_code)))
+ : undefined
+
const isReady =
!!currencies &&
!!regions &&
!!pricePreferences &&
- !isSellerPending &&
!isRegionsPending &&
!isPreferencesPending
@@ -55,10 +49,6 @@ export const usePriceListCurrencyData = () => {
throw regionsError
}
- if (isSellerError) {
- throw sellerError
- }
-
if (isPreferencesError && !isForbidden(preferencesError)) {
throw preferencesError
}