1 import { HttpTypes } from "@medusajs/types"
2 import { TFunction } from "i18next"
3 import { castNumber } from "../../../lib/cast-number"
4 import { jsonResponse } from "../../../lib/json-response"
5 import { PriceListDateStatus, PriceListStatus } from "./constants"
6 import {
7 PriceListCreateCurrencyPrice,
8 PriceListCreateProductVariantSchema,
9 PriceListCreateProductsSchema,
10 PriceListUpdateProductsSchema,
11 PriceListUpdateProductVariantsSchema,
12 PriceListUpdateCurrencyPrice,
13 PriceListUpdateRegionPrice,
14 } from "./schemas"
15
16 const getValues = (priceList: HttpTypes.AdminPriceList) => {
17 const startsAt = priceList.starts_at
18 const endsAt = priceList.ends_at
19
20 const isExpired = endsAt ? new Date(endsAt) < new Date() : false
21 const isScheduled = startsAt ? new Date(startsAt) > new Date() : false
22 const isDraft = priceList.status === PriceListStatus.DRAFT
23
24 return {
25 isExpired,
26 isScheduled,
27 isDraft,
28 }
29 }
30
31 export const getPriceListStatus = (
32 t: TFunction<"translation">,
33 priceList: HttpTypes.AdminPriceList
34 ) => {
35 const { isExpired, isScheduled, isDraft } = getValues(priceList)
36
37 let text = t("priceLists.fields.status.options.active")
38 let color: "red" | "grey" | "orange" | "green" = "green"
39 let status: string = PriceListStatus.ACTIVE
40
41 if (isDraft) {
42 color = "grey"
43 text = t("priceLists.fields.status.options.draft")
44 status = PriceListStatus.DRAFT
45 }
46
47 if (isExpired) {
48 color = "red"
49 text = t("priceLists.fields.status.options.expired")
50 status = PriceListDateStatus.EXPIRED
51 }
52
53 if (isScheduled) {
54 color = "orange"
55 text = t("priceLists.fields.status.options.scheduled")
56 status = PriceListDateStatus.SCHEDULED
57 }
58
59 return {
60 color,
61 text,
62 status,
63 }
64 }
65
66 export const isProductRow = (
67 row: HttpTypes.AdminProduct | HttpTypes.AdminProductVariant
68 ): row is HttpTypes.AdminProduct => {
69 return "variants" in row
70 }
71
72 const extractPricesFromVariants = (
73 variantId: string,
74 variant: PriceListCreateProductVariantSchema,
75 regions: HttpTypes.AdminRegion[]
76 ) => {
77 const extractPriceDetails = (
78 price: PriceListCreateCurrencyPrice,
79 priceType: "region" | "currency",
80 id: string
81 ) => {
82 const currencyCode =
83 priceType === "currency"
84 ? id
85 : regions.find((r) => r.id === id)?.currency_code
86
87 if (!currencyCode) {
88 throw jsonResponse({ message: "Currency code not found" }, 400)
89 }
90
91 const rules: Record<string, string> = {}
92 if (priceType === "region") {
93 rules.region_id = id
94 }
95 if (price.min_quantity) {
96 rules.min_quantity = price.min_quantity.toString()
97 }
98 if (price.max_quantity) {
99 rules.max_quantity = price.max_quantity.toString()
100 }
101
102 return {
103 amount: castNumber(price.amount!),
104 currency_code: currencyCode,
105 variant_id: variantId,
106 rules: Object.keys(rules).length > 0 ? rules : undefined,
107 }
108 }
109
110 const processPrices = (
111 pricesMap:
112 | Record<string, PriceListCreateCurrencyPrice[] | undefined>
113 | undefined,
114 priceType: "region" | "currency"
115 ) => {
116 return Object.entries(pricesMap || {}).flatMap(([id, prices]) => {
117 return (prices || []).flatMap((price) =>
118 price?.amount ? [extractPriceDetails(price, priceType, id)] : []
119 )
120 })
121 }
122
123 const currencyPrices = processPrices(variant.currency_prices, "currency")
124 const conditionalCurrencyPrices = processPrices(
125 variant.conditional_currency_prices,
126 "currency"
127 )
128 const regionPrices = processPrices(variant.region_prices, "region")
129 const conditionalRegionPrices = processPrices(
130 variant.conditional_region_prices,
131 "region"
132 )
133
134 return [
135 ...currencyPrices,
136 ...conditionalCurrencyPrices,
137 ...regionPrices,
138 ...conditionalRegionPrices,
139 ]
140 }
141
142 export const exctractPricesFromProducts = (
143 products: PriceListCreateProductsSchema,
144 regions: HttpTypes.AdminRegion[]
145 ) => {
146 return Object.values(products).flatMap(({ variants }) =>
147 Object.entries(variants).flatMap(([variantId, variant]) =>
148 extractPricesFromVariants(variantId, variant, regions)
149 )
150 )
151 }
152
153 export function initRecord(
154 priceList: HttpTypes.AdminPriceList,
155 products: HttpTypes.AdminProduct[]
156 ): PriceListUpdateProductsSchema {
157 const record: PriceListUpdateProductsSchema = {}
158
159 const variantPrices = priceList.prices?.reduce((variants, price) => {
160 const variantObject = variants[price.variant_id] || {}
161
162 const isRegionPrice = !!price.rules?.region_id
163
164 const isTiered = !!(price.rules?.min_quantity || price.rules?.max_quantity)
165
166 if (isRegionPrice) {
167 const regionId = price.rules.region_id as string
168 const field = isTiered ? "conditional_region_prices" : "region_prices"
169 ;(variantObject[field] = variantObject[field] || {})[regionId] = [
170 ...(variantObject[field]?.[regionId] || []),
171 {
172 amount: price.amount.toString(),
173 id: price.id,
174 min_quantity: price.rules?.min_quantity?.toString(),
175 max_quantity: price.rules?.max_quantity?.toString(),
176 },
177 ]
178 } else {
179 const field = isTiered ? "conditional_currency_prices" : "currency_prices"
180 ;(variantObject[field] = variantObject[field] || {})[
181 price.currency_code
182 ] = [
183 ...(variantObject[field]?.[price.currency_code] || []),
184 {
185 amount: price.amount.toString(),
186 id: price.id,
187 min_quantity: price.rules?.min_quantity?.toString(),
188 max_quantity: price.rules?.max_quantity?.toString(),
189 },
190 ]
191 }
192
193 variants[price.variant_id] = variantObject
194 return variants
195 }, {} as PriceListUpdateProductVariantsSchema)
196
197 for (const product of products) {
198 record[product.id] = {
199 variants:
200 product.variants?.reduce((variants, variant) => {
201 const prices = variantPrices[variant.id] || {}
202 variants[variant.id] = {
203 currency_prices: prices.currency_prices || {},
204 region_prices: prices.region_prices || {},
205 conditional_currency_prices:
206 prices.conditional_currency_prices || {},
207 conditional_region_prices: prices.conditional_region_prices || {},
208 }
209 return variants
210 }, {} as PriceListUpdateProductVariantsSchema) || {},
211 }
212 }
213
214 return record
215 }
216
217 type PriceObject = {
218 variantId: string
219 currencyCode: string
220 regionId?: string
221 amount: number
222 id?: string | null
223 minQuantity?: number
224 maxQuantity?: number
225 }
226
227 export function convertToPriceArray(
228 data: PriceListUpdateProductsSchema,
229 regions: HttpTypes.AdminRegion[]
230 ) {
231 const prices: PriceObject[] = []
232
233 const regionCurrencyMap = regions.reduce((map, region) => {
234 map[region.id] = region.currency_code
235 return map
236 }, {} as Record<string, string>)
237
238 for (const [_productId, product] of Object.entries(data || {})) {
239 const { variants } = product || {}
240
241 for (const [variantId, variant] of Object.entries(variants || {})) {
242 const {
243 currency_prices: variantCurrencyPrices,
244 region_prices: variantRegionPrices,
245 } = variant || {}
246
247 const processCurrencyPrices = (
248 currencyPricesMap:
249 | Record<string, PriceListUpdateCurrencyPrice[] | undefined>
250 | undefined
251 ) => {
252 for (const [currencyCode, currencyPrices] of Object.entries(
253 currencyPricesMap || {}
254 )) {
255 ;(
256 (currencyPrices as PriceListUpdateCurrencyPrice[] | undefined) || []
257 ).forEach((currencyPrice: PriceListUpdateCurrencyPrice) => {
258 if (
259 currencyPrice?.amount !== "" &&
260 typeof currencyPrice?.amount !== "undefined"
261 ) {
262 prices.push({
263 variantId,
264 currencyCode,
265 amount: castNumber(currencyPrice.amount),
266 id: currencyPrice.id,
267 minQuantity: currencyPrice.min_quantity
268 ? castNumber(currencyPrice.min_quantity)
269 : undefined,
270 maxQuantity: currencyPrice.max_quantity
271 ? castNumber(currencyPrice.max_quantity)
272 : undefined,
273 })
274 }
275 })
276 }
277 }
278
279 processCurrencyPrices(variantCurrencyPrices)
280 processCurrencyPrices(variant.conditional_currency_prices)
281
282 const processRegionPrices = (
283 regionPricesMap:
284 | Record<string, PriceListUpdateRegionPrice[] | undefined>
285 | undefined
286 ) => {
287 for (const [regionId, regionPrices] of Object.entries(
288 regionPricesMap || {}
289 )) {
290 ;(
291 (regionPrices as PriceListUpdateRegionPrice[] | undefined) || []
292 ).forEach((regionPrice: PriceListUpdateRegionPrice) => {
293 if (
294 regionPrice?.amount !== "" &&
295 typeof regionPrice?.amount !== "undefined"
296 ) {
297 prices.push({
298 variantId,
299 regionId,
300 currencyCode: regionCurrencyMap[regionId],
301 amount: castNumber(regionPrice.amount),
302 id: regionPrice.id,
303 minQuantity: regionPrice.min_quantity
304 ? castNumber(regionPrice.min_quantity)
305 : undefined,
306 maxQuantity: regionPrice.max_quantity
307 ? castNumber(regionPrice.max_quantity)
308 : undefined,
309 })
310 }
311 })
312 }
313 }
314
315 processRegionPrices(variantRegionPrices)
316 processRegionPrices(variant.conditional_region_prices)
317 }
318 }
319
320 return prices
321 }
322
323 function createMapKey(obj: PriceObject) {
324 if (obj.id) {
325 return `id-${obj.id}`
326 }
327 return `${obj.variantId}-${obj.currencyCode}-${obj.regionId || "none"}-${
328 obj.amount
329 }-${obj.minQuantity || "none"}-${obj.maxQuantity || "none"}`
330 }
331
332 function buildPriceRules(price: PriceObject): Record<string, string> {
333 return {
334 ...(price.regionId ? { region_id: price.regionId } : {}),
335 ...(price.minQuantity
336 ? { min_quantity: price.minQuantity.toString() }
337 : {}),
338 ...(price.maxQuantity
339 ? { max_quantity: price.maxQuantity.toString() }
340 : {}),
341 }
342 }
343
344 export function comparePrices(
345 initialPrices: PriceObject[],
346 newPrices: PriceObject[]
347 ) {
348 const pricesToUpdate: HttpTypes.AdminUpdatePriceListPrice[] = []
349 const pricesToCreate: HttpTypes.AdminCreatePriceListPrice[] = []
350 const pricesToDelete: string[] = []
351
352 const initialPriceMap = initialPrices.reduce((map, price) => {
353 map[createMapKey(price)] = price
354 return map
355 }, {} as Record<string, (typeof initialPrices)[0]>)
356
357 const newPriceMap = newPrices.reduce((map, price) => {
358 map[createMapKey(price)] = price
359 return map
360 }, {} as Record<string, (typeof newPrices)[0]>)
361
362 const keys = new Set([
363 ...Object.keys(initialPriceMap),
364 ...Object.keys(newPriceMap),
365 ])
366
367 for (const key of keys) {
368 const initialPrice = initialPriceMap[key]
369 const newPrice = newPriceMap[key]
370
371 if (initialPrice && newPrice) {
372 if (isNaN(newPrice.amount) && newPrice.id) {
373 pricesToDelete.push(newPrice.id)
374 } else if (
375 initialPrice.amount !== newPrice.amount ||
376 initialPrice.minQuantity !== newPrice.minQuantity ||
377 initialPrice.maxQuantity !== newPrice.maxQuantity
378 ) {
379 if (newPrice.id) {
380 const rules = buildPriceRules(newPrice)
381
382 pricesToUpdate.push({
383 id: newPrice.id,
384 variant_id: newPrice.variantId,
385 currency_code: newPrice.currencyCode,
386 amount: newPrice.amount,
387 rules: Object.keys(rules).length > 0 ? rules : undefined,
388 })
389 }
390 }
391 }
392
393 if (!initialPrice && newPrice) {
394 const rules = buildPriceRules(newPrice)
395
396 pricesToCreate.push({
397 variant_id: newPrice.variantId,
398 currency_code: newPrice.currencyCode,
399 amount: newPrice.amount,
400 rules: Object.keys(rules).length > 0 ? rules : undefined,
401 })
402 }
403
404 if (initialPrice && !newPrice && initialPrice.id) {
405 pricesToDelete.push(initialPrice.id)
406 }
407 }
408
409 return { pricesToDelete, pricesToCreate, pricesToUpdate }
410 }
411
412 export function sortPrices(
413 data: PriceListUpdateProductsSchema,
414 initialValue: PriceListUpdateProductsSchema,
415 regions: HttpTypes.AdminRegion[]
416 ) {
417 const initialPrices = convertToPriceArray(initialValue, regions)
418 const newPrices = convertToPriceArray(data, regions)
419
420 return comparePrices(initialPrices, newPrices)
421 }
422
423 export function formatQuantityPrices(
424 prices: {
425 amount?: string
426 min_quantity?: string | null
427 max_quantity?: string | null
428 id?: string
429 }[]
430 ): PriceListUpdateCurrencyPrice[] {
431 return prices
432 .filter((p) => p.amount && p.amount.trim() !== "")
433 .map((p) => ({
434 ...p,
435 amount: castNumber(p.amount!),
436 min_quantity: p.min_quantity ? castNumber(p.min_quantity) : undefined,
437 max_quantity: p.max_quantity ? castNumber(p.max_quantity) : undefined,
438 }))
439 }