@medusajs/draft-order 2.22.6 → 2.22.7-preview-20261113084204

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,7 @@ import { Tooltip, DropdownMenu, clx, IconButton, useDataTable, DataTable as Data
6
6
  import { useQuery, useQueryClient, useMutation, keepPreviousData, useInfiniteQuery } from "@tanstack/react-query";
7
7
  import React, { useState, useCallback, useMemo, createContext, forwardRef, useId, useContext, useTransition, useRef, useImperativeHandle, useDeferredValue, Fragment, useEffect, Suspense } from "react";
8
8
  import { useSearchParams, Link, useNavigate, useBlocker, useLocation, useParams } from "react-router-dom";
9
- import { EllipsisHorizontal, XMark, InformationCircleSolid, XMarkMini, TrianglesMini, CheckMini, EllipseMiniSolid, PlusMini, ExclamationCircleSolid, ArrowPath, FlyingBox, CurrencyDollar, Envelope, Channels, Trash, ArrowUpRightOnBox, TriangleDownMini, Check, SquareTwoStack, Photo, TriangleRightMini, Shopping, Buildings, TruckFast, Plus, ReceiptPercent, Minus, PencilSquare, Component, EllipsisVertical, ArrowUpMini, ArrowDownMini } from "@medusajs/icons";
9
+ import { EllipsisHorizontal, XMark, InformationCircleSolid, XMarkMini, TrianglesMini, CheckMini, EllipseMiniSolid, PlusMini, ExclamationCircleSolid, ArrowPath, FlyingBox, CurrencyDollar, Envelope, Channels, Trash, ArrowUpRightOnBox, TriangleDownMini, Check, SquareTwoStack, Photo, TriangleRightMini, Shopping, Buildings, TruckFast, Plus, ReceiptPercent, EllipsisVertical, ArrowUpMini, ArrowDownMini, Minus, PencilSquare, Component } from "@medusajs/icons";
10
10
  import Medusa from "@medusajs/js-sdk";
11
11
  import { format, formatDistance, sub, subDays, subMonths } from "date-fns";
12
12
  import { enUS } from "date-fns/locale";
@@ -6379,1482 +6379,864 @@ const schema$3 = z.object({
6379
6379
  const handle$7 = {
6380
6380
  permissions: EDIT_DRAFT_ORDER_PERMISSIONS
6381
6381
  };
6382
- const NumberInput = forwardRef(
6383
- ({
6384
- value,
6385
- onChange,
6386
- size = "base",
6387
- min = 0,
6388
- max = 100,
6389
- step = 1,
6390
- className,
6391
- disabled,
6392
- ...props
6393
- }, ref) => {
6394
- const handleChange = (event) => {
6395
- const newValue = event.target.value === "" ? min : Number(event.target.value);
6396
- if (!isNaN(newValue) && (max === void 0 || newValue <= max) && (min === void 0 || newValue >= min)) {
6397
- onChange(newValue);
6398
- }
6399
- };
6400
- const handleIncrement = () => {
6401
- const newValue = value + step;
6402
- if (max === void 0 || newValue <= max) {
6403
- onChange(newValue);
6404
- }
6405
- };
6406
- const handleDecrement = () => {
6407
- const newValue = value - step;
6408
- if (min === void 0 || newValue >= min) {
6409
- onChange(newValue);
6410
- }
6411
- };
6382
+ const InlineTip = forwardRef(
6383
+ ({ variant = "tip", label, className, children, ...props }, ref) => {
6384
+ const labelValue = label || (variant === "warning" ? "Warning" : "Tip");
6412
6385
  return /* @__PURE__ */ jsxs(
6413
6386
  "div",
6414
6387
  {
6388
+ ref,
6415
6389
  className: clx(
6416
- "inline-flex rounded-md bg-ui-bg-field shadow-borders-base overflow-hidden divide-x transition-fg",
6417
- "[&:has(input:focus)]:shadow-borders-interactive-with-active",
6418
- {
6419
- "h-7": size === "small",
6420
- "h-8": size === "base"
6421
- },
6390
+ "bg-ui-bg-component txt-small text-ui-fg-subtle grid grid-cols-[4px_1fr] items-start gap-3 rounded-lg border p-3",
6422
6391
  className
6423
6392
  ),
6393
+ ...props,
6424
6394
  children: [
6425
6395
  /* @__PURE__ */ jsx(
6426
- "input",
6427
- {
6428
- ref,
6429
- type: "number",
6430
- value,
6431
- onChange: handleChange,
6432
- min,
6433
- max,
6434
- step,
6435
- className: clx(
6436
- "flex-1 px-2 py-1 bg-transparent txt-compact-small text-ui-fg-base outline-none [appearance:textfield]",
6437
- "[&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",
6438
- "placeholder:text-ui-fg-muted"
6439
- ),
6440
- ...props
6441
- }
6442
- ),
6443
- /* @__PURE__ */ jsxs(
6444
- "button",
6396
+ "div",
6445
6397
  {
6446
- className: clx(
6447
- "flex items-center justify-center outline-none transition-fg",
6448
- "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
6449
- "focus:bg-ui-bg-field-component-hover",
6450
- "hover:bg-ui-bg-field-component-hover",
6451
- {
6452
- "size-7": size === "small",
6453
- "size-8": size === "base"
6454
- }
6455
- ),
6456
- type: "button",
6457
- onClick: handleDecrement,
6458
- disabled: min !== void 0 && value <= min || disabled,
6459
- children: [
6460
- /* @__PURE__ */ jsx(Minus, {}),
6461
- /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Decrease by ${step}` })
6462
- ]
6398
+ role: "presentation",
6399
+ className: clx("w-4px bg-ui-tag-neutral-icon h-full rounded-full", {
6400
+ "bg-ui-tag-orange-icon": variant === "warning"
6401
+ })
6463
6402
  }
6464
6403
  ),
6465
- /* @__PURE__ */ jsxs(
6466
- "button",
6467
- {
6468
- className: clx(
6469
- "flex items-center justify-center outline-none transition-fg",
6470
- "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
6471
- "focus:bg-ui-bg-field-hover",
6472
- "hover:bg-ui-bg-field-hover",
6473
- {
6474
- "size-7": size === "small",
6475
- "size-8": size === "base"
6476
- }
6477
- ),
6478
- type: "button",
6479
- onClick: handleIncrement,
6480
- disabled: max !== void 0 && value >= max || disabled,
6481
- children: [
6482
- /* @__PURE__ */ jsx(Plus, {}),
6483
- /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Increase by ${step}` })
6484
- ]
6485
- }
6486
- )
6404
+ /* @__PURE__ */ jsxs("div", { className: "text-pretty", children: [
6405
+ /* @__PURE__ */ jsxs("strong", { className: "txt-small-plus text-ui-fg-base", children: [
6406
+ labelValue,
6407
+ ":"
6408
+ ] }),
6409
+ " ",
6410
+ children
6411
+ ] })
6487
6412
  ]
6488
6413
  }
6489
6414
  );
6490
6415
  }
6491
6416
  );
6492
- const PRODUCT_VARIANTS_QUERY_KEY = "product-variants";
6493
- const productVariantsQueryKeys = {
6494
- list: (query2) => [
6495
- PRODUCT_VARIANTS_QUERY_KEY,
6496
- query2 ? query2 : void 0
6497
- ]
6498
- };
6499
- const useProductVariants = (query2, options) => {
6500
- const { data, ...rest } = useQuery({
6501
- queryKey: productVariantsQueryKeys.list(query2),
6502
- queryFn: async () => await sdk.admin.productVariant.list(query2),
6503
- ...options
6504
- });
6505
- return { ...data, ...rest };
6506
- };
6507
- const useCancelOrderEdit = ({ preview }) => {
6508
- const { mutateAsync: cancelOrderEdit } = useDraftOrderCancelEdit(preview?.id);
6509
- const onCancel = useCallback(async () => {
6510
- if (!preview) {
6511
- return true;
6512
- }
6513
- let res = false;
6514
- await cancelOrderEdit(void 0, {
6515
- onError: (e) => {
6516
- toast.error(e.message);
6517
- },
6518
- onSuccess: () => {
6519
- res = true;
6520
- }
6521
- });
6522
- return res;
6523
- }, [preview, cancelOrderEdit]);
6524
- return { onCancel };
6525
- };
6526
- let IS_REQUEST_RUNNING = false;
6527
- const useInitiateOrderEdit = ({
6528
- preview
6529
- }) => {
6530
- const navigate = useNavigate();
6531
- const { mutateAsync } = useDraftOrderBeginEdit(preview?.id);
6532
- useEffect(() => {
6533
- async function run() {
6534
- if (IS_REQUEST_RUNNING || !preview) {
6535
- return;
6536
- }
6537
- if (preview.order_change) {
6538
- return;
6539
- }
6540
- IS_REQUEST_RUNNING = true;
6541
- await mutateAsync(void 0, {
6542
- onError: (e) => {
6543
- toast.error(e.message);
6544
- navigate(`/draft-orders/${preview.id}`, { replace: true });
6545
- return;
6546
- }
6547
- });
6548
- IS_REQUEST_RUNNING = false;
6549
- }
6550
- run();
6551
- }, [preview, navigate, mutateAsync]);
6552
- };
6553
- function convertNumber(value) {
6554
- return typeof value === "string" ? Number(value.replace(",", ".")) : value;
6555
- }
6556
- const STACKED_MODAL_ID = "items_stacked_modal";
6557
- const Items = () => {
6417
+ InlineTip.displayName = "InlineTip";
6418
+ const MetadataFieldSchema = z.object({
6419
+ key: z.string(),
6420
+ disabled: z.boolean().optional(),
6421
+ value: z.any()
6422
+ });
6423
+ const MetadataSchema = z.object({
6424
+ metadata: z.array(MetadataFieldSchema)
6425
+ });
6426
+ const Metadata = () => {
6558
6427
  const { id } = useParams();
6559
- const {
6560
- order: preview,
6561
- isPending: isPreviewPending,
6562
- isError: isPreviewError,
6563
- error: previewError
6564
- } = useOrderPreview(id, void 0, {
6565
- placeholderData: keepPreviousData
6428
+ const { order, isPending, isError, error } = useOrder(id, {
6429
+ fields: "metadata"
6566
6430
  });
6567
- useInitiateOrderEdit({ preview });
6568
- const { draft_order, isPending, isError, error } = useDraftOrder(
6569
- id,
6570
- {
6571
- fields: "currency_code"
6572
- },
6573
- {
6574
- enabled: !!id
6575
- }
6576
- );
6577
- const { onCancel } = useCancelOrderEdit({ preview });
6578
6431
  if (isError) {
6579
6432
  throw error;
6580
6433
  }
6581
- if (isPreviewError) {
6582
- throw previewError;
6583
- }
6584
- const ready = !!preview && !isPreviewPending && !!draft_order && !isPending;
6585
- return /* @__PURE__ */ jsx(RouteFocusModal, { onClose: onCancel, children: ready ? /* @__PURE__ */ jsx(ItemsForm, { preview, currencyCode: draft_order.currency_code }) : /* @__PURE__ */ jsxs("div", { children: [
6586
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Edit Items" }) }),
6587
- /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading data for the draft order, please wait..." }) })
6588
- ] }) });
6434
+ const isReady = !isPending && !!order;
6435
+ return /* @__PURE__ */ jsxs(RouteDrawer, { children: [
6436
+ /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
6437
+ /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Metadata" }) }),
6438
+ /* @__PURE__ */ jsx(RouteDrawer.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Add metadata to the draft order." }) })
6439
+ ] }),
6440
+ !isReady ? /* @__PURE__ */ jsx(PlaceholderInner, {}) : /* @__PURE__ */ jsx(MetadataForm, { orderId: id, metadata: order?.metadata })
6441
+ ] });
6589
6442
  };
6590
- const ItemsForm = ({ preview, currencyCode }) => {
6591
- const [isSubmitting, setIsSubmitting] = useState(false);
6592
- const [modalContent, setModalContent] = useState(
6593
- null
6594
- );
6443
+ const METADATA_KEY_LABEL_ID = "metadata-form-key-label";
6444
+ const METADATA_VALUE_LABEL_ID = "metadata-form-value-label";
6445
+ const MetadataForm = ({ orderId, metadata }) => {
6595
6446
  const { handleSuccess } = useRouteModal();
6596
- const { searchValue, onSearchValueChange, query: query2 } = useDebouncedSearch();
6597
- const { hasPermission } = usePermissions();
6598
- const canReadVariants = hasPermission("product_variant:read");
6599
- const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
6600
- const { mutateAsync: requestOrderEdit } = useDraftOrderRequestEdit(preview.id);
6601
- const itemCount = preview.items?.reduce((acc, item) => acc + item.quantity, 0) || 0;
6602
- const matches = useMemo(() => {
6603
- return matchSorter(preview.items, query2, {
6604
- keys: ["product_title", "variant_title", "variant_sku", "title"]
6605
- });
6606
- }, [preview.items, query2]);
6607
- const onSubmit = async () => {
6608
- setIsSubmitting(true);
6609
- let requestSucceeded = false;
6610
- await requestOrderEdit(void 0, {
6611
- onError: (e) => {
6612
- toast.error(`Failed to request order edit: ${e.message}`);
6613
- },
6614
- onSuccess: () => {
6615
- requestSucceeded = true;
6616
- }
6617
- });
6618
- if (!requestSucceeded) {
6619
- setIsSubmitting(false);
6620
- return;
6621
- }
6622
- await confirmOrderEdit(void 0, {
6623
- onError: (e) => {
6624
- toast.error(`Failed to confirm order edit: ${e.message}`);
6625
- },
6626
- onSuccess: () => {
6627
- handleSuccess();
6628
- },
6629
- onSettled: () => {
6630
- setIsSubmitting(false);
6631
- }
6632
- });
6633
- };
6634
- const onKeyDown = useCallback(
6635
- (e) => {
6636
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
6637
- if (modalContent || isSubmitting) {
6638
- return;
6639
- }
6640
- onSubmit();
6641
- }
6642
- },
6643
- [modalContent, isSubmitting, onSubmit]
6644
- );
6645
- useEffect(() => {
6646
- document.addEventListener("keydown", onKeyDown);
6647
- return () => {
6648
- document.removeEventListener("keydown", onKeyDown);
6649
- };
6650
- }, [onKeyDown]);
6651
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col overflow-hidden", children: [
6652
- /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
6653
- /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsxs(
6654
- StackedFocusModal,
6655
- {
6656
- id: STACKED_MODAL_ID,
6657
- onOpenChangeCallback: (open) => {
6658
- if (!open) {
6659
- setModalContent(null);
6660
- }
6661
- },
6662
- children: [
6663
- /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-6 py-16", children: [
6664
- /* @__PURE__ */ jsxs("div", { children: [
6665
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Items" }) }),
6666
- /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Edit the items in the draft order" }) })
6667
- ] }),
6668
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
6669
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-6", children: [
6670
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 items-center gap-3", children: [
6671
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
6672
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Items" }),
6673
- /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Choose items from the product catalog." })
6674
- ] }),
6675
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
6676
- /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
6677
- Input,
6678
- {
6679
- type: "search",
6680
- placeholder: "Search items",
6681
- value: searchValue,
6682
- onChange: (e) => onSearchValueChange(e.target.value)
6683
- }
6684
- ) }),
6685
- /* @__PURE__ */ jsxs(DropdownMenu, { children: [
6686
- /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(IconButton, { type: "button", children: /* @__PURE__ */ jsx(Plus, {}) }) }),
6687
- /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
6688
- canReadVariants && /* @__PURE__ */ jsx(
6689
- StackedModalTrigger$1,
6690
- {
6691
- type: "add-items",
6692
- setModalContent
6693
- }
6694
- ),
6695
- /* @__PURE__ */ jsx(
6696
- StackedModalTrigger$1,
6697
- {
6698
- type: "add-custom-item",
6699
- setModalContent
6700
- }
6701
- )
6702
- ] })
6703
- ] })
6704
- ] })
6705
- ] }),
6706
- /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle shadow-elevation-card-rest rounded-xl", children: [
6707
- /* @__PURE__ */ jsx("div", { className: "px-[5px]", children: /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-muted grid grid-cols-[2fr_1fr_2fr_28px] gap-3 px-4 py-2", children: [
6708
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Item" }) }),
6709
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Quantity" }) }),
6710
- /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Price" }) }),
6711
- /* @__PURE__ */ jsx("div", {})
6712
- ] }) }),
6713
- /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-1.5 px-[5px] pb-[5px]", children: itemCount <= 0 ? /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest flex flex-col items-center justify-center gap-1 gap-x-3 rounded-lg p-4", children: [
6714
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "There are no items in this order" }),
6715
- /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Add items to the order to get started." })
6716
- ] }) : matches.length > 0 ? matches?.map((item) => /* @__PURE__ */ jsx(
6717
- Item,
6718
- {
6719
- item,
6720
- preview,
6721
- currencyCode
6722
- },
6723
- item.id
6724
- )) : /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest flex flex-col items-center justify-center gap-1 gap-x-3 rounded-lg p-4", children: [
6725
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "No items found" }),
6726
- /* @__PURE__ */ jsxs(Text, { size: "small", className: "text-ui-fg-subtle", children: [
6727
- 'No items found for "',
6728
- query2,
6729
- '".'
6730
- ] })
6731
- ] }) })
6732
- ] })
6733
- ] }),
6734
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
6735
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_0.5fr_0.5fr] gap-3", children: [
6736
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Subtotal" }) }),
6737
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(
6738
- Text,
6739
- {
6740
- size: "small",
6741
- leading: "compact",
6742
- className: "text-ui-fg-subtle",
6743
- children: [
6744
- itemCount,
6745
- " ",
6746
- itemCount === 1 ? "item" : "items"
6747
- ]
6748
- }
6749
- ) }),
6750
- /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: getStylizedAmount(preview.item_subtotal, currencyCode) }) })
6751
- ] })
6752
- ] }) }),
6753
- modalContent && (modalContent === "add-items" ? /* @__PURE__ */ jsx(ExistingItemsForm, { orderId: preview.id, items: preview.items }) : modalContent === "add-custom-item" ? /* @__PURE__ */ jsx(
6754
- CustomItemForm,
6755
- {
6756
- orderId: preview.id,
6757
- currencyCode
6758
- }
6759
- ) : null)
6760
- ]
6761
- }
6762
- ) }),
6763
- /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
6764
- /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
6765
- /* @__PURE__ */ jsx(
6766
- Button,
6767
- {
6768
- size: "small",
6769
- type: "button",
6770
- onClick: onSubmit,
6771
- isLoading: isSubmitting,
6772
- children: "Save"
6773
- }
6774
- )
6775
- ] }) })
6776
- ] });
6777
- };
6778
- const Item = ({ item, preview, currencyCode }) => {
6779
- if (item.variant_id) {
6780
- return /* @__PURE__ */ jsx(VariantItem, { item, preview, currencyCode });
6781
- }
6782
- return /* @__PURE__ */ jsx(CustomItem, { item, preview, currencyCode });
6783
- };
6784
- const VariantItem = ({ item, preview, currencyCode }) => {
6785
- const [editing, setEditing] = useState(false);
6447
+ const hasUneditableRows = getHasUneditableRows(metadata);
6448
+ const { mutateAsync, isPending } = useUpdateDraftOrder(orderId);
6786
6449
  const form = useForm({
6787
6450
  defaultValues: {
6788
- quantity: item.quantity,
6789
- unit_price: item.unit_price
6451
+ metadata: getDefaultValues(metadata)
6790
6452
  },
6791
- resolver: zodResolver(variantItemSchema)
6453
+ resolver: zodResolver(MetadataSchema)
6792
6454
  });
6793
- const actionId = useMemo(() => {
6794
- return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
6795
- }, [item]);
6796
- const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
6797
- const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
6798
- const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
6799
- const isPending = isUpdatingActionItem || isUpdatingOriginalItem || isRemovingActionItem;
6800
- const onSubmit = form.handleSubmit(async (data) => {
6801
- if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity) {
6802
- setEditing(false);
6803
- return;
6804
- }
6805
- if (!actionId) {
6806
- await updateOriginalItem(
6807
- {
6808
- item_id: item.id,
6809
- quantity: data.quantity,
6810
- unit_price: convertNumber(data.unit_price)
6811
- },
6812
- {
6813
- onSuccess: () => {
6814
- setEditing(false);
6815
- },
6816
- onError: (e) => {
6817
- toast.error(e.message);
6818
- }
6819
- }
6820
- );
6821
- return;
6822
- }
6823
- if (data.quantity === 0) {
6824
- await removeActionItem(actionId, {
6825
- onSuccess: () => {
6826
- setEditing(false);
6827
- },
6828
- onError: (e) => {
6829
- toast.error(e.message);
6830
- }
6831
- });
6832
- return;
6833
- }
6834
- await updateActionItem(
6455
+ const handleSubmit = form.handleSubmit(async (data) => {
6456
+ const parsedData = parseValues(data);
6457
+ await mutateAsync(
6835
6458
  {
6836
- action_id: actionId,
6837
- quantity: data.quantity,
6838
- unit_price: convertNumber(data.unit_price)
6459
+ metadata: parsedData
6839
6460
  },
6840
6461
  {
6841
6462
  onSuccess: () => {
6842
- setEditing(false);
6463
+ toast.success("Metadata updated");
6464
+ handleSuccess();
6843
6465
  },
6844
- onError: (e) => {
6845
- toast.error(e.message);
6466
+ onError: (error) => {
6467
+ toast.error(error.message);
6846
6468
  }
6847
6469
  }
6848
6470
  );
6849
6471
  });
6850
- return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,2fr)_28px] items-center gap-3 rounded-lg px-4 py-2", children: [
6851
- /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center gap-x-3", children: [
6852
- /* @__PURE__ */ jsx(
6853
- Thumbnail,
6854
- {
6855
- thumbnail: item.thumbnail,
6856
- alt: item.product_title ?? void 0
6857
- }
6858
- ),
6859
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
6860
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
6861
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: item.product_title }),
6862
- /* @__PURE__ */ jsxs(
6863
- Text,
6864
- {
6865
- size: "small",
6866
- leading: "compact",
6867
- className: "text-ui-fg-subtle",
6868
- children: [
6869
- "(",
6870
- item.variant_title,
6871
- ")"
6872
- ]
6873
- }
6874
- )
6875
- ] }),
6876
- /* @__PURE__ */ jsx(
6877
- Text,
6878
- {
6879
- size: "small",
6880
- leading: "compact",
6881
- className: "text-ui-fg-subtle",
6882
- children: item.variant_sku
6883
- }
6884
- )
6885
- ] })
6886
- ] }),
6887
- editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
6888
- Form$2.Field,
6889
- {
6890
- control: form.control,
6891
- name: "quantity",
6892
- render: ({ field }) => {
6893
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
6894
- }
6895
- }
6896
- ) }) : /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }) }),
6897
- editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
6898
- Form$2.Field,
6899
- {
6900
- control: form.control,
6901
- name: "unit_price",
6902
- render: ({ field: { onChange, ...field } }) => {
6903
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
6904
- CurrencyInput,
6905
- {
6906
- ...field,
6907
- symbol: getNativeSymbol(currencyCode),
6908
- code: currencyCode,
6909
- onValueChange: (_value, _name, values) => onChange(values?.value)
6910
- }
6911
- ) }) });
6912
- }
6913
- }
6914
- ) }) : /* @__PURE__ */ jsx("div", { className: "flex w-full flex-1 items-center justify-end", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: getLocaleAmount(item.unit_price, currencyCode) }) }),
6915
- /* @__PURE__ */ jsx(
6916
- IconButton,
6917
- {
6918
- type: "button",
6919
- size: "small",
6920
- onClick: editing ? onSubmit : () => {
6921
- setEditing(true);
6922
- },
6923
- disabled: isPending,
6924
- children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
6925
- }
6926
- )
6927
- ] }) }) });
6928
- };
6929
- const variantItemSchema = z.object({
6930
- quantity: z.number(),
6931
- unit_price: z.union([z.number(), z.string()])
6932
- });
6933
- const CustomItem = ({ item, preview, currencyCode }) => {
6934
- const [editing, setEditing] = useState(false);
6935
- const { quantity, unit_price, title } = item;
6936
- const form = useForm({
6937
- defaultValues: {
6938
- title,
6939
- quantity,
6940
- unit_price
6941
- },
6942
- resolver: zodResolver(customItemSchema)
6472
+ const { fields, insert, remove } = useFieldArray({
6473
+ control: form.control,
6474
+ name: "metadata"
6943
6475
  });
6944
- useEffect(() => {
6945
- form.reset({
6946
- title,
6947
- quantity,
6948
- unit_price
6949
- });
6950
- }, [form, title, quantity, unit_price]);
6951
- const actionId = useMemo(() => {
6952
- return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
6953
- }, [item]);
6954
- const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
6955
- const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
6956
- const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
6957
- const isPending = isUpdatingActionItem || isUpdatingOriginalItem;
6958
- const onSubmit = form.handleSubmit(async (data) => {
6959
- if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity && data.title === item.title) {
6960
- setEditing(false);
6961
- return;
6962
- }
6963
- if (!actionId) {
6964
- await updateOriginalItem(
6965
- {
6966
- item_id: item.id,
6967
- quantity: data.quantity,
6968
- unit_price: convertNumber(data.unit_price)
6969
- },
6970
- {
6971
- onSuccess: () => {
6972
- setEditing(false);
6973
- },
6974
- onError: (e) => {
6975
- toast.error(e.message);
6976
- }
6977
- }
6978
- );
6979
- return;
6980
- }
6981
- if (data.quantity === 0) {
6982
- await removeActionItem(actionId, {
6983
- onSuccess: () => {
6984
- setEditing(false);
6985
- },
6986
- onError: (e) => {
6987
- toast.error(e.message);
6988
- }
6476
+ function deleteRow(index) {
6477
+ remove(index);
6478
+ if (fields.length === 1) {
6479
+ insert(0, {
6480
+ key: "",
6481
+ value: "",
6482
+ disabled: false
6989
6483
  });
6990
- return;
6991
6484
  }
6992
- await updateActionItem(
6993
- {
6994
- action_id: actionId,
6995
- quantity: data.quantity,
6996
- unit_price: convertNumber(data.unit_price)
6997
- },
6998
- {
6999
- onSuccess: () => {
7000
- setEditing(false);
7001
- },
7002
- onError: (e) => {
7003
- toast.error(e.message);
7004
- }
7005
- }
7006
- );
7007
- });
7008
- return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,2fr)_28px] items-center gap-3 rounded-lg px-4 py-2", children: [
7009
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
7010
- /* @__PURE__ */ jsx(
7011
- Thumbnail,
7012
- {
7013
- thumbnail: item.thumbnail,
7014
- alt: item.title ?? void 0
7015
- }
7016
- ),
7017
- editing ? /* @__PURE__ */ jsx(
7018
- Form$2.Field,
7019
- {
7020
- control: form.control,
7021
- name: "title",
7022
- render: ({ field }) => {
7023
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }) });
7024
- }
7025
- }
7026
- ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.title })
7027
- ] }),
7028
- editing ? /* @__PURE__ */ jsx(
7029
- Form$2.Field,
7030
- {
7031
- control: form.control,
7032
- name: "quantity",
7033
- render: ({ field }) => {
7034
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
7035
- }
7036
- }
7037
- ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }),
7038
- editing ? /* @__PURE__ */ jsx(
7039
- Form$2.Field,
7040
- {
7041
- control: form.control,
7042
- name: "unit_price",
7043
- render: ({ field: { onChange, ...field } }) => {
7044
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7045
- CurrencyInput,
7046
- {
7047
- ...field,
7048
- symbol: getNativeSymbol(currencyCode),
7049
- code: currencyCode,
7050
- onValueChange: (_value, _name, values) => onChange(values?.value)
7051
- }
7052
- ) }) });
7053
- }
7054
- }
7055
- ) : /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center justify-end", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: getLocaleAmount(item.unit_price, currencyCode) }) }),
7056
- /* @__PURE__ */ jsx(
7057
- IconButton,
7058
- {
7059
- type: "button",
7060
- size: "small",
7061
- onClick: editing ? onSubmit : () => {
7062
- setEditing(true);
7063
- },
7064
- disabled: isPending,
7065
- children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
7066
- }
7067
- )
7068
- ] }) }) });
7069
- };
7070
- const StackedModalTrigger$1 = ({
7071
- type,
7072
- setModalContent
7073
- }) => {
7074
- const { setIsOpen } = useStackedModal();
7075
- const onClick = useCallback(() => {
7076
- setModalContent(type);
7077
- setIsOpen(STACKED_MODAL_ID, true);
7078
- }, [setModalContent, setIsOpen, type]);
7079
- return /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick, children: type === "add-items" ? "Add items" : "Add custom item" }) });
7080
- };
7081
- const VARIANT_PREFIX = "items";
7082
- const LIMIT = 50;
7083
- const ExistingItemsForm = ({ orderId, items }) => {
7084
- const { setIsOpen } = useStackedModal();
7085
- const [rowSelection, setRowSelection] = useState(
7086
- items.reduce((acc, item) => {
7087
- acc[item.variant_id] = true;
7088
- return acc;
7089
- }, {})
7090
- );
7091
- useEffect(() => {
7092
- setRowSelection(
7093
- items.reduce((acc, item) => {
7094
- if (item.variant_id) {
7095
- acc[item.variant_id] = true;
7096
- }
7097
- return acc;
7098
- }, {})
7099
- );
7100
- }, [items]);
7101
- const { q, order, offset } = useQueryParams(
7102
- ["q", "order", "offset"],
7103
- VARIANT_PREFIX
7104
- );
7105
- const { variants, count, isPending, isError, error } = useProductVariants(
7106
- {
7107
- q,
7108
- order,
7109
- offset: offset ? parseInt(offset) : void 0,
7110
- limit: LIMIT,
7111
- fields: "*inventory_items.inventory.location_levels,+inventory_quantity,+manage_inventory"
7112
- },
6485
+ }
6486
+ function insertRow(index, position) {
6487
+ insert(index + (position === "above" ? 0 : 1), {
6488
+ key: "",
6489
+ value: "",
6490
+ disabled: false
6491
+ });
6492
+ }
6493
+ return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
6494
+ KeyboundForm,
7113
6495
  {
7114
- placeholderData: keepPreviousData
7115
- }
7116
- );
7117
- const columns = useColumns();
7118
- const { mutateAsync } = useDraftOrderAddItems(orderId);
7119
- const onSubmit = async () => {
7120
- const ids = Object.keys(rowSelection).filter(
7121
- (id) => !items.find((i) => i.variant_id === id)
7122
- );
7123
- await mutateAsync(
7124
- {
7125
- items: ids.map((id) => ({
7126
- variant_id: id,
7127
- quantity: 1
7128
- }))
7129
- },
7130
- {
7131
- onSuccess: () => {
7132
- setRowSelection({});
7133
- setIsOpen(STACKED_MODAL_ID, false);
7134
- },
7135
- onError: (e) => {
7136
- toast.error(e.message);
7137
- }
7138
- }
7139
- );
7140
- };
7141
- if (isError) {
7142
- throw error;
7143
- }
7144
- return /* @__PURE__ */ jsxs(
7145
- StackedFocusModal.Content,
7146
- {
7147
- onOpenAutoFocus: (e) => {
7148
- e.preventDefault();
7149
- const searchInput = document.querySelector(
7150
- "[data-modal-id='modal-search-input']"
7151
- );
7152
- if (searchInput) {
7153
- searchInput.focus();
7154
- }
7155
- },
6496
+ onSubmit: handleSubmit,
6497
+ className: "flex flex-1 flex-col overflow-hidden",
7156
6498
  children: [
7157
- /* @__PURE__ */ jsxs(StackedFocusModal.Header, { children: [
7158
- /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Product Variants" }) }),
7159
- /* @__PURE__ */ jsx(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Choose product variants to add to the order." }) })
7160
- ] }),
7161
- /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
7162
- DataTable,
7163
- {
7164
- data: variants,
7165
- columns,
7166
- isLoading: isPending,
7167
- getRowId: (row) => row.id,
7168
- rowCount: count,
7169
- prefix: VARIANT_PREFIX,
7170
- layout: "fill",
7171
- rowSelection: {
7172
- state: rowSelection,
7173
- onRowSelectionChange: setRowSelection,
7174
- enableRowSelection: (row) => {
7175
- return !items.find((i) => i.variant_id === row.original.id);
6499
+ /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-8 overflow-y-auto", children: [
6500
+ /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-1 divide-y rounded-lg", children: [
6501
+ /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle grid grid-cols-2 divide-x rounded-t-lg", children: [
6502
+ /* @__PURE__ */ jsx("div", { className: "txt-compact-small-plus text-ui-fg-subtle px-2 py-1.5", children: /* @__PURE__ */ jsx("label", { id: METADATA_KEY_LABEL_ID, children: "Key" }) }),
6503
+ /* @__PURE__ */ jsx("div", { className: "txt-compact-small-plus text-ui-fg-subtle px-2 py-1.5", children: /* @__PURE__ */ jsx("label", { id: METADATA_VALUE_LABEL_ID, children: "Value" }) })
6504
+ ] }),
6505
+ fields.map((field, index) => {
6506
+ const isDisabled = field.disabled || false;
6507
+ let placeholder = "-";
6508
+ if (typeof field.value === "object") {
6509
+ placeholder = "{ ... }";
7176
6510
  }
7177
- },
7178
- autoFocusSearch: true
7179
- }
7180
- ) }),
7181
- /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7182
- /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7183
- /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Update items" })
6511
+ if (Array.isArray(field.value)) {
6512
+ placeholder = "[ ... ]";
6513
+ }
6514
+ return /* @__PURE__ */ jsx(
6515
+ ConditionalTooltip,
6516
+ {
6517
+ showTooltip: isDisabled,
6518
+ content: "This row is disabled because it contains non-primitive data.",
6519
+ children: /* @__PURE__ */ jsxs("div", { className: "group/table relative", children: [
6520
+ /* @__PURE__ */ jsxs(
6521
+ "div",
6522
+ {
6523
+ className: clx("grid grid-cols-2 divide-x", {
6524
+ "overflow-hidden rounded-b-lg": index === fields.length - 1
6525
+ }),
6526
+ children: [
6527
+ /* @__PURE__ */ jsx(
6528
+ Form$2.Field,
6529
+ {
6530
+ control: form.control,
6531
+ name: `metadata.${index}.key`,
6532
+ render: ({ field: field2 }) => {
6533
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
6534
+ GridInput,
6535
+ {
6536
+ "aria-labelledby": METADATA_KEY_LABEL_ID,
6537
+ ...field2,
6538
+ disabled: isDisabled,
6539
+ placeholder: "Key"
6540
+ }
6541
+ ) }) });
6542
+ }
6543
+ }
6544
+ ),
6545
+ /* @__PURE__ */ jsx(
6546
+ Form$2.Field,
6547
+ {
6548
+ control: form.control,
6549
+ name: `metadata.${index}.value`,
6550
+ render: ({ field: { value, ...field2 } }) => {
6551
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
6552
+ GridInput,
6553
+ {
6554
+ "aria-labelledby": METADATA_VALUE_LABEL_ID,
6555
+ ...field2,
6556
+ value: isDisabled ? placeholder : value,
6557
+ disabled: isDisabled,
6558
+ placeholder: "Value"
6559
+ }
6560
+ ) }) });
6561
+ }
6562
+ }
6563
+ )
6564
+ ]
6565
+ }
6566
+ ),
6567
+ /* @__PURE__ */ jsxs(DropdownMenu, { children: [
6568
+ /* @__PURE__ */ jsx(
6569
+ DropdownMenu.Trigger,
6570
+ {
6571
+ className: clx(
6572
+ "invisible absolute inset-y-0 -right-2.5 my-auto group-hover/table:visible data-[state='open']:visible",
6573
+ {
6574
+ hidden: isDisabled
6575
+ }
6576
+ ),
6577
+ disabled: isDisabled,
6578
+ asChild: true,
6579
+ children: /* @__PURE__ */ jsx(IconButton, { size: "2xsmall", children: /* @__PURE__ */ jsx(EllipsisVertical, {}) })
6580
+ }
6581
+ ),
6582
+ /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
6583
+ /* @__PURE__ */ jsxs(
6584
+ DropdownMenu.Item,
6585
+ {
6586
+ className: "gap-x-2",
6587
+ onClick: () => insertRow(index, "above"),
6588
+ children: [
6589
+ /* @__PURE__ */ jsx(ArrowUpMini, { className: "text-ui-fg-subtle" }),
6590
+ "Insert row above"
6591
+ ]
6592
+ }
6593
+ ),
6594
+ /* @__PURE__ */ jsxs(
6595
+ DropdownMenu.Item,
6596
+ {
6597
+ className: "gap-x-2",
6598
+ onClick: () => insertRow(index, "below"),
6599
+ children: [
6600
+ /* @__PURE__ */ jsx(ArrowDownMini, { className: "text-ui-fg-subtle" }),
6601
+ "Insert row below"
6602
+ ]
6603
+ }
6604
+ ),
6605
+ /* @__PURE__ */ jsx(DropdownMenu.Separator, {}),
6606
+ /* @__PURE__ */ jsxs(
6607
+ DropdownMenu.Item,
6608
+ {
6609
+ className: "gap-x-2",
6610
+ onClick: () => deleteRow(index),
6611
+ children: [
6612
+ /* @__PURE__ */ jsx(Trash, { className: "text-ui-fg-subtle" }),
6613
+ "Delete row"
6614
+ ]
6615
+ }
6616
+ )
6617
+ ] })
6618
+ ] })
6619
+ ] })
6620
+ },
6621
+ field.id
6622
+ );
6623
+ })
6624
+ ] }),
6625
+ hasUneditableRows && /* @__PURE__ */ jsx(InlineTip, { variant: "warning", label: "Some rows are disabled", children: "This object contains non-primitive metadata, such as arrays or objects, that can't be edited here. To edit the disabled rows, use the API directly." })
6626
+ ] }),
6627
+ /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
6628
+ /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
6629
+ /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: "Save" })
7184
6630
  ] }) })
