1 import { t } from "i18next"
2 import { z } from "zod"
3 import { castNumber } from "../../../lib/cast-number"
4
5 export const ConditionalPriceSchema = z
6 .object({
7 amount: z.union([z.string(), z.number()]),
8 gte: z.union([z.string(), z.number()]).nullish(),
9 lte: z.union([z.string(), z.number()]).nullish(),
10 lt: z.number().nullish(),
11 gt: z.number().nullish(),
12 eq: z.number().nullish(),
13 })
14 .refine((data) => data.amount !== "", {
15 message: t(
16 "stockLocations.shippingOptions.conditionalPrices.errors.amountRequired"
17 ),
18 path: ["amount"],
19 })
20 .refine(
21 (data) => {
22 const hasEqLtGt =
23 data.eq !== undefined || data.lt !== undefined || data.gt !== undefined
24
25 // The rule has operators that can only be managed using the API, so we should not validate this.
26 if (hasEqLtGt) {
27 return true
28 }
29
30 return (
31 (data.gte !== undefined && data.gte !== "") ||
32 (data.lte !== undefined && data.lte !== "")
33 )
34 },
35 {
36 message: t(
37 "stockLocations.shippingOptions.conditionalPrices.errors.minOrMaxRequired"
38 ),
39 path: ["gte"],
40 }
41 )
42 .refine(
43 (data) => {
44 if (
45 data.gte != null &&
46 data.gte !== "" &&
47 data.lte != null &&
48 data.lte !== ""
49 ) {
50 const gte = castNumber(data.gte)
51 const lte = castNumber(data.lte)
52 return gte <= lte
53 }
54 return true
55 },
56 {
57 message: t(
58 "stockLocations.shippingOptions.conditionalPrices.errors.minGreaterThanMax"
59 ),
60 path: ["gte"],
61 }
62 )
63
64 export type ConditionalPrice = z.infer<typeof ConditionalPriceSchema>
65
66 export const UpdateConditionalPriceSchema = ConditionalPriceSchema.and(
67 z.object({
68 id: z.string().optional(),
69 })
70 )
71
72 export type UpdateConditionalPrice = z.infer<
73 typeof UpdateConditionalPriceSchema
74 >
75
76 type RefinablePrice = {
77 amount: string | number
78 gte?: string | number | null | undefined
79 lte?: string | number | null | undefined
80 lt?: number | null | undefined
81 gt?: number | null | undefined
82 eq?: number | null | undefined
83 }
84
85 const parseBound = (value: string | number | null | undefined) => {
86 if (value === null || value === undefined || value === "") {
87 return undefined
88 }
89
90 return castNumber(value)
91 }
92
93 // Rules using eq/lt/gt operators can only be managed through the API, so we
94 // don't validate overlaps for them in the dashboard.
95 const hasCustomOperators = (price: RefinablePrice) =>
96 price.eq != null || price.lt != null || price.gt != null
97
98 function refineDuplicates(
99 data: {
100 prices: RefinablePrice[]
101 },
102 ctx: z.RefinementCtx
103 ) {
104 const prices = data.prices
105
106 for (let i = 0; i < prices.length; i++) {
107 for (let j = i + 1; j < prices.length; j++) {
108 const price1 = prices[i]
109 const price2 = prices[j]
110
111 if (hasCustomOperators(price1) || hasCustomOperators(price2)) {
112 continue
113 }
114
115 const lower1 = parseBound(price1.gte)
116 const upper1 = parseBound(price1.lte)
117 const lower2 = parseBound(price2.gte)
118 const upper2 = parseBound(price2.lte)
119
120 // A rule without any bound is invalid on its own (handled by another
121 // refinement), so skip the overlap comparison for it.
122 if (
123 (lower1 === undefined && upper1 === undefined) ||
124 (lower2 === undefined && upper2 === undefined)
125 ) {
126 continue
127 }
128
129 const start1 = lower1 ?? Number.NEGATIVE_INFINITY
130 const end1 = upper1 ?? Number.POSITIVE_INFINITY
131 const start2 = lower2 ?? Number.NEGATIVE_INFINITY
132 const end2 = upper2 ?? Number.POSITIVE_INFINITY
133
134 // Two cart item total ranges conflict only when they share at least one
135 // value. The price amount is intentionally not part of this check: the
136 // same amount can legitimately apply to multiple non-overlapping
137 // conditions.
138 const overlaps = start1 <= end2 && start2 <= end1
139
140 if (overlaps) {
141 addOverlappingConditionError(ctx, j)
142 }
143 }
144 }
145 }
146
147 export const CondtionalPriceRuleSchema = z
148 .object({
149 prices: z.array(ConditionalPriceSchema),
150 })
151 .superRefine(refineDuplicates)
152
153 export type CondtionalPriceRuleSchemaType = z.infer<
154 typeof CondtionalPriceRuleSchema
155 >
156
157 export const UpdateConditionalPriceRuleSchema = z
158 .object({
159 prices: z.array(UpdateConditionalPriceSchema),
160 })
161 .superRefine(refineDuplicates)
162
163 export type UpdateConditionalPriceRuleSchemaType = z.infer<
164 typeof UpdateConditionalPriceRuleSchema
165 >
166
167 const addOverlappingConditionError = (ctx: z.RefinementCtx, index: number) => {
168 ctx.addIssue({
169 code: z.ZodIssueCode.custom,
170 message: t(
171 "stockLocations.shippingOptions.conditionalPrices.errors.overlappingConditions"
172 ),
173 path: ["prices", index, "gte"],
174 })
175 }