1 import {
2 ArchiveBox,
3 CurrencyDollar,
4 Map,
5 PencilSquare,
6 Plus,
7 Trash,
8 TriangleDownMini,
9 } from "@medusajs/icons"
10 import { HttpTypes } from "@medusajs/types"
11 import {
12 Badge,
13 Container,
14 Divider,
15 Heading,
16 IconButton,
17 StatusBadge,
18 Text,
19 toast,
20 usePrompt,
21 } from "@medusajs/ui"
22 import { useMemo, useState } from "react"
23 import { useTranslation } from "react-i18next"
24 import { useNavigate } from "react-router-dom"
25
26 import { ActionMenu } from "../../../../../components/common/action-menu"
27 import { NoRecords } from "../../../../../components/common/empty-table-content"
28 import { IconAvatar } from "../../../../../components/common/icon-avatar"
29 import { LinkButton } from "../../../../../components/common/link-button"
30 import { ListSummary } from "../../../../../components/common/list-summary"
31 import {
32 useDeleteFulfillmentServiceZone,
33 useDeleteFulfillmentSet,
34 } from "../../../../../hooks/api/fulfillment-sets"
35 import { useDeleteShippingOption } from "../../../../../hooks/api/shipping-options"
36 import {
37 useCreateStockLocationFulfillmentSet,
38 useDeleteStockLocation,
39 } from "../../../../../hooks/api/stock-locations"
40 import { getFormattedAddress } from "../../../../../lib/addresses"
41 import {
42 StaticCountry,
43 countries as staticCountries,
44 } from "../../../../../lib/data/countries"
45 import { formatProvider } from "../../../../../lib/format-provider"
46 import {
47 isOptionEnabledInStore,
48 isReturnOption,
49 } from "../../../../../lib/shipping-options"
50 import {
51 FulfillmentSetType,
52 ShippingOptionPriceType,
53 } from "../../../common/constants"
54
55 type LocationGeneralSectionProps = {
56 location: HttpTypes.AdminStockLocation
57 }
58
59 export const LocationGeneralSection = ({
60 location,
61 }: LocationGeneralSectionProps) => {
62 return (
63 <>
64 <Container className="p-0">
65 <div className="flex items-center justify-between px-6 py-4">
66 <div>
67 <Heading>{location.name}</Heading>
68 <Text className="text-ui-fg-subtle txt-small">
69 {getFormattedAddress({
70 address: location.address as
71 | HttpTypes.AdminOrderAddress
72 | undefined,
73 }).join(", ")}
74 </Text>
75 </div>
76 <Actions location={location} />
77 </div>
78 </Container>
79
80 <FulfillmentSet
81 locationId={location.id}
82 locationName={location.name}
83 type={FulfillmentSetType.Pickup}
84 fulfillmentSet={location.fulfillment_sets?.find(
85 (f) => f.type === FulfillmentSetType.Pickup
86 )}
87 />
88
89 <FulfillmentSet
90 locationId={location.id}
91 locationName={location.name}
92 type={FulfillmentSetType.Shipping}
93 fulfillmentSet={location.fulfillment_sets?.find(
94 (f) => f.type === FulfillmentSetType.Shipping
95 )}
96 />
97 </>
98 )
99 }
100
101 type ShippingOptionProps = {
102 option: HttpTypes.AdminShippingOption
103 fulfillmentSetId: string
104 locationId: string
105 }
106
107 function ShippingOption({
108 option,
109 fulfillmentSetId,
110 locationId,
111 }: ShippingOptionProps) {
112 const prompt = usePrompt()
113 const { t } = useTranslation()
114
115 const isStoreOption = isOptionEnabledInStore(option)
116
117 const { mutateAsync } = useDeleteShippingOption(option.id)
118
119 const handleDelete = async () => {
120 const res = await prompt({
121 title: t("general.areYouSure"),
122 description: t("stockLocations.shippingOptions.delete.confirmation", {
123 name: option.name,
124 }),
125 verificationInstruction: t("general.typeToConfirm"),
126 verificationText: option.name,
127 confirmText: t("actions.delete"),
128 cancelText: t("actions.cancel"),
129 })
130
131 if (!res) {
132 return
133 }
134
135 await mutateAsync(undefined, {
136 onSuccess: () => {
137 toast.success(
138 t("stockLocations.shippingOptions.delete.successToast", {
139 name: option.name,
140 })
141 )
142 },
143 onError: (e) => {
144 toast.error(e.message)
145 },
146 })
147 }
148
149 return (
150 <div className="flex items-center justify-between px-3 py-2">
151 <div className="flex-1">
152 <Text size="small" weight="plus">
153 {option.name} - {option.shipping_profile.name} (
154 {formatProvider(option.provider_id)})
155 </Text>
156 </div>
157 <Badge
158 className="mr-4"
159 color={isStoreOption ? "grey" : "purple"}
160 size="2xsmall"
161 rounded="full"
162 >
163 {isStoreOption ? t("general.store") : t("general.admin")}
164 </Badge>
165 <ActionMenu
166 groups={[
167 {
168 actions: [
169 {
170 icon: <PencilSquare />,
171 label: t("stockLocations.shippingOptions.edit.action"),
172 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${option.service_zone_id}/shipping-option/${option.id}/edit`,
173 },
174 {
175 label: t("stockLocations.shippingOptions.pricing.action"),
176 icon: <CurrencyDollar />,
177 disabled:
178 option.price_type === ShippingOptionPriceType.Calculated,
179 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${option.service_zone_id}/shipping-option/${option.id}/pricing`,
180 },
181 ],
182 },
183 {
184 actions: [
185 {
186 label: t("actions.delete"),
187 icon: <Trash />,
188 onClick: handleDelete,
189 },
190 ],
191 },
192 ]}
193 />
194 </div>
195 )
196 }
197
198 type ServiceZoneOptionsProps = {
199 zone: HttpTypes.AdminServiceZone
200 locationId: string
201 fulfillmentSetId: string
202 type: FulfillmentSetType
203 }
204
205 function ServiceZoneOptions({
206 zone,
207 locationId,
208 fulfillmentSetId,
209 type,
210 }: ServiceZoneOptionsProps) {
211 const { t } = useTranslation()
212
213 const shippingOptions = zone.shipping_options.filter(
214 (o) => !isReturnOption(o)
215 )
216
217 const returnOptions = zone.shipping_options.filter((o) => isReturnOption(o))
218
219 return (
220 <div>
221 <Divider variant="dashed" />
222 <div className="flex flex-col gap-y-4 px-6 py-4">
223 <div className="item-center flex justify-between">
224 <span className="text-ui-fg-subtle txt-small self-center font-medium">
225 {t(`stockLocations.shippingOptions.create.${type}.label`)}
226 </span>
227 <LinkButton
228 to={`/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/shipping-option/create`}
229 >
230 {t("stockLocations.shippingOptions.create.action")}
231 </LinkButton>
232 </div>
233
234 {!!shippingOptions.length && (
235 <div className="shadow-elevation-card-rest bg-ui-bg-subtle grid divide-y rounded-md">
236 {shippingOptions.map((o) => (
237 <ShippingOption
238 key={o.id}
239 option={o}
240 locationId={locationId}
241 fulfillmentSetId={fulfillmentSetId}
242 />
243 ))}
244 </div>
245 )}
246 </div>
247
248 <Divider variant="dashed" />
249
250 <div className="flex flex-col gap-y-4 px-6 py-4">
251 <div className="item-center flex justify-between">
252 <span className="text-ui-fg-subtle txt-small self-center font-medium">
253 {t("stockLocations.shippingOptions.create.returns.label")}
254 </span>
255 <LinkButton
256 to={`/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/shipping-option/create?is_return`}
257 >
258 {t("stockLocations.shippingOptions.create.action")}
259 </LinkButton>
260 </div>
261
262 {!!returnOptions.length && (
263 <div className="shadow-elevation-card-rest bg-ui-bg-subtle grid divide-y rounded-md">
264 {returnOptions.map((o) => (
265 <ShippingOption
266 key={o.id}
267 option={o}
268 locationId={locationId}
269 fulfillmentSetId={fulfillmentSetId}
270 />
271 ))}
272 </div>
273 )}
274 </div>
275 </div>
276 )
277 }
278
279 type ServiceZoneProps = {
280 zone: HttpTypes.AdminServiceZone
281 locationId: string
282 fulfillmentSetId: string
283 type: FulfillmentSetType
284 }
285
286 function ServiceZone({
287 zone,
288 locationId,
289 fulfillmentSetId,
290 type,
291 }: ServiceZoneProps) {
292 const { t } = useTranslation()
293 const prompt = usePrompt()
294 const [open, setOpen] = useState(true)
295
296 const { mutateAsync: deleteZone } = useDeleteFulfillmentServiceZone(
297 fulfillmentSetId,
298 zone.id
299 )
300
301 const handleDelete = async () => {
302 const res = await prompt({
303 title: t("general.areYouSure"),
304 description: t("stockLocations.serviceZones.delete.confirmation", {
305 name: zone.name,
306 }),
307 confirmText: t("actions.delete"),
308 cancelText: t("actions.cancel"),
309 })
310
311 if (!res) {
312 return
313 }
314
315 await deleteZone(undefined, {
316 onError: (e) => {
317 toast.error(e.message)
318 },
319 onSuccess: () => {
320 toast.success(
321 t("stockLocations.serviceZones.delete.successToast", {
322 name: zone.name,
323 })
324 )
325 },
326 })
327 }
328
329 const countries = useMemo(() => {
330 const countryGeoZones = zone.geo_zones.filter((g) => g.type === "country")
331
332 const countries = countryGeoZones
333 .map(({ country_code }) =>
334 staticCountries.find((c) => c.iso_2 === country_code)
335 )
336 .filter((c) => !!c) as StaticCountry[]
337
338 if (
339 process.env.NODE_ENV === "development" &&
340 countryGeoZones.length !== countries.length
341 ) {
342 console.warn(
343 "Some countries are missing in the static countries list",
344 countryGeoZones
345 .filter((g) => !countries.find((c) => c.iso_2 === g.country_code))
346 .map((g) => g.country_code)
347 )
348 }
349
350 return countries.sort((c1, c2) => c1.name.localeCompare(c2.name))
351 }, [zone.geo_zones])
352
353 const [shippingOptionsCount, returnOptionsCount] = useMemo(() => {
354 const options = zone.shipping_options
355
356 const optionsCount = options.filter((o) => !isReturnOption(o)).length
357
358 const returnOptionsCount = options.filter(isReturnOption).length
359
360 return [optionsCount, returnOptionsCount]
361 }, [zone.shipping_options])
362
363 return (
364 <div className="flex flex-col">
365 <div className="flex flex-row items-center justify-between gap-x-4 px-6 py-4">
366 <IconAvatar>
367 <Map />
368 </IconAvatar>
369
370 <div className="grow-1 flex flex-1 flex-col">
371 <Text size="small" leading="compact" weight="plus">
372 {zone.name}
373 </Text>
374 <div className="flex items-center gap-2">
375 <ListSummary
376 variant="base"
377 list={countries.map((c) => c.display_name)}
378 inline
379 n={1}
380 />
381 <span>·</span>
382 <Text className="text-ui-fg-subtle txt-small">
383 {t(`stockLocations.shippingOptions.fields.count.${type}`, {
384 count: shippingOptionsCount,
385 })}
386 </Text>
387 <span>·</span>
388 <Text className="text-ui-fg-subtle txt-small">
389 {t("stockLocations.shippingOptions.fields.count.returns", {
390 count: returnOptionsCount,
391 })}
392 </Text>
393 </div>
394 </div>
395
396 <div className="flex grow-0 items-center gap-4">
397 <IconButton
398 size="small"
399 onClick={() => setOpen((s) => !s)}
400 variant="transparent"
401 >
402 <TriangleDownMini
403 style={{
404 transform: `rotate(${!open ? 0 : 180}deg)`,
405 transition: ".2s transform ease-in-out",
406 }}
407 />
408 </IconButton>
409 <ActionMenu
410 groups={[
411 {
412 actions: [
413 {
414 label: t("actions.edit"),
415 icon: <PencilSquare />,
416 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/edit`,
417 },
418 {
419 label: t("stockLocations.serviceZones.manageAreas.action"),
420 icon: <Map />,
421 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/areas`,
422 },
423 ],
424 },
425 {
426 actions: [
427 {
428 label: t("actions.delete"),
429 icon: <Trash />,
430 onClick: handleDelete,
431 },
432 ],
433 },
434 ]}
435 />
436 </div>
437 </div>
438 {open && (
439 <ServiceZoneOptions
440 fulfillmentSetId={fulfillmentSetId}
441 locationId={locationId}
442 type={type}
443 zone={zone}
444 />
445 )}
446 </div>
447 )
448 }
449
450 type FulfillmentSetProps = {
451 fulfillmentSet?: HttpTypes.AdminFulfillmentSet
452 locationName: string
453 locationId: string
454 type: FulfillmentSetType
455 }
456
457 function FulfillmentSet(props: FulfillmentSetProps) {
458 const { t } = useTranslation()
459 const prompt = usePrompt()
460
461 const { fulfillmentSet, locationName, locationId, type } = props
462
463 const fulfillmentSetExists = !!fulfillmentSet
464
465 const hasServiceZones = !!fulfillmentSet?.service_zones.length
466
467 const { mutateAsync: createFulfillmentSet } =
468 useCreateStockLocationFulfillmentSet(locationId)
469
470 const { mutateAsync: deleteFulfillmentSet } = useDeleteFulfillmentSet(
471 fulfillmentSet?.id!
472 )
473
474 const handleCreate = async () => {
475 await createFulfillmentSet(
476 {
477 name: `${locationName} ${
478 type === FulfillmentSetType.Pickup ? "pick up" : type
479 }`,
480 type,
481 },
482 {
483 onSuccess: () => {
484 toast.success(t(`stockLocations.fulfillmentSets.enable.${type}`))
485 },
486 onError: (e) => {
487 toast.error(e.message)
488 },
489 }
490 )
491 }
492
493 const handleDelete = async () => {
494 const res = await prompt({
495 title: t("general.areYouSure"),
496 description: t(`stockLocations.fulfillmentSets.disable.confirmation`, {
497 name: fulfillmentSet?.name,
498 }),
499 confirmText: t("actions.disable"),
500 cancelText: t("actions.cancel"),
501 })
502
503 if (!res) {
504 return
505 }
506
507 await deleteFulfillmentSet(undefined, {
508 onSuccess: () => {
509 toast.success(t(`stockLocations.fulfillmentSets.disable.${type}`))
510 },
511 onError: (e) => {
512 toast.error(e.message)
513 },
514 })
515 }
516
517 const groups = fulfillmentSet
518 ? [
519 {
520 actions: [
521 {
522 icon: <Plus />,
523 label: t("stockLocations.serviceZones.create.action"),
524 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSet.id}/service-zones/create`,
525 },
526 ],
527 },
528 {
529 actions: [
530 {
531 icon: <Trash />,
532 label: t("actions.disable"),
533 onClick: handleDelete,
534 },
535 ],
536 },
537 ]
538 : [
539 {
540 actions: [
541 {
542 icon: <Plus />,
543 label: t("actions.enable"),
544 onClick: handleCreate,
545 },
546 ],
547 },
548 ]
549
550 return (
551 <Container className="p-0">
552 <div className="flex flex-col divide-y">
553 <div className="flex items-center justify-between px-6 py-4">
554 <Heading level="h2">
555 {t(`stockLocations.fulfillmentSets.${type}.header`)}
556 </Heading>
557 <div className="flex items-center gap-4">
558 <StatusBadge color={fulfillmentSetExists ? "green" : "grey"}>
559 {t(
560 fulfillmentSetExists ? "statuses.enabled" : "statuses.disabled"
561 )}
562 </StatusBadge>
563
564 <ActionMenu groups={groups} />
565 </div>
566 </div>
567
568 {fulfillmentSetExists && !hasServiceZones && (
569 <div className="flex items-center justify-center py-8 pt-6">
570 <NoRecords
571 message={t("stockLocations.serviceZones.fields.noRecords")}
572 className="h-fit"
573 action={{
574 to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSet.id}/service-zones/create`,
575 label: t("stockLocations.serviceZones.create.action"),
576 }}
577 />
578 </div>
579 )}
580
581 {hasServiceZones && (
582 <div className="flex flex-col divide-y">
583 {fulfillmentSet?.service_zones.map((zone) => (
584 <ServiceZone
585 zone={zone}
586 type={type}
587 key={zone.id}
588 locationId={locationId}
589 fulfillmentSetId={fulfillmentSet.id}
590 />
591 ))}
592 </div>
593 )}
594 </div>
595 </Container>
596 )
597 }
598
599 const Actions = ({ location }: { location: HttpTypes.AdminStockLocation }) => {
600 const navigate = useNavigate()
601 const { t } = useTranslation()
602 const { mutateAsync } = useDeleteStockLocation(location.id)
603 const prompt = usePrompt()
604
605 const handleDelete = async () => {
606 const res = await prompt({
607 title: t("general.areYouSure"),
608 description: t("stockLocations.delete.confirmation", {
609 name: location.name,
610 }),
611 verificationText: location.name,
612 verificationInstruction: t("general.typeToConfirm"),
613 confirmText: t("actions.delete"),
614 cancelText: t("actions.cancel"),
615 })
616
617 if (!res) {
618 return
619 }
620
621 await mutateAsync(undefined, {
622 onSuccess: () => {
623 toast.success(
624 t("stockLocations.create.successToast", {
625 name: location.name,
626 })
627 )
628 navigate("/settings/locations", { replace: true })
629 },
630 onError: (e) => {
631 toast.error(e.message)
632 },
633 })
634 }
635
636 return (
637 <ActionMenu
638 groups={[
639 {
640 actions: [
641 {
642 icon: <PencilSquare />,
643 label: t("actions.edit"),
644 to: `edit`,
645 },
646 {
647 icon: <ArchiveBox />,
648 label: t("stockLocations.edit.viewInventory"),
649 to: `/inventory?location_id=${location.id}`,
650 },
651 ],
652 },
653 {
654 actions: [
655 {
656 icon: <Trash />,
657 label: t("actions.delete"),
658 onClick: handleDelete,
659 },
660 ],
661 },
662 ]}
663 />
664 )
665 }