7185
6631
  ]
7186
6632
  }
7187
- );
6633
+ ) });
7188
6634
  };
7189
- const columnHelper = createDataTableColumnHelper();
7190
- const getVariantInventory = (variant) => {
7191
- if (!variant.manage_inventory) {
7192
- return { text: "Not managed", hasInventoryKit: false, notManaged: true };
7193
- }
7194
- const quantity = variant.inventory_quantity;
7195
- const inventoryItems = variant.inventory_items?.map((i) => i.inventory).filter(Boolean) ?? [];
7196
- const hasInventoryKit = inventoryItems.length > 1;
7197
- const locations = {};
7198
- inventoryItems.forEach((i) => {
7199
- i.location_levels?.forEach((l) => {
7200
- locations[l.id] = true;
7201
- });
7202
- });
7203
- const locationCount = Object.keys(locations).length;
7204
- const text = hasInventoryKit ? `${quantity} available` : `${quantity} available at ${locationCount} location${locationCount === 1 ? "" : "s"}`;
7205
- return { text, hasInventoryKit, quantity, notManaged: false };
6635
+ const GridInput = forwardRef(({ className, ...props }, ref) => {
6636
+ return /* @__PURE__ */ jsx(
6637
+ "input",
6638
+ {
6639
+ ref,
6640
+ ...props,
6641
+ autoComplete: "off",
6642
+ className: clx(
6643
+ "txt-compact-small text-ui-fg-base placeholder:text-ui-fg-muted disabled:text-ui-fg-disabled disabled:bg-ui-bg-base bg-transparent px-2 py-1.5 outline-none",
6644
+ className
6645
+ )
6646
+ }
6647
+ );
6648
+ });
6649
+ GridInput.displayName = "MetadataForm.GridInput";
6650
+ const PlaceholderInner = () => {
6651
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col overflow-hidden", children: [
6652
+ /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsx(Skeleton, { className: "h-[148ox] w-full rounded-lg" }) }),
6653
+ /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
6654
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-7 w-12 rounded-md" }),
6655
+ /* @__PURE__ */ jsx(Skeleton, { className: "h-7 w-12 rounded-md" })
6656
+ ] }) })
6657
+ ] });
7206
6658
  };
