1 ---
2 sidebar_label: "Enforce Sales Channel Availability"
3 tags:
4 - cart
5 - sales channel
6 - name: how to
7 label: Enforce Sales Channel Availability
8 - server
9 ---
10
11 import { Prerequisites } from "docs-ui"
12
13 export const metadata = {
14 title: `Enforce Sales Channel Availability in Carts`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to reject product variants whose product isn't available in the cart's sales channel.
20
21 <Prerequisites
22 items={[
23 {
24 text: "Medusa application set up",
25 link: "!docs!/learn/installation",
26 },
27 ]}
28 />
29
30 ## Why Medusa Doesn't Enforce This by Default
31
32 A product's [availability in a sales channel](../../sales-channel/links-to-other-modules/page.mdx#product-module) is a merchandising filter, not an authorization boundary.
33
34 Medusa applies it when you retrieve products. For example, the [List Products Store API route](!api!/store/products/list-products) only returns the products available in the sales channels of the publishable API key in the request. So, a product that you remove from a sales channel disappears from that channel's storefront.
35
36 Medusa doesn't apply that filter when a variant is added to a cart or when a cart is completed. A customer who knows a variant's ID can still add it to a cart scoped to a sales channel that the variant's product isn't available in.
37
38 <Note title="Warning" type="warning">
39
40 Medusa doesn't enforce this by default because merchants use sales channels for merchandising, and rejecting items would break carts whenever a merchant changes a product's availability. If you rely on sales channels for legal or contractual restrictions, such as licensing agreements that forbid selling a product in a country, add the validation shown in this guide.
41
42 </Note>
43
44 The inventory check that does run when you add an item to a cart, which the [confirmVariantInventoryWorkflow](/references/medusa-workflows/confirmVariantInventoryWorkflow) performs, only checks the quantity available at the stock locations of the cart's sales channel. It doesn't check whether the variant's product is linked to that sales channel.
45
46 To enforce the availability, consume the `validate` [hook](!docs!/learn/fundamentals/workflows/workflow-hooks) of the workflows that add items to a cart and complete a cart. A workflow hook is a point in a workflow where you can inject custom functionality as a step function. If the step function throws an error, the workflow stops and the API route returns the error.
47
48 <Note>
49
50 This guide doesn't cover draft orders that admin users create in the dashboard, as it's assumed that merchants don't need to enforce sales channel availability for them.
51
52 </Note>
53
54 ---
55
56 ## Step 1: Create the Validation Function
57
58 Start by creating a function that finds the variants that aren't available in a sales channel. You'll reuse it in both hooks.
59
60 Create the file `src/utils/sales-channel-availability.ts` with the following content:
61
62 export const helperHighlights = [
63 ["15", "query", "Use Query to retrieve data across modules."],
64 ["21", "fields", "Retrieve the sales channels of each variant's product."],
65 ["32", "some", "Check whether the product is linked to the cart's sales channel."],
66 ]
67
68 ```ts title="src/utils/sales-channel-availability.ts" highlights={helperHighlights}
69 import { MedusaContainer } from "@medusajs/framework/types"
70 import {
71 ContainerRegistrationKeys,
72 } from "@medusajs/framework/utils"
73
74 export async function getUnavailableVariantIds({
75 container,
76 variantIds,
77 salesChannelId,
78 }: {
79 container: MedusaContainer
80 variantIds: string[]
81 salesChannelId: string
82 }) {
83 const query = container.resolve(
84 ContainerRegistrationKeys.QUERY
85 )
86
87 const { data: variants } = await query.graph({
88 entity: "variant",
89 fields: ["id", "product.sales_channels.id"],
90 filters: {
91 id: variantIds,
92 },
93 })
94
95 return variants
96 .filter((variant) => {
97 const salesChannels =
98 variant.product?.sales_channels ?? []
99
100 return !salesChannels.some(
101 (salesChannel) =>
102 salesChannel?.id === salesChannelId
103 )
104 })
105 .map((variant) => variant.id)
106 }
107 ```
108
109 The function uses [Query](!docs!/learn/fundamentals/query) to retrieve the variants with the sales channels of their product, then returns the IDs of the variants whose product isn't linked to the specified sales channel.
110
111 A product without any sales channels isn't available in any of them, so the function considers its variants unavailable.
112
113 ---
114
115 ## Step 2: Validate Items Added to the Cart
116
117 Next, consume the `validate` hook of the [addToCartWorkflow](/references/medusa-workflows/addToCartWorkflow), which the [Add Line Item Store API route](!api!/store/carts/add-line-item) executes.
118
119 Create the file `src/workflows/hooks/validate-add-to-cart.ts` with the following content:
120
121 export const addToCartHighlights = [
122 ["9", "sales_channel_id", "Skip the validation if the cart has no sales channel."],
123 ["13", "variantIds", "Collect the IDs of the variants being added."],
124 ["28", "MedusaError", "Reject the request if a variant isn't available."],
125 ]
126
127 ```ts title="src/workflows/hooks/validate-add-to-cart.ts" highlights={addToCartHighlights}
128 import { MedusaError } from "@medusajs/framework/utils"
129 import { addToCartWorkflow } from "@medusajs/medusa/core-flows"
130 import {
131 getUnavailableVariantIds,
132 } from "../../utils/sales-channel-availability"
133
134 addToCartWorkflow.hooks.validate(
135 async ({ input, cart }, { container }) => {
136 if (!cart.sales_channel_id) {
137 return
138 }
139
140 const variantIds = (input.items ?? [])
141 .map((item) => item.variant_id)
142 .filter(Boolean) as string[]
143
144 if (!variantIds.length) {
145 return
146 }
147
148 const unavailableIds = await getUnavailableVariantIds({
149 container,
150 variantIds,
151 salesChannelId: cart.sales_channel_id,
152 })
153
154 if (unavailableIds.length) {
155 throw new MedusaError(
156 MedusaError.Types.NOT_ALLOWED,
157 `The variants ${unavailableIds.join(", ")} aren't ` +
158 `available in the cart's sales channel.`
159 )
160 }
161 }
162 )
163 ```
164
165 The hook receives the cart and the input passed to the workflow, which holds the items to add. You retrieve the IDs of the variants that aren't available in the cart's sales channel, then throw a `MedusaError` if there are any. The Add Line Item API route then returns a response with the `400` status code.
166
167 <Note>
168
169 A cart isn't always associated with a sales channel. The example returns early in that case, since there's nothing to validate against.
170
171 </Note>
172
173 ---
174
175 ## Step 3: Validate the Cart on Completion
176
177 A merchant can change a product's availability after a customer adds it to their cart. So, also consume the `validate` hook of the [completeCartWorkflow](/references/medusa-workflows/completeCartWorkflow) to check the cart's items before Medusa creates the order.
178
179 Create the file `src/workflows/hooks/validate-complete-cart.ts` with the following content:
180
181 export const completeCartHighlights = [
182 ["15", "cart.items", "Collect the IDs of the variants in the cart."],
183 ["30", "MedusaError", "Reject the cart completion if a variant isn't available."],
184 ]
185
186 ```ts title="src/workflows/hooks/validate-complete-cart.ts" highlights={completeCartHighlights}
187 import { MedusaError } from "@medusajs/framework/utils"
188 import {
189 completeCartWorkflow,
190 } from "@medusajs/medusa/core-flows"
191 import {
192 getUnavailableVariantIds,
193 } from "../../utils/sales-channel-availability"
194
195 completeCartWorkflow.hooks.validate(
196 async ({ cart }, { container }) => {
197 if (!cart.sales_channel_id) {
198 return
199 }
200
201 const variantIds = (cart.items ?? [])
202 .map((item) => item.variant_id)
203 .filter(Boolean) as string[]
204
205 if (!variantIds.length) {
206 return
207 }
208
209 const unavailableIds = await getUnavailableVariantIds({
210 container,
211 variantIds,
212 salesChannelId: cart.sales_channel_id,
213 })
214
215 if (unavailableIds.length) {
216 throw new MedusaError(
217 MedusaError.Types.NOT_ALLOWED,
218 `The variants ${unavailableIds.join(", ")} are no ` +
219 `longer available in the cart's sales channel.`
220 )
221 }
222 }
223 )
224 ```
225
226 This stops the cart completion for carts that a customer created before the merchant changed a product's availability.
227
228 ---
229
230 ## Test it Out
231
232 To test out the validation:
233
234 1. Start the Medusa application.
235 2. In the Medusa Admin dashboard, add a product that doesn't belong to a sales channel, or remove a product from a sales channel, as explained in the [user guide](!user-guide!/settings/sales-channels#manage-products-in-sales-channel).
236 3. Create a cart associated with that sales channel using a publishable API key linked to it.
237 4. Send a request to the [Add Line Item Store API route](!api!/store/carts/add-line-item) with a variant of the product you removed.
238
239 The request returns a response with the `400` status code and the error message you specified.