1 import * as zod from "zod"
2
3 import { Button, Heading, Text, Textarea, toast } from "@medusajs/ui"
4 import {
5 RouteFocusModal,
6 useRouteModal,
7 } from "../../../../../components/modals"
8
9 import { zodResolver } from "@hookform/resolvers/zod"
10 import { HttpTypes } from "@medusajs/types"
11 import { useForm } from "react-hook-form"
12 import { useTranslation } from "react-i18next"
13 import { Form } from "../../../../../components/common/form"
14 import { Combobox } from "../../../../../components/inputs/combobox"
15 import { QuantityInput } from "../../../../../components/inputs/quantity-input"
16 import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
17 import { useComboboxData } from "../../../../../hooks/use-combobox-data"
18 import { sdk } from "../../../../../lib/client"
19 import { formatQuantity } from "../../../../../lib/format-quantity"
20 import { useCreateReservationItem } from "../../../../../hooks/api/reservations"
21 import { useStockLocations } from "../../../../../hooks/api/stock-locations"
22 import { inventoryItemsQueryKeys } from "../../../../../hooks/api/inventory"
23
24 export const CreateReservationSchema = zod.object({
25 inventory_item_id: zod.string().min(1),
26 location_id: zod.string().min(1),
27 quantity: zod.number().positive(),
28 description: zod.string().optional(),
29 })
30
31 const AttributeGridRow = ({
32 title,
33 value,
34 }: {
35 title: string
36 value: string | number
37 }) => {
38 return (
39 <div className="grid grid-cols-2 divide-x">
40 <Text className="px-2 py-1.5" size="small" leading="compact">
41 {title}
42 </Text>
43 <Text className="px-2 py-1.5" size="small" leading="compact">
44 {value}
45 </Text>
46 </div>
47 )
48 }
49
50 export const ReservationCreateForm = (props: { inventoryItemId?: string }) => {
51 const { t } = useTranslation()
52 const { handleSuccess } = useRouteModal()
53 const form = useForm<zod.infer<typeof CreateReservationSchema>>({
54 defaultValues: {
55 inventory_item_id: props.inventoryItemId || "",
56 location_id: "",
57 quantity: 0,
58 description: "",
59 },
60 resolver: zodResolver(CreateReservationSchema),
61 })
62
63 const inventoryItemId = form.watch("inventory_item_id")
64
65 const inventoryItems = useComboboxData({
66 queryKey: inventoryItemsQueryKeys.list(),
67 queryFn: (params) => sdk.admin.inventoryItem.list(params),
68 getOptions: (data) =>
69 data.inventory_items.map((inventoryItem) => ({
70 label: inventoryItem.title ?? inventoryItem.sku!,
71 value: inventoryItem.id,
72 inventoryItem,
73 })),
74 defaultValueKey: "id",
75 defaultValue: props.inventoryItemId,
76 selectedValue: inventoryItemId,
77 })
78
79 const selectedInventoryItem = inventoryItems.options.find(
80 (option) => option.value === inventoryItemId
81 )?.inventoryItem as
82 | HttpTypes.AdminInventoryItemResponse["inventory_item"]
83 | undefined
84
85 const locationId = form.watch("location_id")
86 const selectedLocationLevel = selectedInventoryItem?.location_levels?.find(
87 (it) => it.location_id === locationId
88 )
89
90 const quantity = form.watch("quantity")
91
92 const { stock_locations } = useStockLocations(
93 {
94 id:
95 selectedInventoryItem?.location_levels?.map(
96 (level: HttpTypes.AdminInventoryLevel) => level.location_id
97 ) ?? [],
98 },
99 {
100 enabled: !!selectedInventoryItem,
101 }
102 )
103
104 const { mutateAsync, isPending } = useCreateReservationItem()
105
106 const handleSubmit = form.handleSubmit(async (data) => {
107 const max = selectedLocationLevel?.available_quantity
108 ? selectedLocationLevel.available_quantity
109 : 0
110
111 if (!selectedLocationLevel?.available_quantity) {
112 form.setError("quantity", {
113 type: "manual",
114 message: t("inventory.reservation.errors.noAvaliableQuantity"),
115 })
116
117 return
118 }
119
120 if (data.quantity > max) {
121 form.setError("quantity", {
122 type: "manual",
123 message: t("inventory.reservation.errors.quantityOutOfRange", {
124 max: max,
125 }),
126 })
127
128 return
129 }
130
131 await mutateAsync(data, {
132 onSuccess: ({ reservation }) => {
133 toast.success(t("inventory.reservation.successToast"))
134 handleSuccess(
135 props.inventoryItemId
136 ? `/inventory/${props.inventoryItemId}`
137 : `/reservations/${reservation.id}`
138 )
139 },
140 onError: (e) => {
141 toast.error(e.message)
142 },
143 })
144 })
145
146 return (
147 <RouteFocusModal.Form form={form}>
148 <KeyboundForm
149 onSubmit={handleSubmit}
150 className="flex size-full flex-col overflow-hidden"
151 >
152 <RouteFocusModal.Header />
153 <RouteFocusModal.Body className="flex flex-1 flex-col items-center overflow-auto py-16">
154 <div className="flex w-full max-w-[720px] flex-col gap-y-8">
155 <Heading>{t("inventory.reservation.create")}</Heading>
156 <div className="grid grid-cols-2 gap-4">
157 <Form.Field
158 key={"inventory_item_id"}
159 control={form.control}
160 name={"inventory_item_id"}
161 render={({ field: { value, onChange, ...field } }) => {
162 return (
163 <Form.Item>
164 <Form.Label>
165 {t("inventory.reservation.itemToReserve")}
166 </Form.Label>
167 <Form.Control>
168 <Combobox
169 value={value}
170 onChange={(v) => {
171 onChange(v)
172 }}
173 {...field}
174 disabled={!!props.inventoryItemId}
175 options={inventoryItems.options}
176 searchValue={inventoryItems.searchValue}
177 onSearchValueChange={
178 inventoryItems.onSearchValueChange
179 }
180 fetchNextPage={inventoryItems.fetchNextPage}
181 />
182 </Form.Control>
183 </Form.Item>
184 )
185 }}
186 />
187 <Form.Field
188 key={"location_id"}
189 control={form.control}
190 name={"location_id"}
191 render={({ field: { value, onChange, ...field } }) => {
192 return (
193 <Form.Item>
194 <Form.Label>{t("fields.location")}</Form.Label>
195 <Form.Control>
196 <Combobox
197 value={value}
198 onChange={(v) => {
199 onChange(v)
200 }}
201 {...field}
202 disabled={!inventoryItemId}
203 options={(stock_locations ?? []).map(
204 (stockLocation) => ({
205 label: stockLocation.name,
206 value: stockLocation.id,
207 })
208 )}
209 />
210 </Form.Control>
211 </Form.Item>
212 )
213 }}
214 />
215 </div>
216 <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-4 divide-y rounded-lg">
217 <AttributeGridRow
218 title={t("fields.title")}
219 value={
220 selectedInventoryItem?.title ??
221 selectedInventoryItem?.sku ??
222 "-"
223 }
224 />
225 <AttributeGridRow
226 title={t("fields.sku")}
227 value={selectedInventoryItem?.sku ?? "-"}
228 />
229 <AttributeGridRow
230 title={t("fields.inStock")}
231 value={formatQuantity(
232 selectedLocationLevel?.stocked_quantity,
233 selectedInventoryItem?.unit_of_measure
234 )}
235 />
236 <AttributeGridRow
237 title={t("inventory.available")}
238 value={
239 selectedLocationLevel?.available_quantity
240 ? formatQuantity(
241 selectedLocationLevel.available_quantity -
242 (quantity || 0),
243 selectedInventoryItem?.unit_of_measure
244 )
245 : "-"
246 }
247 />
248 </div>
249 <div className="w-full lg:w-1/2">
250 <Form.Field
251 control={form.control}
252 name="quantity"
253 render={({ field: { onChange, value, ...field } }) => {
254 return (
255 <Form.Item>
256 <Form.Label>{t("fields.quantity")}</Form.Label>
257 <Form.Control>
258 <QuantityInput
259 step="any"
260 unitOfMeasure={selectedInventoryItem?.unit_of_measure}
261 placeholder={t(
262 "inventory.reservation.quantityPlaceholder"
263 )}
264 value={value}
265 onChange={(e) => {
266 const value = e.target.value
267
268 if (value === "") {
269 onChange(null)
270 } else {
271 onChange(parseFloat(value))
272 }
273 }}
274 {...field}
275 disabled={!inventoryItemId || !locationId}
276 />
277 </Form.Control>
278 <Form.ErrorMessage />
279 </Form.Item>
280 )
281 }}
282 />
283 </div>
284 <Form.Field
285 control={form.control}
286 name="description"
287 render={({ field }) => {
288 return (
289 <Form.Item>
290 <Form.Label optional>{t("fields.description")}</Form.Label>
291 <Form.Control>
292 <Textarea
293 {...field}
294 disabled={!inventoryItemId || !locationId}
295 placeholder={t(
296 "inventory.reservation.descriptionPlaceholder"
297 )}
298 />
299 </Form.Control>
300 <Form.ErrorMessage />
301 </Form.Item>
302 )
303 }}
304 />
305 </div>
306 </RouteFocusModal.Body>
307 <RouteFocusModal.Footer>
308 <div className="flex items-center justify-end gap-x-2">
309 <RouteFocusModal.Close asChild>
310 <Button variant="secondary" size="small">
311 {t("actions.cancel")}
312 </Button>
313 </RouteFocusModal.Close>
314 <Button
315 type="submit"
316 variant="primary"
317 size="small"
318 isLoading={isPending}
319 >
320 {t("actions.create")}
321 </Button>
322 </div>
323 </RouteFocusModal.Footer>
324 </KeyboundForm>
325 </RouteFocusModal.Form>
326 )
327 }