7207
- const useColumns = () => {
7208
- return useMemo(() => {
6659
+ const EDITABLE_TYPES = ["string", "number", "boolean"];
6660
+ function getDefaultValues(metadata) {
6661
+ if (!metadata || !Object.keys(metadata).length) {
7209
6662
  return [
7210
- columnHelper.select(),
7211
- columnHelper.accessor("product.title", {
7212
- header: "Product",
7213
- cell: ({ row }) => {
7214
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
7215
- /* @__PURE__ */ jsx(
7216
- Thumbnail,
7217
- {
7218
- thumbnail: row.original.product?.thumbnail,
7219
- alt: row.original.product?.title
7220
- }
7221
- ),
7222
- /* @__PURE__ */ jsx("span", { children: row.original.product?.title })
7223
- ] });
7224
- },
7225
- enableSorting: true
7226
- }),
7227
- columnHelper.accessor("title", {
7228
- header: "Variant",
7229
- enableSorting: true
7230
- }),
7231
- columnHelper.accessor("sku", {
7232
- header: "SKU",
7233
- cell: ({ getValue }) => {
7234
- return getValue() ?? "-";
7235
- },
7236
- enableSorting: true
7237
- }),
7238
- columnHelper.accessor("updated_at", {
7239
- header: "Updated",
7240
- cell: ({ getValue }) => {
7241
- return /* @__PURE__ */ jsx(
7242
- Tooltip,
7243
- {
7244
- content: getFullDate({ date: getValue(), includeTime: true }),
7245
- children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
7246
- }
7247
- );
7248
- },
7249
- enableSorting: true,
7250
- sortAscLabel: "Oldest first",
7251
- sortDescLabel: "Newest first"
7252
- }),
7253
- columnHelper.accessor("created_at", {
7254
- header: "Created",
7255
- cell: ({ getValue }) => {
7256
- return /* @__PURE__ */ jsx(
7257
- Tooltip,
7258
- {
7259
- content: getFullDate({ date: getValue(), includeTime: true }),
7260
- children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
7261
- }
7262
- );
7263
- },
7264
- enableSorting: true,
7265
- sortAscLabel: "Oldest first",
7266
- sortDescLabel: "Newest first"
7267
- }),
7268
- columnHelper.display({
7269
- id: "inventory",
7270
- header: "Stock",
7271
- cell: ({ row }) => {
7272
- const { text, hasInventoryKit, quantity, notManaged } = getVariantInventory(row.original);
7273
- return /* @__PURE__ */ jsx(Tooltip, { content: text, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full items-center gap-2 overflow-hidden", children: [
7274
- hasInventoryKit && /* @__PURE__ */ jsx(Component, {}),
7275
- /* @__PURE__ */ jsx(
7276
- "span",
7277
- {
7278
- className: clx("truncate", {
7279
- "text-ui-fg-error": !quantity && !notManaged
7280
- }),
7281
- children: text
7282
- }
7283
- )
7284
- ] }) });
7285
- }
7286
- })
6663
+ {
6664
+ key: "",
6665
+ value: "",
6666
+ disabled: false
6667
+ }
7287
6668
  ];
7288
- }, []);
7289
- };
7290
- const CustomItemForm = ({ orderId, currencyCode }) => {
7291
- const { setIsOpen } = useStackedModal();
7292
- const { mutateAsync: addItems } = useDraftOrderAddItems(orderId);
7293
- const form = useForm({
7294
- defaultValues: {
7295
- title: "",
7296
- quantity: 1,
7297
- unit_price: ""
7298
- },
7299
- resolver: zodResolver(customItemSchema)
6669
+ }
6670
+ return Object.entries(metadata).map(([key, value]) => {
6671
+ if (!EDITABLE_TYPES.includes(typeof value)) {
6672
+ return {
6673
+ key,
6674
+ value,
6675
+ disabled: true
6676
+ };
6677
+ }
6678
+ let stringValue = value;
6679
+ if (typeof value !== "string") {
6680
+ stringValue = JSON.stringify(value);
6681
+ }
6682
+ return {
6683
+ key,
6684
+ value: stringValue,
6685
+ original_key: key
6686
+ };
7300
6687
  });
7301
- const onSubmit = form.handleSubmit(async (data) => {
7302
- await addItems(
7303
- {
7304
- items: [
7305
- {
7306
- title: data.title,
7307
- quantity: data.quantity,
7308
- unit_price: convertNumber(data.unit_price)
7309
- }
7310
- ]
7311
- },
7312
- {
7313
- onSuccess: () => {
7314
- setIsOpen(STACKED_MODAL_ID, false);
7315
- },
7316
- onError: (e) => {
7317
- toast.error(e.message);
7318
- }
6688
+ }
6689
+ function parseValues(values) {
6690
+ const metadata = values.metadata;
6691
+ const isEmpty = !metadata.length || metadata.length === 1 && !metadata[0].key && !metadata[0].value;
6692
+ if (isEmpty) {
6693
+ return null;
6694
+ }
6695
+ const update = {};
6696
+ metadata.forEach((field) => {
6697
+ let key = field.key;
6698
+ let value = field.value;
6699
+ const disabled = field.disabled;
6700
+ if (!key || !value) {
6701
+ return;
6702
+ }
6703
+ if (disabled) {
6704
+ update[key] = value;
6705
+ return;
6706
+ }
6707
+ key = key.trim();
6708
+ value = value.trim();
6709
+ if (value === "true") {
6710
+ update[key] = true;
6711
+ } else if (value === "false") {
6712
+ update[key] = false;
6713
+ } else {
6714
+ const parsedNumber = parseFloat(value);
6715
+ if (!isNaN(parsedNumber)) {
6716
+ update[key] = parsedNumber;
6717
+ } else {
6718
+ update[key] = value;
7319
6719
  }
7320
- );
6720
+ }
7321
6721
  });
7322
- return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx(KeyboundForm, { onSubmit, children: /* @__PURE__ */ jsxs(StackedFocusModal.Content, { children: [
7323
- /* @__PURE__ */ jsx(StackedFocusModal.Header, {}),
7324
- /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-2 py-16", children: [
7325
- /* @__PURE__ */ jsxs("div", { children: [
7326
- /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Add custom item" }) }),
7327
- /* @__PURE__ */ jsx(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Add a custom item to the order. This will add a new line item that is not associated with an existing product." }) })
7328
- ] }),
7329
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7330
- /* @__PURE__ */ jsx(
7331
- Form$2.Field,
7332
- {
7333
- control: form.control,
7334
- name: "title",
7335
- render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7336
- /* @__PURE__ */ jsxs("div", { children: [
7337
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Title" }),
7338
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the title of the item" })
7339
- ] }),
7340
- /* @__PURE__ */ jsxs("div", { children: [
7341
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
7342
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7343
- ] })
7344
- ] }) })
7345
- }
7346
- ),
7347
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7348
- /* @__PURE__ */ jsx(
7349
- Form$2.Field,
7350
- {
7351
- control: form.control,
7352
- name: "unit_price",
7353
- render: ({ field: { onChange, ...field } }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7354
- /* @__PURE__ */ jsxs("div", { children: [
7355
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Unit price" }),
7356
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the unit price of the item" })
7357
- ] }),
7358
- /* @__PURE__ */ jsxs("div", { children: [
7359
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7360
- CurrencyInput,
7361
- {
7362
- symbol: getNativeSymbol(currencyCode),
7363
- code: currencyCode,
7364
- onValueChange: (_value, _name, values) => onChange(values?.value),
7365
- ...field
7366
- }
7367
- ) }),
7368
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7369
- ] })
7370
- ] }) })
7371
- }
7372
- ),
7373
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7374
- /* @__PURE__ */ jsx(
7375
- Form$2.Field,
7376
- {
7377
- control: form.control,
7378
- name: "quantity",
7379
- render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7380
- /* @__PURE__ */ jsxs("div", { children: [
7381
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Quantity" }),
7382
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the quantity of the item" })
7383
- ] }),
7384
- /* @__PURE__ */ jsxs("div", { className: "w-full flex-1", children: [
7385
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(NumberInput, { ...field, className: "w-full" }) }) }),
7386
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7387
- ] })
7388
- ] }) })
7389
- }
7390
- )
7391
- ] }) }) }),
7392
- /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7393
- /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7394
- /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Add item" })
7395
- ] }) })
7396
- ] }) }) });
7397
- };
7398
- const customItemSchema = z.object({
7399
- title: z.string().min(1),
7400
- quantity: z.number(),
7401
- unit_price: z.union([z.number(), z.string()])
7402
- });
6722
+ return update;
6723
+ }
6724
+ function getHasUneditableRows(metadata) {
6725
+ if (!metadata) {
6726
+ return false;
6727
+ }
6728
+ return Object.values(metadata).some(
6729
+ (value) => !EDITABLE_TYPES.includes(typeof value)
6730
+ );
6731
+ }
7403
6732
  const handle$6 = {
7404
6733
  permissions: EDIT_DRAFT_ORDER_PERMISSIONS
7405
6734
  };
7406
- const InlineTip = forwardRef(
7407
- ({ variant = "tip", label, className, children, ...props }, ref) => {
7408
- const labelValue = label || (variant === "warning" ? "Warning" : "Tip");
7409
- return /* @__PURE__ */ jsxs(
7410
- "div",
7411
- {
7412
- ref,
7413
- className: clx(
7414
- "bg-ui-bg-component txt-small text-ui-fg-subtle grid grid-cols-[4px_1fr] items-start gap-3 rounded-lg border p-3",
7415
- className
7416
- ),
7417
- ...props,
7418
- children: [
7419
- /* @__PURE__ */ jsx(
7420
- "div",
7421
- {
7422
- role: "presentation",
7423
- className: clx("w-4px bg-ui-tag-neutral-icon h-full rounded-full", {
7424
- "bg-ui-tag-orange-icon": variant === "warning"
7425
- })
7426
- }
7427
- ),
7428
- /* @__PURE__ */ jsxs("div", { className: "text-pretty", children: [
7429
- /* @__PURE__ */ jsxs("strong", { className: "txt-small-plus text-ui-fg-base", children: [
7430
- labelValue,
7431
- ":"
7432
- ] }),
7433
- " ",
7434
- children
7435
- ] })
7436
- ]
6735
+ const PROMOTION_QUERY_KEY = "promotions";
6736
+ const promotionsQueryKeys = {
6737
+ list: (query2) => [
6738
+ PROMOTION_QUERY_KEY,
6739
+ query2 ? query2 : void 0
6740
+ ],
6741
+ detail: (id, query2) => [
6742
+ PROMOTION_QUERY_KEY,
6743
+ id,
6744
+ query2 ? query2 : void 0
6745
+ ]
6746
+ };
6747
+ const usePromotions = (query2, options) => {
6748
+ const { data, ...rest } = useQuery({
6749
+ queryKey: promotionsQueryKeys.list(query2),
6750
+ queryFn: async () => sdk.admin.promotion.list(query2),
6751
+ ...options
6752
+ });
6753
+ return { ...data, ...rest };
6754
+ };
6755
+ const useCancelOrderEdit = ({ preview }) => {
6756
+ const { mutateAsync: cancelOrderEdit } = useDraftOrderCancelEdit(preview?.id);
6757
+ const onCancel = useCallback(async () => {
6758
+ if (!preview) {
6759
+ return true;
6760
+ }
6761
+ let res = false;
6762
+ await cancelOrderEdit(void 0, {
6763
+ onError: (e) => {
6764
+ toast.error(e.message);
6765
+ },
6766
+ onSuccess: () => {
6767
+ res = true;
7437
6768
  }
7438
- );
7439
- }
7440
- );
7441
- InlineTip.displayName = "InlineTip";
7442
- const MetadataFieldSchema = z.object({
7443
- key: z.string(),
7444
- disabled: z.boolean().optional(),
7445
- value: z.any()
7446
- });
7447
- const MetadataSchema = z.object({
7448
- metadata: z.array(MetadataFieldSchema)
7449
- });
7450
- const Metadata = () => {
6769
+ });
6770
+ return res;
6771
+ }, [preview, cancelOrderEdit]);
6772
+ return { onCancel };
6773
+ };
6774
+ let IS_REQUEST_RUNNING = false;
6775
+ const useInitiateOrderEdit = ({
6776
+ preview
6777
+ }) => {
6778
+ const navigate = useNavigate();
6779
+ const { mutateAsync } = useDraftOrderBeginEdit(preview?.id);
6780
+ useEffect(() => {
6781
+ async function run() {
6782
+ if (IS_REQUEST_RUNNING || !preview) {
6783
+ return;
6784
+ }
6785
+ if (preview.order_change) {
6786
+ return;
6787
+ }
6788
+ IS_REQUEST_RUNNING = true;
6789
+ await mutateAsync(void 0, {
6790
+ onError: (e) => {
6791
+ toast.error(e.message);
6792
+ navigate(`/draft-orders/${preview.id}`, { replace: true });
6793
+ return;
6794
+ }
6795
+ });
6796
+ IS_REQUEST_RUNNING = false;
6797
+ }
6798
+ run();
6799
+ }, [preview, navigate, mutateAsync]);
6800
+ };
6801
+ const Promotions = () => {
7451
6802
  const { id } = useParams();
7452
- const { order, isPending, isError, error } = useOrder(id, {
7453
- fields: "metadata"
7454
- });
7455
- if (isError) {
7456
- throw error;
6803
+ const {
6804
+ order: preview,
6805
+ isError: isPreviewError,
6806
+ error: previewError
6807
+ } = useOrderPreview(id, void 0);
6808
+ useInitiateOrderEdit({ preview });
6809
+ const { onCancel } = useCancelOrderEdit({ preview });
6810
+ if (isPreviewError) {
6811
+ throw previewError;
7457
6812
  }
7458
- const isReady = !isPending && !!order;
7459
- return /* @__PURE__ */ jsxs(RouteDrawer, { children: [
7460
- /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
7461
- /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Metadata" }) }),
7462
- /* @__PURE__ */ jsx(RouteDrawer.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Add metadata to the draft order." }) })
7463
- ] }),
7464
- !isReady ? /* @__PURE__ */ jsx(PlaceholderInner, {}) : /* @__PURE__ */ jsx(MetadataForm, { orderId: id, metadata: order?.metadata })
6813
+ const isReady = !!preview;
6814
+ return /* @__PURE__ */ jsxs(RouteDrawer, { onClose: onCancel, children: [
6815
+ /* @__PURE__ */ jsx(RouteDrawer.Header, { children: /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Promotions" }) }) }),
6816
+ isReady && /* @__PURE__ */ jsx(PromotionForm, { preview })
7465
6817
  ] });
7466
6818
  };
7467
- const METADATA_KEY_LABEL_ID = "metadata-form-key-label";
7468
- const METADATA_VALUE_LABEL_ID = "metadata-form-value-label";
7469
- const MetadataForm = ({ orderId, metadata }) => {
6819
+ const PromotionForm = ({ preview }) => {
6820
+ const { items, shipping_methods } = preview;
6821
+ const [isSubmitting, setIsSubmitting] = useState(false);
6822
+ const [comboboxValue, setComboboxValue] = useState("");
7470
6823
  const { handleSuccess } = useRouteModal();
7471
- const hasUneditableRows = getHasUneditableRows(metadata);
7472
- const { mutateAsync, isPending } = useUpdateDraftOrder(orderId);
7473
- const form = useForm({
7474
- defaultValues: {
7475
- metadata: getDefaultValues(metadata)
6824
+ const { mutateAsync: addPromotions, isPending: isAddingPromotions } = useDraftOrderAddPromotions(preview.id);
6825
+ const promoIds = getPromotionIds(items, shipping_methods);
6826
+ const { promotions, isPending, isError, error } = usePromotions(
6827
+ {
6828
+ id: promoIds
7476
6829
  },
7477
- resolver: zodResolver(MetadataSchema)
6830
+ {
6831
+ enabled: !!promoIds.length
6832
+ }
6833
+ );
6834
+ const comboboxData = useComboboxData({
6835
+ queryKey: ["promotions", "combobox", promoIds],
6836
+ queryFn: async (params) => {
6837
+ return await sdk.admin.promotion.list({
6838
+ ...params,
6839
+ id: {
6840
+ $nin: promoIds
6841
+ }
6842
+ });
6843
+ },
6844
+ getOptions: (data) => {
6845
+ return data.promotions.map((promotion) => ({
6846
+ label: promotion.code,
6847
+ value: promotion.code
6848
+ }));
6849
+ }
7478
6850
  });
7479
- const handleSubmit = form.handleSubmit(async (data) => {
7480
- const parsedData = parseValues(data);
7481
- await mutateAsync(
6851
+ const add = async (value) => {
6852
+ if (!value) {
6853
+ return;
6854
+ }
6855
+ addPromotions(
7482
6856
  {
7483
- metadata: parsedData
6857
+ promo_codes: [value]
7484
6858
  },
7485
6859
  {
7486
- onSuccess: () => {
7487
- toast.success("Metadata updated");
7488
- handleSuccess();
6860
+ onError: (e) => {
6861
+ toast.error(e.message);
6862
+ comboboxData.onSearchValueChange("");
6863
+ setComboboxValue("");
7489
6864
  },
7490
- onError: (error) => {
7491
- toast.error(error.message);
6865
+ onSuccess: () => {
6866
+ comboboxData.onSearchValueChange("");
6867
+ setComboboxValue("");
7492
6868
  }
7493
6869
  }
7494
6870
  );
7495
- });
7496
- const { fields, insert, remove } = useFieldArray({
7497
- control: form.control,
7498
- name: "metadata"
7499
- });
7500
- function deleteRow(index) {
7501
- remove(index);
7502
- if (fields.length === 1) {
7503
- insert(0, {
7504
- key: "",
7505
- value: "",
7506
- disabled: false
7507
- });
6871
+ };
6872
+ const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
6873
+ const { mutateAsync: requestOrderEdit } = useOrderEditRequest(preview.id);
6874
+ const onSubmit = async () => {
6875
+ setIsSubmitting(true);
6876
+ let requestSucceeded = false;
6877
+ await requestOrderEdit(void 0, {
6878
+ onError: (e) => {
6879
+ toast.error(e.message);
6880
+ },
6881
+ onSuccess: () => {
6882
+ requestSucceeded = true;
6883
+ }
6884
+ });
6885
+ if (!requestSucceeded) {
6886
+ setIsSubmitting(false);
6887
+ return;
7508
6888
  }
7509
- }
7510
- function insertRow(index, position) {
7511
- insert(index + (position === "above" ? 0 : 1), {
7512
- key: "",
7513
- value: "",
7514
- disabled: false
6889
+ await confirmOrderEdit(void 0, {
6890
+ onError: (e) => {
6891
+ toast.error(e.message);
6892
+ },
6893
+ onSuccess: () => {
6894
+ handleSuccess();
6895
+ },
6896
+ onSettled: () => {
6897
+ setIsSubmitting(false);
6898
+ }
7515
6899
  });
6900
+ };
6901
+ if (isError) {
6902
+ throw error;
7516
6903
  }
7517
- return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
7518
- KeyboundForm,
7519
- {
7520
- onSubmit: handleSubmit,
7521
- className: "flex flex-1 flex-col overflow-hidden",
7522
- children: [
7523
- /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-1 flex-col gap-y-8 overflow-y-auto", children: [
7524
- /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-1 divide-y rounded-lg", children: [
7525
- /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle grid grid-cols-2 divide-x rounded-t-lg", children: [
7526
- /* @__PURE__ */ jsx("div", { className: "txt-compact-small-plus text-ui-fg-subtle px-2 py-1.5", children: /* @__PURE__ */ jsx("label", { id: METADATA_KEY_LABEL_ID, children: "Key" }) }),
7527
- /* @__PURE__ */ jsx("div", { className: "txt-compact-small-plus text-ui-fg-subtle px-2 py-1.5", children: /* @__PURE__ */ jsx("label", { id: METADATA_VALUE_LABEL_ID, children: "Value" }) })
7528
- ] }),
7529
- fields.map((field, index) => {
7530
- const isDisabled = field.disabled || false;
7531
- let placeholder = "-";
7532
- if (typeof field.value === "object") {
7533
- placeholder = "{ ... }";
7534
- }
7535
- if (Array.isArray(field.value)) {
7536
- placeholder = "[ ... ]";
7537
- }
7538
- return /* @__PURE__ */ jsx(
7539
- ConditionalTooltip,
7540
- {
7541
- showTooltip: isDisabled,
7542
- content: "This row is disabled because it contains non-primitive data.",
7543
- children: /* @__PURE__ */ jsxs("div", { className: "group/table relative", children: [
7544
- /* @__PURE__ */ jsxs(
7545
- "div",
7546
- {
7547
- className: clx("grid grid-cols-2 divide-x", {
7548
- "overflow-hidden rounded-b-lg": index === fields.length - 1
7549
- }),
7550
- children: [
7551
- /* @__PURE__ */ jsx(
7552
- Form$2.Field,
7553
- {
7554
- control: form.control,
7555
- name: `metadata.${index}.key`,
7556
- render: ({ field: field2 }) => {
7557
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7558
- GridInput,
7559
- {
7560
- "aria-labelledby": METADATA_KEY_LABEL_ID,
7561
- ...field2,
7562
- disabled: isDisabled,
7563
- placeholder: "Key"
7564
- }
7565
- ) }) });
7566
- }
7567
- }
7568
- ),
7569
- /* @__PURE__ */ jsx(
7570
- Form$2.Field,
7571
- {
7572
- control: form.control,
7573
- name: `metadata.${index}.value`,
7574
- render: ({ field: { value, ...field2 } }) => {
7575
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7576
- GridInput,
7577
- {
7578
- "aria-labelledby": METADATA_VALUE_LABEL_ID,
7579
- ...field2,
7580
- value: isDisabled ? placeholder : value,
7581
- disabled: isDisabled,
7582
- placeholder: "Value"
7583
- }
7584
- ) }) });
7585
- }
7586
- }
7587
- )
7588
- ]
7589
- }
7590
- ),
7591
- /* @__PURE__ */ jsxs(DropdownMenu, { children: [
7592
- /* @__PURE__ */ jsx(
7593
- DropdownMenu.Trigger,
7594
- {
7595
- className: clx(
7596
- "invisible absolute inset-y-0 -right-2.5 my-auto group-hover/table:visible data-[state='open']:visible",
7597
- {
7598
- hidden: isDisabled
7599
- }
7600
- ),
7601
- disabled: isDisabled,
7602
- asChild: true,
7603
- children: /* @__PURE__ */ jsx(IconButton, { size: "2xsmall", children: /* @__PURE__ */ jsx(EllipsisVertical, {}) })
7604
- }
7605
- ),
7606
- /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
7607
- /* @__PURE__ */ jsxs(
7608
- DropdownMenu.Item,
7609
- {
7610
- className: "gap-x-2",
7611
- onClick: () => insertRow(index, "above"),
7612
- children: [
7613
- /* @__PURE__ */ jsx(ArrowUpMini, { className: "text-ui-fg-subtle" }),
7614
- "Insert row above"
7615
- ]
7616
- }
7617
- ),
7618
- /* @__PURE__ */ jsxs(
7619
- DropdownMenu.Item,
7620
- {
7621
- className: "gap-x-2",
7622
- onClick: () => insertRow(index, "below"),
7623
- children: [
7624
- /* @__PURE__ */ jsx(ArrowDownMini, { className: "text-ui-fg-subtle" }),
7625
- "Insert row below"
7626
- ]
7627
- }
7628
- ),
7629
- /* @__PURE__ */ jsx(DropdownMenu.Separator, {}),
7630
- /* @__PURE__ */ jsxs(
7631
- DropdownMenu.Item,
7632
- {
7633
- className: "gap-x-2",
7634
- onClick: () => deleteRow(index),
7635
- children: [
7636
- /* @__PURE__ */ jsx(Trash, { className: "text-ui-fg-subtle" }),
7637
- "Delete row"
7638
- ]
7639
- }
7640
- )
7641
- ] })
7642
- ] })
7643
- ] })
7644
- },
7645
- field.id
7646
- );
7647
- })
7648
- ] }),
7649
- hasUneditableRows && /* @__PURE__ */ jsx(InlineTip, { variant: "warning", label: "Some rows are disabled", children: "This object contains non-primitive metadata, such as arrays or objects, that can't be edited here. To edit the disabled rows, use the API directly." })
6904
+ return /* @__PURE__ */ jsxs(KeyboundForm, { className: "flex flex-1 flex-col", onSubmit, children: [
6905
+ /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", children: [
6906
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
6907
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
6908
+ /* @__PURE__ */ jsx(Label$1, { size: "small", weight: "plus", htmlFor: "promotion-combobox", children: "Apply promotions" }),
6909
+ /* @__PURE__ */ jsx(Hint$1, { id: "promotion-combobox-hint", children: "Manage promotions that should be applied to the order." })
7650
6910
  ] }),
7651
- /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7652
- /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7653
- /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: "Save" })
7654
- ] }) })
7655
- ]
7656
- }
7657
- ) });
7658
- };
7659
- const GridInput = forwardRef(({ className, ...props }, ref) => {
7660
- return /* @__PURE__ */ jsx(
7661
- "input",
7662
- {
7663
- ref,
7664
- ...props,
7665
- autoComplete: "off",
7666
- className: clx(
7667
- "txt-compact-small text-ui-fg-base placeholder:text-ui-fg-muted disabled:text-ui-fg-disabled disabled:bg-ui-bg-base bg-transparent px-2 py-1.5 outline-none",
7668
- className
6911
+ /* @__PURE__ */ jsx(
6912
+ Combobox,
6913
+ {
6914
+ id: "promotion-combobox",
6915
+ "aria-describedby": "promotion-combobox-hint",
6916
+ isFetchingNextPage: comboboxData.isFetchingNextPage,
6917
+ fetchNextPage: comboboxData.fetchNextPage,
6918
+ options: comboboxData.options,
6919
+ onSearchValueChange: comboboxData.onSearchValueChange,
6920
+ searchValue: comboboxData.searchValue,
6921
+ disabled: comboboxData.disabled || isAddingPromotions,
6922
+ onChange: add,
6923
+ value: comboboxValue
6924
+ }
6925
+ )
6926
+ ] }),
6927
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
6928
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", children: promotions?.map((promotion) => /* @__PURE__ */ jsx(
6929
+ PromotionItem,
6930
+ {
6931
+ promotion,
6932
+ orderId: preview.id,
6933
+ isLoading: isPending
6934
+ },
6935
+ promotion.id
6936
+ )) })
6937
+ ] }) }),
6938
+ /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
6939
+ /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: "Cancel" }) }),
6940
+ /* @__PURE__ */ jsx(
6941
+ Button,
6942
+ {
6943
+ size: "small",
6944
+ type: "submit",
6945
+ isLoading: isSubmitting || isAddingPromotions,
6946
+ children: "Save"
6947
+ }
7669
6948
  )
7670
- }
7671
- );
7672
- });
7673
- GridInput.displayName = "MetadataForm.GridInput";
7674
- const PlaceholderInner = () => {
7675
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col overflow-hidden", children: [
7676
- /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsx(Skeleton, { className: "h-[148ox] w-full rounded-lg" }) }),
7677
- /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7678
- /* @__PURE__ */ jsx(Skeleton, { className: "h-7 w-12 rounded-md" }),
7679
- /* @__PURE__ */ jsx(Skeleton, { className: "h-7 w-12 rounded-md" })
7680
6949
  ] }) })
7681
6950
  ] });
7682
6951
  };
7683
- const EDITABLE_TYPES = ["string", "number", "boolean"];
7684
- function getDefaultValues(metadata) {
7685
- if (!metadata || !Object.keys(metadata).length) {
7686
- return [
6952
+ const PromotionItem = ({
6953
+ promotion,
6954
+ orderId,
6955
+ isLoading
6956
+ }) => {
6957
+ const { mutateAsync: removePromotions, isPending } = useDraftOrderRemovePromotions(orderId);
6958
+ const onRemove = async () => {
6959
+ removePromotions(
7687
6960
  {
7688
- key: "",
7689
- value: "",
7690
- disabled: false
6961
+ promo_codes: [promotion.code]
6962
+ },
6963
+ {
6964
+ onError: (e) => {
6965
+ toast.error(e.message);
6966
+ }
7691
6967
  }
7692
- ];
6968
+ );
6969
+ };
6970
+ const displayValue = getDisplayValue(promotion);
6971
+ return /* @__PURE__ */ jsxs(
6972
+ "div",
6973
+ {
6974
+ className: clx(
6975
+ "bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2",
6976
+ {
6977
+ "animate-pulse": isLoading
6978
+ }
6979
+ ),
6980
+ children: [
6981
+ /* @__PURE__ */ jsxs("div", { children: [
6982
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: promotion.code }),
6983
+ /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle flex items-center gap-1.5", children: [
6984
+ displayValue && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
6985
+ /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: displayValue }),
6986
+ /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: "·" })
6987
+ ] }),
6988
+ /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "capitalize", children: promotion.application_method?.allocation })
6989
+ ] })
6990
+ ] }),
6991
+ /* @__PURE__ */ jsx(
6992
+ IconButton,
6993
+ {
6994
+ size: "small",
6995
+ type: "button",
6996
+ variant: "transparent",
6997
+ onClick: onRemove,
6998
+ isLoading: isPending || isLoading,
6999
+ children: /* @__PURE__ */ jsx(XMark, {})
7000
+ }
7001
+ )
7002
+ ]
7003
+ },
7004
+ promotion.id
7005
+ );
7006
+ };
7007
+ function getDisplayValue(promotion) {
7008
+ const value = promotion.application_method?.value;
7009
+ if (!value) {
7010
+ return null;
7693
7011
  }
7694
- return Object.entries(metadata).map(([key, value]) => {
7695
- if (!EDITABLE_TYPES.includes(typeof value)) {
7696
- return {
7697
- key,
7698
- value,
7699
- disabled: true
7700
- };
7012
+ if (promotion.application_method?.type === "fixed") {
7013
+ const currency = promotion.application_method?.currency_code;
7014
+ if (!currency) {
7015
+ return null;
7701
7016
  }
7702
- let stringValue = value;
7703
- if (typeof value !== "string") {
7704
- stringValue = JSON.stringify(value);
7705
- }
7706
- return {
7707
- key,
7708
- value: stringValue,
7709
- original_key: key
7710
- };
7711
- });
7017
+ return getLocaleAmount(value, currency);
7018
+ } else if (promotion.application_method?.type === "percentage") {
7019
+ return formatPercentage(value);
7020
+ }
7021
+ return null;
7712
7022
  }
7713
- function parseValues(values) {
7714
- const metadata = values.metadata;
7715
- const isEmpty = !metadata.length || metadata.length === 1 && !metadata[0].key && !metadata[0].value;
7716
- if (isEmpty) {
7717
- return null;
7023
+ const formatter = new Intl.NumberFormat([], {
7024
+ style: "percent",
7025
+ minimumFractionDigits: 2
7026
+ });
7027
+ const formatPercentage = (value, isPercentageValue = false) => {
7028
+ let val = value || 0;
7029
+ if (!isPercentageValue) {
7030
+ val = val / 100;
7718
7031
  }
7719
- const update = {};
7720
- metadata.forEach((field) => {
7721
- let key = field.key;
7722
- let value = field.value;
7723
- const disabled = field.disabled;
7724
- if (!key || !value) {
7725
- return;
7726
- }
7727
- if (disabled) {
7728
- update[key] = value;
7729
- return;
7032
+ return formatter.format(val);
7033
+ };
7034
+ function getPromotionIds(items, shippingMethods) {
7035
+ const promotionIds = /* @__PURE__ */ new Set();
7036
+ for (const item of items) {
7037
+ if (item.adjustments) {
7038
+ for (const adjustment of item.adjustments) {
7039
+ if (adjustment.promotion_id) {
7040
+ promotionIds.add(adjustment.promotion_id);
7041
+ }
7042
+ }
7730
7043
  }
7731
- key = key.trim();
7732
- value = value.trim();
7733
- if (value === "true") {
7734
- update[key] = true;
7735
- } else if (value === "false") {
7736
- update[key] = false;
7737
- } else {
7738
- const parsedNumber = parseFloat(value);
7739
- if (!isNaN(parsedNumber)) {
7740
- update[key] = parsedNumber;
7741
- } else {
7742
- update[key] = value;
7044
+ }
7045
+ for (const shippingMethod of shippingMethods) {
7046
+ if (shippingMethod.adjustments) {
7047
+ for (const adjustment of shippingMethod.adjustments) {
7048
+ if (adjustment.promotion_id) {
7049
+ promotionIds.add(adjustment.promotion_id);
7050
+ }
7743
7051
  }
7744
7052
  }
7745
- });
7746
- return update;
7747
- }
7748
- function getHasUneditableRows(metadata) {
7749
- if (!metadata) {
7750
- return false;
7751
7053
  }
7752
- return Object.values(metadata).some(
7753
- (value) => !EDITABLE_TYPES.includes(typeof value)
7754
- );
7054
+ return Array.from(promotionIds);
7755
7055
  }
7756
7056
  const handle$5 = {
7757
- permissions: EDIT_DRAFT_ORDER_PERMISSIONS
7057
+ permissions: EDIT_DRAFT_ORDER_PROMOTIONS_PERMISSIONS
7758
7058
  };
7759
- const PROMOTION_QUERY_KEY = "promotions";
7760
- const promotionsQueryKeys = {
7761
- list: (query2) => [
7762
- PROMOTION_QUERY_KEY,
7763
- query2 ? query2 : void 0
7764
- ],
7765
- detail: (id, query2) => [
7766
- PROMOTION_QUERY_KEY,
7059
+ const SalesChannel = () => {
7060
+ const { id } = useParams();
7061
+ const { draft_order, isPending, isError, error } = useDraftOrder(
7767
7062
  id,
7768
- query2 ? query2 : void 0
7769
- ]
7063
+ {
7064
+ fields: "+sales_channel_id"
7065
+ },
7066
+ {
7067
+ enabled: !!id
7068
+ }
7069
+ );
7070
+ if (isError) {
7071
+ throw error;
7072
+ }
7073
+ const ISrEADY = !!draft_order && !isPending;
7074
+ return /* @__PURE__ */ jsxs(RouteDrawer, { children: [
7075
+ /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
7076
+ /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Sales Channel" }) }),
7077
+ /* @__PURE__ */ jsx(RouteDrawer.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Update which sales channel the draft order is associated with" }) })
7078
+ ] }),
7079
+ ISrEADY && /* @__PURE__ */ jsx(SalesChannelForm, { order: draft_order })
7080
+ ] });
7770
7081
  };
7771
- const usePromotions = (query2, options) => {
7772
- const { data, ...rest } = useQuery({
7773
- queryKey: promotionsQueryKeys.list(query2),
7774
- queryFn: async () => sdk.admin.promotion.list(query2),
7775
- ...options
7082
+ const SalesChannelForm = ({ order }) => {
7083
+ const form = useForm({
7084
+ defaultValues: {
7085
+ sales_channel_id: order.sales_channel_id || ""
7086
+ },
7087
+ resolver: zodResolver(schema$2)
7776
7088
  });
7777
- return { ...data, ...rest };
7089
+ const { mutateAsync, isPending } = useUpdateDraftOrder(order.id);
7090
+ const { handleSuccess } = useRouteModal();
7091
+ const onSubmit = form.handleSubmit(async (data) => {
7092
+ await mutateAsync(
7093
+ {
7094
+ sales_channel_id: data.sales_channel_id
7095
+ },
7096
+ {
7097
+ onSuccess: () => {
7098
+ toast.success("Sales channel updated");
7099
+ handleSuccess();
7100
+ },
7101
+ onError: (error) => {
7102
+ toast.error(error.message);
7103
+ }
7104
+ }
7105
+ );
7106
+ });
7107
+ return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
7108
+ KeyboundForm,
7109
+ {
7110
+ className: "flex flex-1 flex-col overflow-hidden",
7111
+ onSubmit,
7112
+ children: [
7113
+ /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "flex flex-col gap-y-6 overflow-y-auto", children: /* @__PURE__ */ jsx(SalesChannelField, { control: form.control, order }) }),
7114
+ /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
7115
+ /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: "Cancel" }) }),
7116
+ /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: "Save" })
7117
+ ] }) })
7118
+ ]
7119
+ }
7120
+ ) });
7778
7121
  };
7779
- const Promotions = () => {
7122
+ const SalesChannelField = ({ control, order }) => {
7123
+ const salesChannels = useComboboxData({
7124
+ queryFn: async (params) => {
7125
+ return await sdk.admin.salesChannel.list(params);
7126
+ },
7127
+ queryKey: ["sales-channels"],
7128
+ getOptions: (data) => {
7129
+ return data.sales_channels.map((salesChannel) => ({
7130
+ label: salesChannel.name,
7131
+ value: salesChannel.id
7132
+ }));
7133
+ },
7134
+ defaultValue: order.sales_channel_id || void 0
7135
+ });
7136
+ return /* @__PURE__ */ jsx(
7137
+ Form$2.Field,
7138
+ {
7139
+ control,
7140
+ name: "sales_channel_id",
7141
+ render: ({ field }) => {
7142
+ return /* @__PURE__ */ jsxs(Form$2.Item, { children: [
7143
+ /* @__PURE__ */ jsx(Form$2.Label, { children: "Sales Channel" }),
7144
+ /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7145
+ Combobox,
7146
+ {
7147
+ options: salesChannels.options,
7148
+ fetchNextPage: salesChannels.fetchNextPage,
7149
+ isFetchingNextPage: salesChannels.isFetchingNextPage,
7150
+ searchValue: salesChannels.searchValue,
7151
+ onSearchValueChange: salesChannels.onSearchValueChange,
7152
+ placeholder: "Select sales channel",
7153
+ ...field
7154
+ }
7155
+ ) }),
7156
+ /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7157
+ ] });
7158
+ }
7159
+ }
7160
+ );
7161
+ };
7162
+ const schema$2 = z.object({
7163
+ sales_channel_id: z.string().min(1)
7164
+ });
7165
+ const handle$4 = {
7166
+ permissions: EDIT_DRAFT_ORDER_SALES_CHANNEL_PERMISSIONS
7167
+ };
7168
+ function convertNumber(value) {
7169
+ return typeof value === "string" ? Number(value.replace(",", ".")) : value;
7170
+ }
7171
+ const STACKED_FOCUS_MODAL_ID = "shipping-form";
7172
+ const Shipping = () => {
7780
7173
  const { id } = useParams();
7174
+ const { order, isPending, isError, error } = useOrder(id, {
7175
+ fields: "+items.*,+items.variant.*,+items.variant.product.*,+items.variant.product.shipping_profile.*,+currency_code"
7176
+ });
7781
7177
  const {
7782
7178
  order: preview,
7179
+ isPending: isPreviewPending,
7783
7180
  isError: isPreviewError,
7784
7181
  error: previewError
7785
- } = useOrderPreview(id, void 0);
7182
+ } = useOrderPreview(id);
7786
7183
  useInitiateOrderEdit({ preview });
7787
7184
  const { onCancel } = useCancelOrderEdit({ preview });
7185
+ if (isError) {
7186
+ throw error;
7187
+ }
7788
7188
  if (isPreviewError) {
7789
7189
  throw previewError;
7790
7190
  }
7791
- const isReady = !!preview;
7792
- return /* @__PURE__ */ jsxs(RouteDrawer, { onClose: onCancel, children: [
7793
- /* @__PURE__ */ jsx(RouteDrawer.Header, { children: /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Promotions" }) }) }),
7794
- isReady && /* @__PURE__ */ jsx(PromotionForm, { preview })
7795
- ] });
7191
+ const orderHasItems = (order?.items?.length || 0) > 0;
7192
+ const isReady = preview && !isPreviewPending && order && !isPending;
7193
+ return /* @__PURE__ */ jsx(RouteFocusModal, { onClose: onCancel, children: !orderHasItems ? /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col overflow-hidden ", children: [
7194
+ /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
7195
+ /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-6 py-16", children: [
7196
+ /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Shipping" }) }),
7197
+ /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "This draft order currently has no items. Add items to the order before adding shipping." }) })
7198
+ ] }) }) }),
7199
+ /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }) })
7200
+ ] }) : isReady ? /* @__PURE__ */ jsx(ShippingForm, { preview, order }) : /* @__PURE__ */ jsxs("div", { children: [
7201
+ /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Edit Shipping" }) }),
7202
+ /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading data for the draft order, please wait..." }) })
7203
+ ] }) });
7796
7204
  };
7797
- const PromotionForm = ({ preview }) => {
7798
- const { items, shipping_methods } = preview;
7205
+ const ShippingForm = ({ preview, order }) => {
7206
+ const { setIsOpen } = useStackedModal();
7799
7207
  const [isSubmitting, setIsSubmitting] = useState(false);
7800
- const [comboboxValue, setComboboxValue] = useState("");
7801
- const { handleSuccess } = useRouteModal();
7802
- const { mutateAsync: addPromotions, isPending: isAddingPromotions } = useDraftOrderAddPromotions(preview.id);
7803
- const promoIds = getPromotionIds(items, shipping_methods);
7804
- const { promotions, isPending, isError, error } = usePromotions(
7208
+ const [data, setData] = useState(null);
7209
+ const appliedShippingOptionIds = preview.shipping_methods?.map((method) => method.shipping_option_id).filter(Boolean);
7210
+ const { shipping_options } = useShippingOptions(
7805
7211
  {
7806
- id: promoIds
7212
+ id: appliedShippingOptionIds,
7213
+ fields: "+service_zone.*,+service_zone.fulfillment_set.*,+service_zone.fulfillment_set.location.*"
7807
7214
  },
7808
7215
  {
7809
- enabled: !!promoIds.length
7216
+ enabled: appliedShippingOptionIds.length > 0
7810
7217
  }
7811
7218
  );
7812
- const comboboxData = useComboboxData({
7813
- queryKey: ["promotions", "combobox", promoIds],
7814
- queryFn: async (params) => {
7815
- return await sdk.admin.promotion.list({
7816
- ...params,
7817
- id: {
7818
- $nin: promoIds
7819
- }
7820
- });
7821
- },
7822
- getOptions: (data) => {
7823
- return data.promotions.map((promotion) => ({
7824
- label: promotion.code,
7825
- value: promotion.code
7826
- }));
7827
- }
7828
- });
7829
- const add = async (value) => {
7830
- if (!value) {
7831
- return;
7832
- }
7833
- addPromotions(
7834
- {
7835
- promo_codes: [value]
7836
- },
7837
- {
7838
- onError: (e) => {
7839
- toast.error(e.message);
7840
- comboboxData.onSearchValueChange("");
7841
- setComboboxValue("");
7842
- },
7843
- onSuccess: () => {
7844
- comboboxData.onSearchValueChange("");
7845
- setComboboxValue("");
7846
- }
7847
- }
7848
- );
7849
- };
7219
+ const uniqueShippingProfiles = useMemo(() => {
7220
+ const profiles = /* @__PURE__ */ new Map();
7221
+ getUniqueShippingProfiles(order.items).forEach((profile) => {
7222
+ profiles.set(profile.id, profile);
7223
+ });
7224
+ shipping_options?.forEach((option) => {
7225
+ profiles.set(option.shipping_profile_id, option.shipping_profile);
7226
+ });
7227
+ return Array.from(profiles.values());
7228
+ }, [order.items, shipping_options]);
7229
+ const { handleSuccess } = useRouteModal();
7850
7230
  const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
7851
- const { mutateAsync: requestOrderEdit } = useOrderEditRequest(preview.id);
7231
+ const { mutateAsync: requestOrderEdit } = useDraftOrderRequestEdit(preview.id);
7232
+ const { mutateAsync: removeShippingMethod } = useDraftOrderRemoveShippingMethod(preview.id);
7233
+ const { mutateAsync: removeActionShippingMethod } = useDraftOrderRemoveActionShippingMethod(preview.id);
7852
7234
  const onSubmit = async () => {
7853
7235
  setIsSubmitting(true);
7854
7236
  let requestSucceeded = false;
7855
7237
  await requestOrderEdit(void 0, {
7856
7238
  onError: (e) => {
7857
- toast.error(e.message);
7239
+ toast.error(`Failed to request order edit: ${e.message}`);
7858
7240
  },
7859
7241
  onSuccess: () => {
7860
7242
  requestSucceeded = true;
@@ -7866,7 +7248,7 @@ const PromotionForm = ({ preview }) => {
7866
7248
  }
7867
7249
  await confirmOrderEdit(void 0, {
7868
7250
  onError: (e) => {
7869
- toast.error(e.message);
7251
+ toast.error(`Failed to confirm order edit: ${e.message}`);
7870
7252
  },
7871
7253
  onSuccess: () => {
7872
7254
  handleSuccess();
@@ -7876,373 +7258,16 @@ const PromotionForm = ({ preview }) => {
7876
7258
  }
7877
7259
  });
7878
7260
  };
7879
- if (isError) {
7880
- throw error;
7881
- }
7882
- return /* @__PURE__ */ jsxs(KeyboundForm, { className: "flex flex-1 flex-col", onSubmit, children: [
7883
- /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", children: [
7884
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3", children: [
7885
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
7886
- /* @__PURE__ */ jsx(Label$1, { size: "small", weight: "plus", htmlFor: "promotion-combobox", children: "Apply promotions" }),
7887
- /* @__PURE__ */ jsx(Hint$1, { id: "promotion-combobox-hint", children: "Manage promotions that should be applied to the order." })
7888
- ] }),
7889
- /* @__PURE__ */ jsx(
7890
- Combobox,
7891
- {
7892
- id: "promotion-combobox",
7893
- "aria-describedby": "promotion-combobox-hint",
7894
- isFetchingNextPage: comboboxData.isFetchingNextPage,
7895
- fetchNextPage: comboboxData.fetchNextPage,
7896
- options: comboboxData.options,
7897
- onSearchValueChange: comboboxData.onSearchValueChange,
7898
- searchValue: comboboxData.searchValue,
7899
- disabled: comboboxData.disabled || isAddingPromotions,
7900
- onChange: add,
7901
- value: comboboxValue
7902
- }
7903
- )
7904
- ] }),
7905
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7906
- /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", children: promotions?.map((promotion) => /* @__PURE__ */ jsx(
7907
- PromotionItem,
7908
- {
7909
- promotion,
7910
- orderId: preview.id,
7911
- isLoading: isPending
7912
- },
7913
- promotion.id
7914
- )) })
7915
- ] }) }),
7916
- /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
7917
- /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: "Cancel" }) }),
7918
- /* @__PURE__ */ jsx(
7919
- Button,
7920
- {
7921
- size: "small",
7922
- type: "submit",
7923
- isLoading: isSubmitting || isAddingPromotions,
7924
- children: "Save"
7925
- }
7926
- )
7927
- ] }) })
7928
- ] });
7929
- };
7930
- const PromotionItem = ({
7931
- promotion,
7932
- orderId,
7933
- isLoading
7934
- }) => {
7935
- const { mutateAsync: removePromotions, isPending } = useDraftOrderRemovePromotions(orderId);
7936
- const onRemove = async () => {
7937
- removePromotions(
7938
- {
7939
- promo_codes: [promotion.code]
7940
- },
7941
- {
7942
- onError: (e) => {
7943
- toast.error(e.message);
7944
- }
7945
- }
7946
- );
7947
- };
7948
- const displayValue = getDisplayValue(promotion);
7949
- return /* @__PURE__ */ jsxs(
7950
- "div",
7951
- {
7952
- className: clx(
7953
- "bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2",
7954
- {
7955
- "animate-pulse": isLoading
7956
- }
7957
- ),
7958
- children: [
7959
- /* @__PURE__ */ jsxs("div", { children: [
7960
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: promotion.code }),
7961
- /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle flex items-center gap-1.5", children: [
7962
- displayValue && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
7963
- /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: displayValue }),
7964
- /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", children: "·" })
7965
- ] }),
7966
- /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "capitalize", children: promotion.application_method?.allocation })
7967
- ] })
7968
- ] }),
7969
- /* @__PURE__ */ jsx(
7970
- IconButton,
7971
- {
7972
- size: "small",
7973
- type: "button",
7974
- variant: "transparent",
7975
- onClick: onRemove,
7976
- isLoading: isPending || isLoading,
7977
- children: /* @__PURE__ */ jsx(XMark, {})
7978
- }
7979
- )
7980
- ]
7981
- },
7982
- promotion.id
7983
- );
7984
- };
7985
- function getDisplayValue(promotion) {
7986
- const value = promotion.application_method?.value;
7987
- if (!value) {
7988
- return null;
7989
- }
7990
- if (promotion.application_method?.type === "fixed") {
7991
- const currency = promotion.application_method?.currency_code;
7992
- if (!currency) {
7993
- return null;
7994
- }
7995
- return getLocaleAmount(value, currency);
7996
- } else if (promotion.application_method?.type === "percentage") {
7997
- return formatPercentage(value);
7998
- }
7999
- return null;
8000
- }
8001
- const formatter = new Intl.NumberFormat([], {
8002
- style: "percent",
8003
- minimumFractionDigits: 2
8004
- });
8005
- const formatPercentage = (value, isPercentageValue = false) => {
8006
- let val = value || 0;
8007
- if (!isPercentageValue) {
8008
- val = val / 100;
8009
- }
8010
- return formatter.format(val);
8011
- };
8012
- function getPromotionIds(items, shippingMethods) {
8013
- const promotionIds = /* @__PURE__ */ new Set();
8014
- for (const item of items) {
8015
- if (item.adjustments) {
8016
- for (const adjustment of item.adjustments) {
8017
- if (adjustment.promotion_id) {
8018
- promotionIds.add(adjustment.promotion_id);
8019
- }
8020
- }
8021
- }
8022
- }
8023
- for (const shippingMethod of shippingMethods) {
8024
- if (shippingMethod.adjustments) {
8025
- for (const adjustment of shippingMethod.adjustments) {
8026
- if (adjustment.promotion_id) {
8027
- promotionIds.add(adjustment.promotion_id);
7261
+ const onKeydown = useCallback(
7262
+ (e) => {
7263
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
7264
+ if (data || isSubmitting) {
7265
+ return;
8028
7266
  }
7267
+ onSubmit();
8029
7268
  }
8030
- }
8031
- }
8032
- return Array.from(promotionIds);
8033
- }
8034
- const handle$4 = {
8035
- permissions: EDIT_DRAFT_ORDER_PROMOTIONS_PERMISSIONS
8036
- };
8037
- const SalesChannel = () => {
8038
- const { id } = useParams();
8039
- const { draft_order, isPending, isError, error } = useDraftOrder(
8040
- id,
8041
- {
8042
- fields: "+sales_channel_id"
8043
7269
  },
8044
- {
8045
- enabled: !!id
8046
- }
8047
- );
8048
- if (isError) {
8049
- throw error;
8050
- }
8051
- const ISrEADY = !!draft_order && !isPending;
8052
- return /* @__PURE__ */ jsxs(RouteDrawer, { children: [
8053
- /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
8054
- /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Sales Channel" }) }),
8055
- /* @__PURE__ */ jsx(RouteDrawer.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Update which sales channel the draft order is associated with" }) })
8056
- ] }),
8057
- ISrEADY && /* @__PURE__ */ jsx(SalesChannelForm, { order: draft_order })
8058
- ] });
8059
- };
8060
- const SalesChannelForm = ({ order }) => {
8061
- const form = useForm({
8062
- defaultValues: {
8063
- sales_channel_id: order.sales_channel_id || ""
8064
- },
8065
- resolver: zodResolver(schema$2)
8066
- });
8067
- const { mutateAsync, isPending } = useUpdateDraftOrder(order.id);
8068
- const { handleSuccess } = useRouteModal();
8069
- const onSubmit = form.handleSubmit(async (data) => {
8070
- await mutateAsync(
8071
- {
8072
- sales_channel_id: data.sales_channel_id
8073
- },
8074
- {
8075
- onSuccess: () => {
8076
- toast.success("Sales channel updated");
8077
- handleSuccess();
8078
- },
8079
- onError: (error) => {
8080
- toast.error(error.message);
8081
- }
8082
- }
8083
- );
8084
- });
8085
- return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
8086
- KeyboundForm,
8087
- {
8088
- className: "flex flex-1 flex-col overflow-hidden",
8089
- onSubmit,
8090
- children: [
8091
- /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "flex flex-col gap-y-6 overflow-y-auto", children: /* @__PURE__ */ jsx(SalesChannelField, { control: form.control, order }) }),
8092
- /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
8093
- /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: "Cancel" }) }),
8094
- /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: "Save" })
8095
- ] }) })
8096
- ]
8097
- }
8098
- ) });
8099
- };
8100
- const SalesChannelField = ({ control, order }) => {
8101
- const salesChannels = useComboboxData({
8102
- queryFn: async (params) => {
8103
- return await sdk.admin.salesChannel.list(params);
8104
- },
8105
- queryKey: ["sales-channels"],
8106
- getOptions: (data) => {
8107
- return data.sales_channels.map((salesChannel) => ({
8108
- label: salesChannel.name,
8109
- value: salesChannel.id
8110
- }));
8111
- },
8112
- defaultValue: order.sales_channel_id || void 0
8113
- });
8114
- return /* @__PURE__ */ jsx(
8115
- Form$2.Field,
8116
- {
8117
- control,
8118
- name: "sales_channel_id",
8119
- render: ({ field }) => {
8120
- return /* @__PURE__ */ jsxs(Form$2.Item, { children: [
8121
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Sales Channel" }),
8122
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
8123
- Combobox,
8124
- {
8125
- options: salesChannels.options,
8126
- fetchNextPage: salesChannels.fetchNextPage,
8127
- isFetchingNextPage: salesChannels.isFetchingNextPage,
8128
- searchValue: salesChannels.searchValue,
8129
- onSearchValueChange: salesChannels.onSearchValueChange,
8130
- placeholder: "Select sales channel",
8131
- ...field
8132
- }
8133
- ) }),
8134
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
8135
- ] });
8136
- }
8137
- }
8138
- );
8139
- };
8140
- const schema$2 = z.object({
8141
- sales_channel_id: z.string().min(1)
8142
- });
8143
- const handle$3 = {
8144
- permissions: EDIT_DRAFT_ORDER_SALES_CHANNEL_PERMISSIONS
8145
- };
8146
- const STACKED_FOCUS_MODAL_ID = "shipping-form";
8147
- const Shipping = () => {
8148
- const { id } = useParams();
8149
- const { order, isPending, isError, error } = useOrder(id, {
8150
- fields: "+items.*,+items.variant.*,+items.variant.product.*,+items.variant.product.shipping_profile.*,+currency_code"
8151
- });
8152
- const {
8153
- order: preview,
8154
- isPending: isPreviewPending,
8155
- isError: isPreviewError,
8156
- error: previewError
8157
- } = useOrderPreview(id);
8158
- useInitiateOrderEdit({ preview });
8159
- const { onCancel } = useCancelOrderEdit({ preview });
8160
- if (isError) {
8161
- throw error;
8162
- }
8163
- if (isPreviewError) {
8164
- throw previewError;
8165
- }
8166
- const orderHasItems = (order?.items?.length || 0) > 0;
8167
- const isReady = preview && !isPreviewPending && order && !isPending;
8168
- return /* @__PURE__ */ jsx(RouteFocusModal, { onClose: onCancel, children: !orderHasItems ? /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col overflow-hidden ", children: [
8169
- /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
8170
- /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-6 py-16", children: [
8171
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Shipping" }) }),
8172
- /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "This draft order currently has no items. Add items to the order before adding shipping." }) })
8173
- ] }) }) }),
8174
- /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }) })
8175
- ] }) : isReady ? /* @__PURE__ */ jsx(ShippingForm, { preview, order }) : /* @__PURE__ */ jsxs("div", { children: [
8176
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Edit Shipping" }) }),
8177
- /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading data for the draft order, please wait..." }) })
8178
- ] }) });
8179
- };
8180
- const ShippingForm = ({ preview, order }) => {
8181
- const { setIsOpen } = useStackedModal();
8182
- const [isSubmitting, setIsSubmitting] = useState(false);
8183
- const [data, setData] = useState(null);
8184
- const appliedShippingOptionIds = preview.shipping_methods?.map((method) => method.shipping_option_id).filter(Boolean);
8185
- const { shipping_options } = useShippingOptions(
8186
- {
8187
- id: appliedShippingOptionIds,
8188
- fields: "+service_zone.*,+service_zone.fulfillment_set.*,+service_zone.fulfillment_set.location.*"
8189
- },
8190
- {
8191
- enabled: appliedShippingOptionIds.length > 0
8192
- }
8193
- );
8194
- const uniqueShippingProfiles = useMemo(() => {
8195
- const profiles = /* @__PURE__ */ new Map();
8196
- getUniqueShippingProfiles(order.items).forEach((profile) => {
8197
- profiles.set(profile.id, profile);
8198
- });
8199
- shipping_options?.forEach((option) => {
8200
- profiles.set(option.shipping_profile_id, option.shipping_profile);
8201
- });
8202
- return Array.from(profiles.values());
8203
- }, [order.items, shipping_options]);
8204
- const { handleSuccess } = useRouteModal();
8205
- const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
8206
- const { mutateAsync: requestOrderEdit } = useDraftOrderRequestEdit(preview.id);
8207
- const { mutateAsync: removeShippingMethod } = useDraftOrderRemoveShippingMethod(preview.id);
8208
- const { mutateAsync: removeActionShippingMethod } = useDraftOrderRemoveActionShippingMethod(preview.id);
8209
- const onSubmit = async () => {
8210
- setIsSubmitting(true);
8211
- let requestSucceeded = false;
8212
- await requestOrderEdit(void 0, {
8213
- onError: (e) => {
8214
- toast.error(`Failed to request order edit: ${e.message}`);
8215
- },
8216
- onSuccess: () => {
8217
- requestSucceeded = true;
8218
- }
8219
- });
8220
- if (!requestSucceeded) {
8221
- setIsSubmitting(false);
8222
- return;
8223
- }
8224
- await confirmOrderEdit(void 0, {
8225
- onError: (e) => {
8226
- toast.error(`Failed to confirm order edit: ${e.message}`);
8227
- },
8228
- onSuccess: () => {
8229
- handleSuccess();
8230
- },
8231
- onSettled: () => {
8232
- setIsSubmitting(false);
8233
- }
8234
- });
8235
- };
8236
- const onKeydown = useCallback(
8237
- (e) => {
8238
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
8239
- if (data || isSubmitting) {
8240
- return;
8241
- }
8242
- onSubmit();
8243
- }
8244
- },
8245
- [data, isSubmitting, onSubmit]
7270
+ [data, isSubmitting, onSubmit]
8246
7271
  );
8247
7272
  useEffect(() => {
8248
7273
  document.addEventListener("keydown", onKeydown);
@@ -8444,7 +7469,7 @@ const ShippingForm = ({ preview, order }) => {
8444
7469
  ]
8445
7470
  }
8446
7471
  ) : /* @__PURE__ */ jsx(
8447
- StackedModalTrigger,
7472
+ StackedModalTrigger$1,
8448
7473
  {
8449
7474
  shippingProfileId: profile.id,
8450
7475
  shippingOption,
@@ -8554,7 +7579,7 @@ const ShippingForm = ({ preview, order }) => {
8554
7579
  ] }) })
8555
7580
  ] });
8556
7581
  };
8557
- const StackedModalTrigger = ({
7582
+ const StackedModalTrigger$1 = ({
8558
7583
  shippingProfileId,
8559
7584
  shippingOption,
8560
7585
  shippingMethod,
@@ -8937,7 +7962,7 @@ const CustomAmountField = ({
8937
7962
  }
8938
7963
  );
8939
7964
  };
8940
- const handle$2 = {
7965
+ const handle$3 = {
8941
7966
  permissions: EDIT_DRAFT_ORDER_SHIPPING_PERMISSIONS
8942
7967
  };
8943
7968
  const ShippingAddress = () => {
@@ -9142,7 +8167,7 @@ const ShippingAddressForm = ({ order }) => {
9142
8167
  ) });
9143
8168
  };
9144
8169
  const schema$1 = addressSchema;
9145
- const handle$1 = {
8170
+ const handle$2 = {
9146
8171
  permissions: EDIT_DRAFT_ORDER_PERMISSIONS
9147
8172
  };
9148
8173
  const TransferOwnership = () => {
@@ -9491,139 +8516,1114 @@ const Illustration = () => {
9491
8516
  transform: "matrix(0.865865 0.500278 -0.871576 0.490261 105.4 62.5457)",
9492
8517
  fill: "#A1A1AA"
9493
8518
  }
9494
- ),
8519
+ ),
8520
+ /* @__PURE__ */ jsx(
8521
+ "path",
8522
+ {
8523
+ d: "M104.562 57.0927C103.13 56.265 100.792 56.2515 99.3501 57.0626C97.9081 57.8738 97.9004 59.2065 99.333 60.0343C100.766 60.862 103.103 60.8754 104.545 60.0643C105.987 59.2532 105.995 57.9204 104.562 57.0927ZM103.858 58.8972L100.815 59.1265C100.683 59.1367 100.55 59.1134 100.449 59.063C100.44 59.0585 100.432 59.0545 100.425 59.05C100.339 59.0005 100.29 58.9336 100.291 58.8637L100.294 58.1201C100.294 57.9752 100.501 57.8585 100.756 57.86C101.01 57.8615 101.217 57.98 101.216 58.1256L101.214 58.5669L103.732 58.3769C103.984 58.3578 104.217 58.4584 104.251 58.603C104.286 58.7468 104.11 58.8788 103.858 58.8977L103.858 58.8972Z",
8524
+ fill: "#52525B"
8525
+ }
8526
+ ),
8527
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip0_20915_38670)", children: /* @__PURE__ */ jsx(
8528
+ "path",
8529
+ {
8530
+ d: "M133.106 81.8022L140.49 81.8447L140.515 77.6349",
8531
+ stroke: "#A1A1AA",
8532
+ strokeWidth: "1.5",
8533
+ strokeLinecap: "round",
8534
+ strokeLinejoin: "round"
8535
+ }
8536
+ ) }),
8537
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip1_20915_38670)", children: /* @__PURE__ */ jsx(
8538
+ "path",
8539
+ {
8540
+ d: "M143.496 87.8055L150.881 87.8481L150.905 83.6383",
8541
+ stroke: "#A1A1AA",
8542
+ strokeWidth: "1.5",
8543
+ strokeLinecap: "round",
8544
+ strokeLinejoin: "round"
8545
+ }
8546
+ ) }),
8547
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip2_20915_38670)", children: /* @__PURE__ */ jsx(
8548
+ "path",
8549
+ {
8550
+ d: "M153.887 93.8088L161.271 93.8514L161.295 89.6416",
8551
+ stroke: "#A1A1AA",
8552
+ strokeWidth: "1.5",
8553
+ strokeLinecap: "round",
8554
+ strokeLinejoin: "round"
8555
+ }
8556
+ ) }),
8557
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip3_20915_38670)", children: /* @__PURE__ */ jsx(
8558
+ "path",
8559
+ {
8560
+ d: "M126.114 89.1912L118.729 89.1486L118.705 93.3584",
8561
+ stroke: "#A1A1AA",
8562
+ strokeWidth: "1.5",
8563
+ strokeLinecap: "round",
8564
+ strokeLinejoin: "round"
8565
+ }
8566
+ ) }),
8567
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip4_20915_38670)", children: /* @__PURE__ */ jsx(
8568
+ "path",
8569
+ {
8570
+ d: "M136.504 95.1945L129.12 95.1519L129.095 99.3617",
8571
+ stroke: "#A1A1AA",
8572
+ strokeWidth: "1.5",
8573
+ strokeLinecap: "round",
8574
+ strokeLinejoin: "round"
8575
+ }
8576
+ ) }),
8577
+ /* @__PURE__ */ jsx("g", { clipPath: "url(#clip5_20915_38670)", children: /* @__PURE__ */ jsx(
8578
+ "path",
8579
+ {
8580
+ d: "M146.894 101.198L139.51 101.155L139.486 105.365",
8581
+ stroke: "#A1A1AA",
8582
+ strokeWidth: "1.5",
8583
+ strokeLinecap: "round",
8584
+ strokeLinejoin: "round"
8585
+ }
8586
+ ) }),
8587
+ /* @__PURE__ */ jsxs("defs", { children: [
8588
+ /* @__PURE__ */ jsx("clipPath", { id: "clip0_20915_38670", children: /* @__PURE__ */ jsx(
8589
+ "rect",
8590
+ {
8591
+ width: "12",
8592
+ height: "12",
8593
+ fill: "white",
8594
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 138.36 74.6508)"
8595
+ }
8596
+ ) }),
8597
+ /* @__PURE__ */ jsx("clipPath", { id: "clip1_20915_38670", children: /* @__PURE__ */ jsx(
8598
+ "rect",
8599
+ {
8600
+ width: "12",
8601
+ height: "12",
8602
+ fill: "white",
8603
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 148.75 80.6541)"
8604
+ }
8605
+ ) }),
8606
+ /* @__PURE__ */ jsx("clipPath", { id: "clip2_20915_38670", children: /* @__PURE__ */ jsx(
8607
+ "rect",
8608
+ {
8609
+ width: "12",
8610
+ height: "12",
8611
+ fill: "white",
8612
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 159.141 86.6575)"
8613
+ }
8614
+ ) }),
8615
+ /* @__PURE__ */ jsx("clipPath", { id: "clip3_20915_38670", children: /* @__PURE__ */ jsx(
8616
+ "rect",
8617
+ {
8618
+ width: "12",
8619
+ height: "12",
8620
+ fill: "white",
8621
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 120.928 84.4561)"
8622
+ }
8623
+ ) }),
8624
+ /* @__PURE__ */ jsx("clipPath", { id: "clip4_20915_38670", children: /* @__PURE__ */ jsx(
8625
+ "rect",
8626
+ {
8627
+ width: "12",
8628
+ height: "12",
8629
+ fill: "white",
8630
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 131.318 90.4594)"
8631
+ }
8632
+ ) }),
8633
+ /* @__PURE__ */ jsx("clipPath", { id: "clip5_20915_38670", children: /* @__PURE__ */ jsx(
8634
+ "rect",
8635
+ {
8636
+ width: "12",
8637
+ height: "12",
8638
+ fill: "white",
8639
+ transform: "matrix(0.865865 0.500278 -0.871576 0.490261 141.709 96.4627)"
8640
+ }
8641
+ ) })
8642
+ ] })
8643
+ ]
8644
+ }
8645
+ );
8646
+ };
8647
+ const schema = z.object({
8648
+ customer_id: z.string().min(1)
8649
+ });
8650
+ const handle$1 = {
8651
+ permissions: TRANSFER_DRAFT_ORDER_PERMISSIONS
8652
+ };
8653
+ const NumberInput = forwardRef(
8654
+ ({
8655
+ value,
8656
+ onChange,
8657
+ size = "base",
8658
+ min = 0,
8659
+ max = 100,
8660
+ step = 1,
8661
+ className,
8662
+ disabled,
8663
+ ...props
8664
+ }, ref) => {
8665
+ const handleChange = (event) => {
8666
+ const newValue = event.target.value === "" ? min : Number(event.target.value);
8667
+ if (!isNaN(newValue) && (max === void 0 || newValue <= max) && (min === void 0 || newValue >= min)) {
8668
+ onChange(newValue);
8669
+ }
8670
+ };
8671
+ const handleIncrement = () => {
8672
+ const newValue = value + step;
8673
+ if (max === void 0 || newValue <= max) {
8674
+ onChange(newValue);
8675
+ }
8676
+ };
8677
+ const handleDecrement = () => {
8678
+ const newValue = value - step;
8679
+ if (min === void 0 || newValue >= min) {
8680
+ onChange(newValue);
8681
+ }
8682
+ };
8683
+ return /* @__PURE__ */ jsxs(
8684
+ "div",
8685
+ {
8686
+ className: clx(
8687
+ "inline-flex rounded-md bg-ui-bg-field shadow-borders-base overflow-hidden divide-x transition-fg",
8688
+ "[&:has(input:focus)]:shadow-borders-interactive-with-active",
8689
+ {
8690
+ "h-7": size === "small",
8691
+ "h-8": size === "base"
8692
+ },
8693
+ className
8694
+ ),
8695
+ children: [
8696
+ /* @__PURE__ */ jsx(
8697
+ "input",
8698
+ {
8699
+ ref,
8700
+ type: "number",
8701
+ value,
8702
+ onChange: handleChange,
8703
+ min,
8704
+ max,
8705
+ step,
8706
+ className: clx(
8707
+ "flex-1 px-2 py-1 bg-transparent txt-compact-small text-ui-fg-base outline-none [appearance:textfield]",
8708
+ "[&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",
8709
+ "placeholder:text-ui-fg-muted"
8710
+ ),
8711
+ ...props
8712
+ }
8713
+ ),
8714
+ /* @__PURE__ */ jsxs(
8715
+ "button",
8716
+ {
8717
+ className: clx(
8718
+ "flex items-center justify-center outline-none transition-fg",
8719
+ "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
8720
+ "focus:bg-ui-bg-field-component-hover",
8721
+ "hover:bg-ui-bg-field-component-hover",
8722
+ {
8723
+ "size-7": size === "small",
8724
+ "size-8": size === "base"
8725
+ }
8726
+ ),
8727
+ type: "button",
8728
+ onClick: handleDecrement,
8729
+ disabled: min !== void 0 && value <= min || disabled,
8730
+ children: [
8731
+ /* @__PURE__ */ jsx(Minus, {}),
8732
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Decrease by ${step}` })
8733
+ ]
8734
+ }
8735
+ ),
8736
+ /* @__PURE__ */ jsxs(
8737
+ "button",
8738
+ {
8739
+ className: clx(
8740
+ "flex items-center justify-center outline-none transition-fg",
8741
+ "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
8742
+ "focus:bg-ui-bg-field-hover",
8743
+ "hover:bg-ui-bg-field-hover",
8744
+ {
8745
+ "size-7": size === "small",
8746
+ "size-8": size === "base"
8747
+ }
8748
+ ),
8749
+ type: "button",
8750
+ onClick: handleIncrement,
8751
+ disabled: max !== void 0 && value >= max || disabled,
8752
+ children: [
8753
+ /* @__PURE__ */ jsx(Plus, {}),
8754
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Increase by ${step}` })
8755
+ ]
8756
+ }
8757
+ )
8758
+ ]
8759
+ }
8760
+ );
8761
+ }
8762
+ );
8763
+ const PRODUCT_VARIANTS_QUERY_KEY = "product-variants";
8764
+ const productVariantsQueryKeys = {
8765
+ list: (query2) => [
8766
+ PRODUCT_VARIANTS_QUERY_KEY,
8767
+ query2 ? query2 : void 0
8768
+ ]
8769
+ };
8770
+ const useProductVariants = (query2, options) => {
8771
+ const { data, ...rest } = useQuery({
8772
+ queryKey: productVariantsQueryKeys.list(query2),
8773
+ queryFn: async () => await sdk.admin.productVariant.list(query2),
8774
+ ...options
8775
+ });
8776
+ return { ...data, ...rest };
8777
+ };
8778
+ const STACKED_MODAL_ID = "items_stacked_modal";
8779
+ const Items = () => {
8780
+ const { id } = useParams();
8781
+ const {
8782
+ order: preview,
8783
+ isPending: isPreviewPending,
8784
+ isError: isPreviewError,
8785
+ error: previewError
8786
+ } = useOrderPreview(id, void 0, {
8787
+ placeholderData: keepPreviousData
8788
+ });
8789
+ useInitiateOrderEdit({ preview });
8790
+ const { draft_order, isPending, isError, error } = useDraftOrder(
8791
+ id,
8792
+ {
8793
+ fields: "currency_code"
8794
+ },
8795
+ {
8796
+ enabled: !!id
8797
+ }
8798
+ );
8799
+ const { onCancel } = useCancelOrderEdit({ preview });
8800
+ if (isError) {
8801
+ throw error;
8802
+ }
8803
+ if (isPreviewError) {
8804
+ throw previewError;
8805
+ }
8806
+ const ready = !!preview && !isPreviewPending && !!draft_order && !isPending;
8807
+ return /* @__PURE__ */ jsx(RouteFocusModal, { onClose: onCancel, children: ready ? /* @__PURE__ */ jsx(ItemsForm, { preview, currencyCode: draft_order.currency_code }) : /* @__PURE__ */ jsxs("div", { children: [
8808
+ /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Edit Items" }) }),
8809
+ /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading data for the draft order, please wait..." }) })
8810
+ ] }) });
8811
+ };
8812
+ const ItemsForm = ({ preview, currencyCode }) => {
8813
+ const [isSubmitting, setIsSubmitting] = useState(false);
8814
+ const [modalContent, setModalContent] = useState(
8815
+ null
8816
+ );
8817
+ const { handleSuccess } = useRouteModal();
8818
+ const { searchValue, onSearchValueChange, query: query2 } = useDebouncedSearch();
8819
+ const { hasPermission } = usePermissions();
8820
+ const canReadVariants = hasPermission("product_variant:read");
8821
+ const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
8822
+ const { mutateAsync: requestOrderEdit } = useDraftOrderRequestEdit(preview.id);
8823
+ const itemCount = preview.items?.reduce((acc, item) => acc + item.quantity, 0) || 0;
8824
+ const matches = useMemo(() => {
8825
+ return matchSorter(preview.items, query2, {
8826
+ keys: ["product_title", "variant_title", "variant_sku", "title"]
8827
+ });
8828
+ }, [preview.items, query2]);
8829
+ const onSubmit = async () => {
8830
+ setIsSubmitting(true);
8831
+ let requestSucceeded = false;
8832
+ await requestOrderEdit(void 0, {
8833
+ onError: (e) => {
8834
+ toast.error(`Failed to request order edit: ${e.message}`);
8835
+ },
8836
+ onSuccess: () => {
8837
+ requestSucceeded = true;
8838
+ }
8839
+ });
8840
+ if (!requestSucceeded) {
8841
+ setIsSubmitting(false);
8842
+ return;
8843
+ }
8844
+ await confirmOrderEdit(void 0, {
8845
+ onError: (e) => {
8846
+ toast.error(`Failed to confirm order edit: ${e.message}`);
8847
+ },
8848
+ onSuccess: () => {
8849
+ handleSuccess();
8850
+ },
8851
+ onSettled: () => {
8852
+ setIsSubmitting(false);
8853
+ }
8854
+ });
8855
+ };
8856
+ const onKeyDown = useCallback(
8857
+ (e) => {
8858
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
8859
+ if (modalContent || isSubmitting) {
8860
+ return;
8861
+ }
8862
+ onSubmit();
8863
+ }
8864
+ },
8865
+ [modalContent, isSubmitting, onSubmit]
8866
+ );
8867
+ useEffect(() => {
8868
+ document.addEventListener("keydown", onKeyDown);
8869
+ return () => {
8870
+ document.removeEventListener("keydown", onKeyDown);
8871
+ };
8872
+ }, [onKeyDown]);
8873
+ return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col overflow-hidden", children: [
8874
+ /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
8875
+ /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsxs(
8876
+ StackedFocusModal,
8877
+ {
8878
+ id: STACKED_MODAL_ID,
8879
+ onOpenChangeCallback: (open) => {
8880
+ if (!open) {
8881
+ setModalContent(null);
8882
+ }
8883
+ },
8884
+ children: [
8885
+ /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-6 py-16", children: [
8886
+ /* @__PURE__ */ jsxs("div", { children: [
8887
+ /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Items" }) }),
8888
+ /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Edit the items in the draft order" }) })
8889
+ ] }),
8890
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
8891
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-6", children: [
8892
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 items-center gap-3", children: [
8893
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
8894
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Items" }),
8895
+ /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Choose items from the product catalog." })
8896
+ ] }),
8897
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
8898
+ /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
8899
+ Input,
8900
+ {
8901
+ type: "search",
8902
+ placeholder: "Search items",
8903
+ value: searchValue,
8904
+ onChange: (e) => onSearchValueChange(e.target.value)
8905
+ }
8906
+ ) }),
8907
+ /* @__PURE__ */ jsxs(DropdownMenu, { children: [
8908
+ /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(IconButton, { type: "button", children: /* @__PURE__ */ jsx(Plus, {}) }) }),
8909
+ /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
8910
+ canReadVariants && /* @__PURE__ */ jsx(
8911
+ StackedModalTrigger,
8912
+ {
8913
+ type: "add-items",
8914
+ setModalContent
8915
+ }
8916
+ ),
8917
+ /* @__PURE__ */ jsx(
8918
+ StackedModalTrigger,
8919
+ {
8920
+ type: "add-custom-item",
8921
+ setModalContent
8922
+ }
8923
+ )
8924
+ ] })
8925
+ ] })
8926
+ ] })
8927
+ ] }),
8928
+ /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle shadow-elevation-card-rest rounded-xl", children: [
8929
+ /* @__PURE__ */ jsx("div", { className: "px-[5px]", children: /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-muted grid grid-cols-[2fr_1fr_2fr_28px] gap-3 px-4 py-2", children: [
8930
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Item" }) }),
8931
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Quantity" }) }),
8932
+ /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Price" }) }),
8933
+ /* @__PURE__ */ jsx("div", {})
8934
+ ] }) }),
8935
+ /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-1.5 px-[5px] pb-[5px]", children: itemCount <= 0 ? /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest flex flex-col items-center justify-center gap-1 gap-x-3 rounded-lg p-4", children: [
8936
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "There are no items in this order" }),
8937
+ /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Add items to the order to get started." })
8938
+ ] }) : matches.length > 0 ? matches?.map((item) => /* @__PURE__ */ jsx(
8939
+ Item,
8940
+ {
8941
+ item,
8942
+ preview,
8943
+ currencyCode
8944
+ },
8945
+ item.id
8946
+ )) : /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest flex flex-col items-center justify-center gap-1 gap-x-3 rounded-lg p-4", children: [
8947
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "No items found" }),
8948
+ /* @__PURE__ */ jsxs(Text, { size: "small", className: "text-ui-fg-subtle", children: [
8949
+ 'No items found for "',
8950
+ query2,
8951
+ '".'
8952
+ ] })
8953
+ ] }) })
8954
+ ] })
8955
+ ] }),
8956
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
8957
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_0.5fr_0.5fr] gap-3", children: [
8958
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Subtotal" }) }),
8959
+ /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(
8960
+ Text,
8961
+ {
8962
+ size: "small",
8963
+ leading: "compact",
8964
+ className: "text-ui-fg-subtle",
8965
+ children: [
8966
+ itemCount,
8967
+ " ",
8968
+ itemCount === 1 ? "item" : "items"
8969
+ ]
8970
+ }
8971
+ ) }),
8972
+ /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: getStylizedAmount(preview.item_subtotal, currencyCode) }) })
8973
+ ] })
8974
+ ] }) }),
8975
+ modalContent && (modalContent === "add-items" ? /* @__PURE__ */ jsx(ExistingItemsForm, { orderId: preview.id, items: preview.items }) : modalContent === "add-custom-item" ? /* @__PURE__ */ jsx(
8976
+ CustomItemForm,
8977
+ {
8978
+ orderId: preview.id,
8979
+ currencyCode
8980
+ }
8981
+ ) : null)
8982
+ ]
8983
+ }
8984
+ ) }),
8985
+ /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
8986
+ /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
8987
+ /* @__PURE__ */ jsx(
8988
+ Button,
8989
+ {
8990
+ size: "small",
8991
+ type: "button",
8992
+ onClick: onSubmit,
8993
+ isLoading: isSubmitting,
8994
+ children: "Save"
8995
+ }
8996
+ )
8997
+ ] }) })
8998
+ ] });
8999
+ };
9000
+ const Item = ({ item, preview, currencyCode }) => {
9001
+ if (item.variant_id) {
9002
+ return /* @__PURE__ */ jsx(VariantItem, { item, preview, currencyCode });
9003
+ }
9004
+ return /* @__PURE__ */ jsx(CustomItem, { item, preview, currencyCode });
9005
+ };
9006
+ const VariantItem = ({ item, preview, currencyCode }) => {
9007
+ const [editing, setEditing] = useState(false);
9008
+ const form = useForm({
9009
+ defaultValues: {
9010
+ quantity: item.quantity,
9011
+ unit_price: item.unit_price
9012
+ },
9013
+ resolver: zodResolver(variantItemSchema)
9014
+ });
9015
+ const actionId = useMemo(() => {
9016
+ return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
9017
+ }, [item]);
9018
+ const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
9019
+ const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
9020
+ const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
9021
+ const isPending = isUpdatingActionItem || isUpdatingOriginalItem || isRemovingActionItem;
9022
+ const onSubmit = form.handleSubmit(async (data) => {
9023
+ if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity) {
9024
+ setEditing(false);
9025
+ return;
9026
+ }
9027
+ if (!actionId) {
9028
+ await updateOriginalItem(
9029
+ {
9030
+ item_id: item.id,
9031
+ quantity: data.quantity,
9032
+ unit_price: convertNumber(data.unit_price)
9033
+ },
9034
+ {
9035
+ onSuccess: () => {
9036
+ setEditing(false);
9037
+ },
9038
+ onError: (e) => {
9039
+ toast.error(e.message);
9040
+ }
9041
+ }
9042
+ );
9043
+ return;
9044
+ }
9045
+ if (data.quantity === 0) {
9046
+ await removeActionItem(actionId, {
9047
+ onSuccess: () => {
9048
+ setEditing(false);
9049
+ },
9050
+ onError: (e) => {
9051
+ toast.error(e.message);
9052
+ }
9053
+ });
9054
+ return;
9055
+ }
9056
+ await updateActionItem(
9057
+ {
9058
+ action_id: actionId,
9059
+ quantity: data.quantity,
9060
+ unit_price: convertNumber(data.unit_price)
9061
+ },
9062
+ {
9063
+ onSuccess: () => {
9064
+ setEditing(false);
9065
+ },
9066
+ onError: (e) => {
9067
+ toast.error(e.message);
9068
+ }
9069
+ }
9070
+ );
9071
+ });
9072
+ return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,2fr)_28px] items-center gap-3 rounded-lg px-4 py-2", children: [
9073
+ /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center gap-x-3", children: [
9074
+ /* @__PURE__ */ jsx(
9075
+ Thumbnail,
9076
+ {
9077
+ thumbnail: item.thumbnail,
9078
+ alt: item.product_title ?? void 0
9079
+ }
9080
+ ),
9081
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
9082
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
9083
+ /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: item.product_title }),
9084
+ /* @__PURE__ */ jsxs(
9085
+ Text,
9086
+ {
9087
+ size: "small",
9088
+ leading: "compact",
9089
+ className: "text-ui-fg-subtle",
9090
+ children: [
9091
+ "(",
9092
+ item.variant_title,
9093
+ ")"
9094
+ ]
9095
+ }
9096
+ )
9097
+ ] }),
9495
9098
  /* @__PURE__ */ jsx(
9496
- "path",
9497
- {
9498
- d: "M104.562 57.0927C103.13 56.265 100.792 56.2515 99.3501 57.0626C97.9081 57.8738 97.9004 59.2065 99.333 60.0343C100.766 60.862 103.103 60.8754 104.545 60.0643C105.987 59.2532 105.995 57.9204 104.562 57.0927ZM103.858 58.8972L100.815 59.1265C100.683 59.1367 100.55 59.1134 100.449 59.063C100.44 59.0585 100.432 59.0545 100.425 59.05C100.339 59.0005 100.29 58.9336 100.291 58.8637L100.294 58.1201C100.294 57.9752 100.501 57.8585 100.756 57.86C101.01 57.8615 101.217 57.98 101.216 58.1256L101.214 58.5669L103.732 58.3769C103.984 58.3578 104.217 58.4584 104.251 58.603C104.286 58.7468 104.11 58.8788 103.858 58.8977L103.858 58.8972Z",
9499
- fill: "#52525B"
9500
- }
9501
- ),
9502
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip0_20915_38670)", children: /* @__PURE__ */ jsx(
9503
- "path",
9504
- {
9505
- d: "M133.106 81.8022L140.49 81.8447L140.515 77.6349",
9506
- stroke: "#A1A1AA",
9507
- strokeWidth: "1.5",
9508
- strokeLinecap: "round",
9509
- strokeLinejoin: "round"
9510
- }
9511
- ) }),
9512
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip1_20915_38670)", children: /* @__PURE__ */ jsx(
9513
- "path",
9514
- {
9515
- d: "M143.496 87.8055L150.881 87.8481L150.905 83.6383",
9516
- stroke: "#A1A1AA",
9517
- strokeWidth: "1.5",
9518
- strokeLinecap: "round",
9519
- strokeLinejoin: "round"
9520
- }
9521
- ) }),
9522
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip2_20915_38670)", children: /* @__PURE__ */ jsx(
9523
- "path",
9099
+ Text,
9524
9100
  {
9525
- d: "M153.887 93.8088L161.271 93.8514L161.295 89.6416",
9526
- stroke: "#A1A1AA",
9527
- strokeWidth: "1.5",
9528
- strokeLinecap: "round",
9529
- strokeLinejoin: "round"
9101
+ size: "small",
9102
+ leading: "compact",
9103
+ className: "text-ui-fg-subtle",
9104
+ children: item.variant_sku
9530
9105
  }
9531
- ) }),
9532
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip3_20915_38670)", children: /* @__PURE__ */ jsx(
9533
- "path",
9534
- {
9535
- d: "M126.114 89.1912L118.729 89.1486L118.705 93.3584",
9536
- stroke: "#A1A1AA",
9537
- strokeWidth: "1.5",
9538
- strokeLinecap: "round",
9539
- strokeLinejoin: "round"
9106
+ )
9107
+ ] })
9108
+ ] }),
9109
+ editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
9110
+ Form$2.Field,
9111
+ {
9112
+ control: form.control,
9113
+ name: "quantity",
9114
+ render: ({ field }) => {
9115
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
9116
+ }
9117
+ }
9118
+ ) }) : /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }) }),
9119
+ editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
9120
+ Form$2.Field,
9121
+ {
9122
+ control: form.control,
9123
+ name: "unit_price",
9124
+ render: ({ field: { onChange, ...field } }) => {
9125
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
9126
+ CurrencyInput,
9127
+ {
9128
+ ...field,
9129
+ symbol: getNativeSymbol(currencyCode),
9130
+ code: currencyCode,
9131
+ onValueChange: (_value, _name, values) => onChange(values?.value)
9132
+ }
9133
+ ) }) });
9134
+ }
9135
+ }
9136
+ ) }) : /* @__PURE__ */ jsx("div", { className: "flex w-full flex-1 items-center justify-end", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: getLocaleAmount(item.unit_price, currencyCode) }) }),
9137
+ /* @__PURE__ */ jsx(
9138
+ IconButton,
9139
+ {
9140
+ type: "button",
9141
+ size: "small",
9142
+ onClick: editing ? onSubmit : () => {
9143
+ setEditing(true);
9144
+ },
9145
+ disabled: isPending,
9146
+ children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
9147
+ }
9148
+ )
9149
+ ] }) }) });
9150
+ };
9151
+ const variantItemSchema = z.object({
9152
+ quantity: z.number(),
9153
+ unit_price: z.union([z.number(), z.string()])
9154
+ });
9155
+ const CustomItem = ({ item, preview, currencyCode }) => {
9156
+ const [editing, setEditing] = useState(false);
9157
+ const { quantity, unit_price, title } = item;
9158
+ const form = useForm({
9159
+ defaultValues: {
9160
+ title,
9161
+ quantity,
9162
+ unit_price
9163
+ },
9164
+ resolver: zodResolver(customItemSchema)
9165
+ });
9166
+ useEffect(() => {
9167
+ form.reset({
9168
+ title,
9169
+ quantity,
9170
+ unit_price
9171
+ });
9172
+ }, [form, title, quantity, unit_price]);
9173
+ const actionId = useMemo(() => {
9174
+ return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
9175
+ }, [item]);
9176
+ const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
9177
+ const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
9178
+ const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
9179
+ const isPending = isUpdatingActionItem || isUpdatingOriginalItem;
9180
+ const onSubmit = form.handleSubmit(async (data) => {
9181
+ if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity && data.title === item.title) {
9182
+ setEditing(false);
9183
+ return;
9184
+ }
9185
+ if (!actionId) {
9186
+ await updateOriginalItem(
9187
+ {
9188
+ item_id: item.id,
9189
+ quantity: data.quantity,
9190
+ unit_price: convertNumber(data.unit_price)
9191
+ },
9192
+ {
9193
+ onSuccess: () => {
9194
+ setEditing(false);
9195
+ },
9196
+ onError: (e) => {
9197
+ toast.error(e.message);
9540
9198
  }
9541
- ) }),
9542
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip4_20915_38670)", children: /* @__PURE__ */ jsx(
9543
- "path",
9544
- {
9545
- d: "M136.504 95.1945L129.12 95.1519L129.095 99.3617",
9546
- stroke: "#A1A1AA",
9547
- strokeWidth: "1.5",
9548
- strokeLinecap: "round",
9549
- strokeLinejoin: "round"
9199
+ }
9200
+ );
9201
+ return;
9202
+ }
9203
+ if (data.quantity === 0) {
9204
+ await removeActionItem(actionId, {
9205
+ onSuccess: () => {
9206
+ setEditing(false);
9207
+ },
9208
+ onError: (e) => {
9209
+ toast.error(e.message);
9210
+ }
9211
+ });
9212
+ return;
9213
+ }
9214
+ await updateActionItem(
9215
+ {
9216
+ action_id: actionId,
9217
+ quantity: data.quantity,
9218
+ unit_price: convertNumber(data.unit_price)
9219
+ },
9220
+ {
9221
+ onSuccess: () => {
9222
+ setEditing(false);
9223
+ },
9224
+ onError: (e) => {
9225
+ toast.error(e.message);
9226
+ }
9227
+ }
9228
+ );
9229
+ });
9230
+ return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx("form", { onSubmit, children: /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-card-rest grid grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,2fr)_28px] items-center gap-3 rounded-lg px-4 py-2", children: [
9231
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
9232
+ /* @__PURE__ */ jsx(
9233
+ Thumbnail,
9234
+ {
9235
+ thumbnail: item.thumbnail,
9236
+ alt: item.title ?? void 0
9237
+ }
9238
+ ),
9239
+ editing ? /* @__PURE__ */ jsx(
9240
+ Form$2.Field,
9241
+ {
9242
+ control: form.control,
9243
+ name: "title",
9244
+ render: ({ field }) => {
9245
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }) });
9550
9246
  }
9551
- ) }),
9552
- /* @__PURE__ */ jsx("g", { clipPath: "url(#clip5_20915_38670)", children: /* @__PURE__ */ jsx(
9553
- "path",
9247
+ }
9248
+ ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.title })
9249
+ ] }),
9250
+ editing ? /* @__PURE__ */ jsx(
9251
+ Form$2.Field,
9252
+ {
9253
+ control: form.control,
9254
+ name: "quantity",
9255
+ render: ({ field }) => {
9256
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
9257
+ }
9258
+ }
9259
+ ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }),
9260
+ editing ? /* @__PURE__ */ jsx(
9261
+ Form$2.Field,
9262
+ {
9263
+ control: form.control,
9264
+ name: "unit_price",
9265
+ render: ({ field: { onChange, ...field } }) => {
9266
+ return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
9267
+ CurrencyInput,
9268
+ {
9269
+ ...field,
9270
+ symbol: getNativeSymbol(currencyCode),
9271
+ code: currencyCode,
9272
+ onValueChange: (_value, _name, values) => onChange(values?.value)
9273
+ }
9274
+ ) }) });
9275
+ }
9276
+ }
9277
+ ) : /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center justify-end", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: getLocaleAmount(item.unit_price, currencyCode) }) }),
9278
+ /* @__PURE__ */ jsx(
9279
+ IconButton,
9280
+ {
9281
+ type: "button",
9282
+ size: "small",
9283
+ onClick: editing ? onSubmit : () => {
9284
+ setEditing(true);
9285
+ },
9286
+ disabled: isPending,
9287
+ children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
9288
+ }
9289
+ )
9290
+ ] }) }) });
9291
+ };
9292
+ const StackedModalTrigger = ({
9293
+ type,
9294
+ setModalContent
9295
+ }) => {
9296
+ const { setIsOpen } = useStackedModal();
9297
+ const onClick = useCallback(() => {
9298
+ setModalContent(type);
9299
+ setIsOpen(STACKED_MODAL_ID, true);
9300
+ }, [setModalContent, setIsOpen, type]);
9301
+ return /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick, children: type === "add-items" ? "Add items" : "Add custom item" }) });
9302
+ };
9303
+ const VARIANT_PREFIX = "items";
9304
+ const LIMIT = 50;
9305
+ const ExistingItemsForm = ({ orderId, items }) => {
9306
+ const { setIsOpen } = useStackedModal();
9307
+ const [rowSelection, setRowSelection] = useState(
9308
+ items.reduce((acc, item) => {
9309
+ acc[item.variant_id] = true;
9310
+ return acc;
9311
+ }, {})
9312
+ );
9313
+ useEffect(() => {
9314
+ setRowSelection(
9315
+ items.reduce((acc, item) => {
9316
+ if (item.variant_id) {
9317
+ acc[item.variant_id] = true;
9318
+ }
9319
+ return acc;
9320
+ }, {})
9321
+ );
9322
+ }, [items]);
9323
+ const { q, order, offset } = useQueryParams(
9324
+ ["q", "order", "offset"],
9325
+ VARIANT_PREFIX
9326
+ );
9327
+ const { variants, count, isPending, isError, error } = useProductVariants(
9328
+ {
9329
+ q,
9330
+ order,
9331
+ offset: offset ? parseInt(offset) : void 0,
9332
+ limit: LIMIT,
9333
+ fields: "*inventory_items.inventory.location_levels,+inventory_quantity,+manage_inventory"
9334
+ },
9335
+ {
9336
+ placeholderData: keepPreviousData
9337
+ }
9338
+ );
9339
+ const columns = useColumns();
9340
+ const { mutateAsync } = useDraftOrderAddItems(orderId);
9341
+ const onSubmit = async () => {
9342
+ const ids = Object.keys(rowSelection).filter(
9343
+ (id) => !items.find((i) => i.variant_id === id)
9344
+ );
9345
+ await mutateAsync(
9346
+ {
9347
+ items: ids.map((id) => ({
9348
+ variant_id: id,
9349
+ quantity: 1
9350
+ }))
9351
+ },
9352
+ {
9353
+ onSuccess: () => {
9354
+ setRowSelection({});
9355
+ setIsOpen(STACKED_MODAL_ID, false);
9356
+ },
9357
+ onError: (e) => {
9358
+ toast.error(e.message);
9359
+ }
9360
+ }
9361
+ );
9362
+ };
9363
+ if (isError) {
9364
+ throw error;
9365
+ }
9366
+ return /* @__PURE__ */ jsxs(
9367
+ StackedFocusModal.Content,
9368
+ {
9369
+ onOpenAutoFocus: (e) => {
9370
+ e.preventDefault();
9371
+ const searchInput = document.querySelector(
9372
+ "[data-modal-id='modal-search-input']"
9373
+ );
9374
+ if (searchInput) {
9375
+ searchInput.focus();
9376
+ }
9377
+ },
9378
+ children: [
9379
+ /* @__PURE__ */ jsxs(StackedFocusModal.Header, { children: [
9380
+ /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Product Variants" }) }),
9381
+ /* @__PURE__ */ jsx(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Choose product variants to add to the order." }) })
9382
+ ] }),
9383
+ /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
9384
+ DataTable,
9554
9385
  {
9555
- d: "M146.894 101.198L139.51 101.155L139.486 105.365",
9556
- stroke: "#A1A1AA",
9557
- strokeWidth: "1.5",
9558
- strokeLinecap: "round",
9559
- strokeLinejoin: "round"
9386
+ data: variants,
9387
+ columns,
9388
+ isLoading: isPending,
9389
+ getRowId: (row) => row.id,
9390
+ rowCount: count,
9391
+ prefix: VARIANT_PREFIX,
9392
+ layout: "fill",
9393
+ rowSelection: {
9394
+ state: rowSelection,
9395
+ onRowSelectionChange: setRowSelection,
9396
+ enableRowSelection: (row) => {
9397
+ return !items.find((i) => i.variant_id === row.original.id);
9398
+ }
9399
+ },
9400
+ autoFocusSearch: true
9560
9401
  }
9561
9402
  ) }),
9562
- /* @__PURE__ */ jsxs("defs", { children: [
9563
- /* @__PURE__ */ jsx("clipPath", { id: "clip0_20915_38670", children: /* @__PURE__ */ jsx(
9564
- "rect",
9565
- {
9566
- width: "12",
9567
- height: "12",
9568
- fill: "white",
9569
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 138.36 74.6508)"
9570
- }
9571
- ) }),
9572
- /* @__PURE__ */ jsx("clipPath", { id: "clip1_20915_38670", children: /* @__PURE__ */ jsx(
9573
- "rect",
9574
- {
9575
- width: "12",
9576
- height: "12",
9577
- fill: "white",
9578
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 148.75 80.6541)"
9579
- }
9580
- ) }),
9581
- /* @__PURE__ */ jsx("clipPath", { id: "clip2_20915_38670", children: /* @__PURE__ */ jsx(
9582
- "rect",
9583
- {
9584
- width: "12",
9585
- height: "12",
9586
- fill: "white",
9587
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 159.141 86.6575)"
9588
- }
9589
- ) }),
9590
- /* @__PURE__ */ jsx("clipPath", { id: "clip3_20915_38670", children: /* @__PURE__ */ jsx(
9591
- "rect",
9592
- {
9593
- width: "12",
9594
- height: "12",
9595
- fill: "white",
9596
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 120.928 84.4561)"
9597
- }
9598
- ) }),
9599
- /* @__PURE__ */ jsx("clipPath", { id: "clip4_20915_38670", children: /* @__PURE__ */ jsx(
9600
- "rect",
9403
+ /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
9404
+ /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
9405
+ /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Update items" })
9406
+ ] }) })
9407
+ ]
9408
+ }
9409
+ );
9410
+ };
9411
+ const columnHelper = createDataTableColumnHelper();
9412
+ const getVariantInventory = (variant) => {
9413
+ if (!variant.manage_inventory) {
9414
+ return { text: "Not managed", hasInventoryKit: false, notManaged: true };
9415
+ }
9416
+ const quantity = variant.inventory_quantity;
9417
+ const inventoryItems = variant.inventory_items?.map((i) => i.inventory).filter(Boolean) ?? [];
9418
+ const hasInventoryKit = inventoryItems.length > 1;
9419
+ const locations = {};
9420
+ inventoryItems.forEach((i) => {
9421
+ i.location_levels?.forEach((l) => {
9422
+ locations[l.id] = true;
9423
+ });
9424
+ });
9425
+ const locationCount = Object.keys(locations).length;
9426
+ const text = hasInventoryKit ? `${quantity} available` : `${quantity} available at ${locationCount} location${locationCount === 1 ? "" : "s"}`;
9427
+ return { text, hasInventoryKit, quantity, notManaged: false };
9428
+ };
9429
+ const useColumns = () => {
9430
+ return useMemo(() => {
9431
+ return [
9432
+ columnHelper.select(),
9433
+ columnHelper.accessor("product.title", {
9434
+ header: "Product",
9435
+ cell: ({ row }) => {
9436
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
9437
+ /* @__PURE__ */ jsx(
9438
+ Thumbnail,
9439
+ {
9440
+ thumbnail: row.original.product?.thumbnail,
9441
+ alt: row.original.product?.title
9442
+ }
9443
+ ),
9444
+ /* @__PURE__ */ jsx("span", { children: row.original.product?.title })
9445
+ ] });
9446
+ },
9447
+ enableSorting: true
9448
+ }),
9449
+ columnHelper.accessor("title", {
9450
+ header: "Variant",
9451
+ enableSorting: true
9452
+ }),
9453
+ columnHelper.accessor("sku", {
9454
+ header: "SKU",
9455
+ cell: ({ getValue }) => {
9456
+ return getValue() ?? "-";
9457
+ },
9458
+ enableSorting: true
9459
+ }),
9460
+ columnHelper.accessor("updated_at", {
9461
+ header: "Updated",
9462
+ cell: ({ getValue }) => {
9463
+ return /* @__PURE__ */ jsx(
9464
+ Tooltip,
9601
9465
  {
9602
- width: "12",
9603
- height: "12",
9604
- fill: "white",
9605
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 131.318 90.4594)"
9466
+ content: getFullDate({ date: getValue(), includeTime: true }),
9467
+ children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
9606
9468
  }
9607
- ) }),
9608
- /* @__PURE__ */ jsx("clipPath", { id: "clip5_20915_38670", children: /* @__PURE__ */ jsx(
9609
- "rect",
9469
+ );
9470
+ },
9471
+ enableSorting: true,
9472
+ sortAscLabel: "Oldest first",
9473
+ sortDescLabel: "Newest first"
9474
+ }),
9475
+ columnHelper.accessor("created_at", {
9476
+ header: "Created",
9477
+ cell: ({ getValue }) => {
9478
+ return /* @__PURE__ */ jsx(
9479
+ Tooltip,
9610
9480
  {
9611
- width: "12",
9612
- height: "12",
9613
- fill: "white",
9614
- transform: "matrix(0.865865 0.500278 -0.871576 0.490261 141.709 96.4627)"
9481
+ content: getFullDate({ date: getValue(), includeTime: true }),
9482
+ children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
9615
9483
  }
9616
- ) })
9617
- ] })
9618
- ]
9619
- }
9620
- );
9484
+ );
9485
+ },
9486
+ enableSorting: true,
9487
+ sortAscLabel: "Oldest first",
9488
+ sortDescLabel: "Newest first"
9489
+ }),
9490
+ columnHelper.display({
9491
+ id: "inventory",
9492
+ header: "Stock",
9493
+ cell: ({ row }) => {
9494
+ const { text, hasInventoryKit, quantity, notManaged } = getVariantInventory(row.original);
9495
+ return /* @__PURE__ */ jsx(Tooltip, { content: text, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full items-center gap-2 overflow-hidden", children: [
9496
+ hasInventoryKit && /* @__PURE__ */ jsx(Component, {}),
9497
+ /* @__PURE__ */ jsx(
9498
+ "span",
9499
+ {
9500
+ className: clx("truncate", {
9501
+ "text-ui-fg-error": !quantity && !notManaged
9502
+ }),
9503
+ children: text
9504
+ }
9505
+ )
9506
+ ] }) });
9507
+ }
9508
+ })
9509
+ ];
9510
+ }, []);
9621
9511
  };
9622
- const schema = z.object({
9623
- customer_id: z.string().min(1)
9512
+ const CustomItemForm = ({ orderId, currencyCode }) => {
9513
+ const { setIsOpen } = useStackedModal();
9514
+ const { mutateAsync: addItems } = useDraftOrderAddItems(orderId);
9515
+ const form = useForm({
9516
+ defaultValues: {
9517
+ title: "",
9518
+ quantity: 1,
9519
+ unit_price: ""
9520
+ },
9521
+ resolver: zodResolver(customItemSchema)
9522
+ });
9523
+ const onSubmit = form.handleSubmit(async (data) => {
9524
+ await addItems(
9525
+ {
9526
+ items: [
9527
+ {
9528
+ title: data.title,
9529
+ quantity: data.quantity,
9530
+ unit_price: convertNumber(data.unit_price)
9531
+ }
9532
+ ]
9533
+ },
9534
+ {
9535
+ onSuccess: () => {
9536
+ setIsOpen(STACKED_MODAL_ID, false);
9537
+ },
9538
+ onError: (e) => {
9539
+ toast.error(e.message);
9540
+ }
9541
+ }
9542
+ );
9543
+ });
9544
+ return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx(KeyboundForm, { onSubmit, children: /* @__PURE__ */ jsxs(StackedFocusModal.Content, { children: [
9545
+ /* @__PURE__ */ jsx(StackedFocusModal.Header, {}),
9546
+ /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-6 px-2 py-16", children: [
9547
+ /* @__PURE__ */ jsxs("div", { children: [
9548
+ /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Add custom item" }) }),
9549
+ /* @__PURE__ */ jsx(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Add a custom item to the order. This will add a new line item that is not associated with an existing product." }) })
9550
+ ] }),
9551
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
9552
+ /* @__PURE__ */ jsx(
9553
+ Form$2.Field,
9554
+ {
9555
+ control: form.control,
9556
+ name: "title",
9557
+ render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
9558
+ /* @__PURE__ */ jsxs("div", { children: [
9559
+ /* @__PURE__ */ jsx(Form$2.Label, { children: "Title" }),
9560
+ /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the title of the item" })
9561
+ ] }),
9562
+ /* @__PURE__ */ jsxs("div", { children: [
9563
+ /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
9564
+ /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
9565
+ ] })
9566
+ ] }) })
9567
+ }
9568
+ ),
9569
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
9570
+ /* @__PURE__ */ jsx(
9571
+ Form$2.Field,
9572
+ {
9573
+ control: form.control,
9574
+ name: "unit_price",
9575
+ render: ({ field: { onChange, ...field } }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
9576
+ /* @__PURE__ */ jsxs("div", { children: [
9577
+ /* @__PURE__ */ jsx(Form$2.Label, { children: "Unit price" }),
9578
+ /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the unit price of the item" })
9579
+ ] }),
9580
+ /* @__PURE__ */ jsxs("div", { children: [
9581
+ /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
9582
+ CurrencyInput,
9583
+ {
9584
+ symbol: getNativeSymbol(currencyCode),
9585
+ code: currencyCode,
9586
+ onValueChange: (_value, _name, values) => onChange(values?.value),
9587
+ ...field
9588
+ }
9589
+ ) }),
9590
+ /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
9591
+ ] })
9592
+ ] }) })
9593
+ }
9594
+ ),
9595
+ /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
9596
+ /* @__PURE__ */ jsx(
9597
+ Form$2.Field,
9598
+ {
9599
+ control: form.control,
9600
+ name: "quantity",
9601
+ render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
9602
+ /* @__PURE__ */ jsxs("div", { children: [
9603
+ /* @__PURE__ */ jsx(Form$2.Label, { children: "Quantity" }),
9604
+ /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the quantity of the item" })
9605
+ ] }),
9606
+ /* @__PURE__ */ jsxs("div", { className: "w-full flex-1", children: [
9607
+ /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(NumberInput, { ...field, className: "w-full" }) }) }),
9608
+ /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
9609
+ ] })
9610
+ ] }) })
9611
+ }
9612
+ )
9613
+ ] }) }) }),
9614
+ /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
9615
+ /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
9616
+ /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Add item" })
9617
+ ] }) })
9618
+ ] }) }) });
9619
+ };
9620
+ const customItemSchema = z.object({
9621
+ title: z.string().min(1),
9622
+ quantity: z.number(),
9623
+ unit_price: z.union([z.number(), z.string()])
9624
9624
  });
9625
9625
  const handle = {
9626
- permissions: TRANSFER_DRAFT_ORDER_PERMISSIONS
9626
+ permissions: EDIT_DRAFT_ORDER_PERMISSIONS
9627
9627
  };
9628
9628
  const widgetModule = { widgets: [] };
9629
9629
  const routeModule = {
@@ -9661,39 +9661,39 @@ const routeModule = {
9661
9661
  path: "/draft-orders/:id/email",
9662
9662
  handle: handle$7
9663
9663
  },
9664
- {
9665
- Component: Items,
9666
- path: "/draft-orders/:id/items",
9667
- handle: handle$6
9668
- },
9669
9664
  {
9670
9665
  Component: Metadata,
9671
9666
  path: "/draft-orders/:id/metadata",
9672
- handle: handle$5
9667
+ handle: handle$6
9673
9668
  },
9674
9669
  {
9675
9670
  Component: Promotions,
9676
9671
  path: "/draft-orders/:id/promotions",
9677
- handle: handle$4
9672
+ handle: handle$5
9678
9673
  },
9679
9674
  {
9680
9675
  Component: SalesChannel,
9681
9676
  path: "/draft-orders/:id/sales-channel",
9682
- handle: handle$3
9677
+ handle: handle$4
9683
9678
  },
9684
9679
  {
9685
9680
  Component: Shipping,
9686
9681
  path: "/draft-orders/:id/shipping",
9687
- handle: handle$2
9682
+ handle: handle$3
9688
9683
  },
9689
9684
  {
9690
9685
  Component: ShippingAddress,
9691
9686
  path: "/draft-orders/:id/shipping-address",
9692
- handle: handle$1
9687
+ handle: handle$2
9693
9688
  },
9694
9689
  {
9695
9690
  Component: TransferOwnership,
9696
9691
  path: "/draft-orders/:id/transfer-ownership",
9692
+ handle: handle$1
9693
+ },
9694
+ {
9695
+ Component: Items,
9696
+ path: "/draft-orders/:id/items",
9697
9697
  handle
9698
9698
  }
9699
9699
  ]