@medusajs/draft-order 2.22.4-preview-20261106081111 → 2.22.4

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, EllipsisVertical, ArrowUpMini, ArrowDownMini, Minus, PencilSquare, Component } 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, Minus, PencilSquare, Component, EllipsisVertical, ArrowUpMini, ArrowDownMini } 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,820 +6379,939 @@ const schema$3 = z.object({
6379
6379
  const handle$7 = {
6380
6380
  permissions: EDIT_DRAFT_ORDER_PERMISSIONS
6381
6381
  };
6382
- const InlineTip = forwardRef(
6383
- ({ variant = "tip", label, className, children, ...props }, ref) => {
6384
- const labelValue = label || (variant === "warning" ? "Warning" : "Tip");
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
+ };
6385
6412
  return /* @__PURE__ */ jsxs(
6386
6413
  "div",
6387
6414
  {
6388
- ref,
6389
6415
  className: clx(
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",
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
+ },
6391
6422
  className
6392
6423
  ),
6393
- ...props,
6394
6424
  children: [
6395
6425
  /* @__PURE__ */ jsx(
6396
- "div",
6426
+ "input",
6397
6427
  {
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
- })
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
6402
6441
  }
6403
6442
  ),
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
- ] })
6443
+ /* @__PURE__ */ jsxs(
6444
+ "button",
6445
+ {
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
+ ]
6463
+ }
6464
+ ),
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
+ )
6412
6487
  ]
6413
6488
  }
6414
6489
  );
6415
6490
  }
6416
6491
  );
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 = () => {
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 = () => {
6427
6558
  const { id } = useParams();
6428
- const { order, isPending, isError, error } = useOrder(id, {
6429
- fields: "metadata"
6559
+ const {
6560
+ order: preview,
6561
+ isPending: isPreviewPending,
6562
+ isError: isPreviewError,
6563
+ error: previewError
6564
+ } = useOrderPreview(id, void 0, {
6565
+ placeholderData: keepPreviousData
6430
6566
  });
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 });
6431
6578
  if (isError) {
6432
6579
  throw error;
6433
6580
  }
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
- ] });
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
+ ] }) });
6442
6589
  };
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 }) => {
6590
+ const ItemsForm = ({ preview, currencyCode }) => {
6591
+ const [isSubmitting, setIsSubmitting] = useState(false);
6592
+ const [modalContent, setModalContent] = useState(
6593
+ null
6594
+ );
6446
6595
  const { handleSuccess } = useRouteModal();
6447
- const hasUneditableRows = getHasUneditableRows(metadata);
6448
- const { mutateAsync, isPending } = useUpdateDraftOrder(orderId);
6449
- const form = useForm({
6450
- defaultValues: {
6451
- metadata: getDefaultValues(metadata)
6452
- },
6453
- resolver: zodResolver(MetadataSchema)
6454
- });
6455
- const handleSubmit = form.handleSubmit(async (data) => {
6456
- const parsedData = parseValues(data);
6457
- await mutateAsync(
6458
- {
6459
- metadata: parsedData
6460
- },
6461
- {
6462
- onSuccess: () => {
6463
- toast.success("Metadata updated");
6464
- handleSuccess();
6465
- },
6466
- onError: (error) => {
6467
- toast.error(error.message);
6468
- }
6469
- }
6470
- );
6471
- });
6472
- const { fields, insert, remove } = useFieldArray({
6473
- control: form.control,
6474
- name: "metadata"
6475
- });
6476
- function deleteRow(index) {
6477
- remove(index);
6478
- if (fields.length === 1) {
6479
- insert(0, {
6480
- key: "",
6481
- value: "",
6482
- disabled: false
6483
- });
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;
6484
6621
  }
6485
- }
6486
- function insertRow(index, position) {
6487
- insert(index + (position === "above" ? 0 : 1), {
6488
- key: "",
6489
- value: "",
6490
- disabled: false
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
+ }
6491
6632
  });
6492
- }
6493
- return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
6494
- KeyboundForm,
6495
- {
6496
- onSubmit: handleSubmit,
6497
- className: "flex flex-1 flex-col overflow-hidden",
6498
- children: [
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" }) })
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" }) })
6504
6667
  ] }),
6505
- fields.map((field, index) => {
6506
- const isDisabled = field.disabled || false;
6507
- let placeholder = "-";
6508
- if (typeof field.value === "object") {
6509
- placeholder = "{ ... }";
6510
- }
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,
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,
6570
6690
  {
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, {}) })
6691
+ type: "add-items",
6692
+ setModalContent
6580
6693
  }
6581
6694
  ),
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
- ] })
6695
+ /* @__PURE__ */ jsx(
6696
+ StackedModalTrigger$1,
6697
+ {
6698
+ type: "add-custom-item",
6699
+ setModalContent
6700
+ }
6701
+ )
6618
6702
  ] })
6619
6703
  ] })
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" })
6630
- ] }) })
6631
- ]
6632
- }
6633
- ) });
6634
- };
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
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
+ }
6645
6774
  )
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
6775
  ] }) })
6657
6776
  ] });
6658
6777
  };
6659
- const EDITABLE_TYPES = ["string", "number", "boolean"];
6660
- function getDefaultValues(metadata) {
6661
- if (!metadata || !Object.keys(metadata).length) {
6662
- return [
6663
- {
6664
- key: "",
6665
- value: "",
6666
- disabled: false
6667
- }
6668
- ];
6778
+ const Item = ({ item, preview, currencyCode }) => {
6779
+ if (item.variant_id) {
6780
+ return /* @__PURE__ */ jsx(VariantItem, { item, preview, currencyCode });
6669
6781
  }
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
- };
6782
+ return /* @__PURE__ */ jsx(CustomItem, { item, preview, currencyCode });
6783
+ };
6784
+ const VariantItem = ({ item, preview, currencyCode }) => {
6785
+ const [editing, setEditing] = useState(false);
6786
+ const form = useForm({
6787
+ defaultValues: {
6788
+ quantity: item.quantity,
6789
+ unit_price: item.unit_price
6790
+ },
6791
+ resolver: zodResolver(variantItemSchema)
6687
6792
  });
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) {
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);
6701
6803
  return;
6702
6804
  }
6703
- if (disabled) {
6704
- update[key] = value;
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
+ );
6705
6821
  return;
6706
6822
  }
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;
6719
- }
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;
6720
6833
  }
6721
- });
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
- }
6732
- const handle$6 = {
6733
- permissions: EDIT_DRAFT_ORDER_PERMISSIONS
6734
- };
6735
- const NumberInput = forwardRef(
6736
- ({
6737
- value,
6738
- onChange,
6739
- size = "base",
6740
- min = 0,
6741
- max = 100,
6742
- step = 1,
6743
- className,
6744
- disabled,
6745
- ...props
6746
- }, ref) => {
6747
- const handleChange = (event) => {
6748
- const newValue = event.target.value === "" ? min : Number(event.target.value);
6749
- if (!isNaN(newValue) && (max === void 0 || newValue <= max) && (min === void 0 || newValue >= min)) {
6750
- onChange(newValue);
6751
- }
6752
- };
6753
- const handleIncrement = () => {
6754
- const newValue = value + step;
6755
- if (max === void 0 || newValue <= max) {
6756
- onChange(newValue);
6757
- }
6758
- };
6759
- const handleDecrement = () => {
6760
- const newValue = value - step;
6761
- if (min === void 0 || newValue >= min) {
6762
- onChange(newValue);
6763
- }
6764
- };
6765
- return /* @__PURE__ */ jsxs(
6766
- "div",
6834
+ await updateActionItem(
6767
6835
  {
6768
- className: clx(
6769
- "inline-flex rounded-md bg-ui-bg-field shadow-borders-base overflow-hidden divide-x transition-fg",
6770
- "[&:has(input:focus)]:shadow-borders-interactive-with-active",
6771
- {
6772
- "h-7": size === "small",
6773
- "h-8": size === "base"
6774
- },
6775
- className
6776
- ),
6777
- children: [
6778
- /* @__PURE__ */ jsx(
6779
- "input",
6780
- {
6781
- ref,
6782
- type: "number",
6783
- value,
6784
- onChange: handleChange,
6785
- min,
6786
- max,
6787
- step,
6788
- className: clx(
6789
- "flex-1 px-2 py-1 bg-transparent txt-compact-small text-ui-fg-base outline-none [appearance:textfield]",
6790
- "[&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",
6791
- "placeholder:text-ui-fg-muted"
6792
- ),
6793
- ...props
6794
- }
6795
- ),
6836
+ action_id: actionId,
6837
+ quantity: data.quantity,
6838
+ unit_price: convertNumber(data.unit_price)
6839
+ },
6840
+ {
6841
+ onSuccess: () => {
6842
+ setEditing(false);
6843
+ },
6844
+ onError: (e) => {
6845
+ toast.error(e.message);
6846
+ }
6847
+ }
6848
+ );
6849
+ });
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 }),
6796
6862
  /* @__PURE__ */ jsxs(
6797
- "button",
6863
+ Text,
6798
6864
  {
6799
- className: clx(
6800
- "flex items-center justify-center outline-none transition-fg",
6801
- "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
6802
- "focus:bg-ui-bg-field-component-hover",
6803
- "hover:bg-ui-bg-field-component-hover",
6804
- {
6805
- "size-7": size === "small",
6806
- "size-8": size === "base"
6807
- }
6808
- ),
6809
- type: "button",
6810
- onClick: handleDecrement,
6811
- disabled: min !== void 0 && value <= min || disabled,
6865
+ size: "small",
6866
+ leading: "compact",
6867
+ className: "text-ui-fg-subtle",
6812
6868
  children: [
6813
- /* @__PURE__ */ jsx(Minus, {}),
6814
- /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Decrease by ${step}` })
6869
+ "(",
6870
+ item.variant_title,
6871
+ ")"
6815
6872
  ]
6816
6873
  }
6817
- ),
6818
- /* @__PURE__ */ jsxs(
6819
- "button",
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,
6820
6905
  {
6821
- className: clx(
6822
- "flex items-center justify-center outline-none transition-fg",
6823
- "disabled:cursor-not-allowed disabled:text-ui-fg-muted",
6824
- "focus:bg-ui-bg-field-hover",
6825
- "hover:bg-ui-bg-field-hover",
6826
- {
6827
- "size-7": size === "small",
6828
- "size-8": size === "base"
6829
- }
6830
- ),
6831
- type: "button",
6832
- onClick: handleIncrement,
6833
- disabled: max !== void 0 && value >= max || disabled,
6834
- children: [
6835
- /* @__PURE__ */ jsx(Plus, {}),
6836
- /* @__PURE__ */ jsx("span", { className: "sr-only", children: `Increase by ${step}` })
6837
- ]
6906
+ ...field,
6907
+ symbol: getNativeSymbol(currencyCode),
6908
+ code: currencyCode,
6909
+ onValueChange: (_value, _name, values) => onChange(values?.value)
6838
6910
  }
6839
- )
6840
- ]
6911
+ ) }) });
6912
+ }
6841
6913
  }
6842
- );
6843
- }
6844
- );
6845
- const PRODUCT_VARIANTS_QUERY_KEY = "product-variants";
6846
- const productVariantsQueryKeys = {
6847
- list: (query2) => [
6848
- PRODUCT_VARIANTS_QUERY_KEY,
6849
- query2 ? query2 : void 0
6850
- ]
6851
- };
6852
- const useProductVariants = (query2, options) => {
6853
- const { data, ...rest } = useQuery({
6854
- queryKey: productVariantsQueryKeys.list(query2),
6855
- queryFn: async () => await sdk.admin.productVariant.list(query2),
6856
- ...options
6857
- });
6858
- return { ...data, ...rest };
6859
- };
6860
- const useCancelOrderEdit = ({ preview }) => {
6861
- const { mutateAsync: cancelOrderEdit } = useDraftOrderCancelEdit(preview?.id);
6862
- const onCancel = useCallback(async () => {
6863
- if (!preview) {
6864
- return true;
6865
- }
6866
- let res = false;
6867
- await cancelOrderEdit(void 0, {
6868
- onError: (e) => {
6869
- toast.error(e.message);
6870
- },
6871
- onSuccess: () => {
6872
- res = true;
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, {})
6873
6925
  }
6874
- });
6875
- return res;
6876
- }, [preview, cancelOrderEdit]);
6877
- return { onCancel };
6926
+ )
6927
+ ] }) }) });
6878
6928
  };
6879
- let IS_REQUEST_RUNNING = false;
6880
- const useInitiateOrderEdit = ({
6881
- preview
6882
- }) => {
6883
- const navigate = useNavigate();
6884
- const { mutateAsync } = useDraftOrderBeginEdit(preview?.id);
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)
6943
+ });
6885
6944
  useEffect(() => {
6886
- async function run() {
6887
- if (IS_REQUEST_RUNNING || !preview) {
6888
- return;
6889
- }
6890
- if (preview.order_change) {
6891
- return;
6892
- }
6893
- IS_REQUEST_RUNNING = true;
6894
- await mutateAsync(void 0, {
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
+ },
6895
6986
  onError: (e) => {
6896
6987
  toast.error(e.message);
6897
- navigate(`/draft-orders/${preview.id}`, { replace: true });
6898
- return;
6899
6988
  }
6900
6989
  });
6901
- IS_REQUEST_RUNNING = false;
6990
+ return;
6902
6991
  }
6903
- run();
6904
- }, [preview, navigate, mutateAsync]);
6905
- };
6906
- function convertNumber(value) {
6907
- return typeof value === "string" ? Number(value.replace(",", ".")) : value;
6908
- }
6909
- const STACKED_MODAL_ID = "items_stacked_modal";
6910
- const Items = () => {
6911
- const { id } = useParams();
6912
- const {
6913
- order: preview,
6914
- isPending: isPreviewPending,
6915
- isError: isPreviewError,
6916
- error: previewError
6917
- } = useOrderPreview(id, void 0, {
6918
- placeholderData: keepPreviousData
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
+ );
6919
7007
  });
6920
- useInitiateOrderEdit({ preview });
6921
- const { draft_order, isPending, isError, error } = useDraftOrder(
6922
- id,
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(
6923
7106
  {
6924
- fields: "currency_code"
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"
6925
7112
  },
6926
7113
  {
6927
- enabled: !!id
7114
+ placeholderData: keepPreviousData
6928
7115
  }
6929
7116
  );
6930
- const { onCancel } = useCancelOrderEdit({ preview });
6931
- if (isError) {
6932
- throw error;
6933
- }
6934
- if (isPreviewError) {
6935
- throw previewError;
6936
- }
6937
- const ready = !!preview && !isPreviewPending && !!draft_order && !isPending;
6938
- return /* @__PURE__ */ jsx(RouteFocusModal, { onClose: onCancel, children: ready ? /* @__PURE__ */ jsx(ItemsForm, { preview, currencyCode: draft_order.currency_code }) : /* @__PURE__ */ jsxs("div", { children: [
6939
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Edit Items" }) }),
6940
- /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Loading data for the draft order, please wait..." }) })
6941
- ] }) });
6942
- };
6943
- const ItemsForm = ({ preview, currencyCode }) => {
6944
- const [isSubmitting, setIsSubmitting] = useState(false);
6945
- const [modalContent, setModalContent] = useState(
6946
- null
6947
- );
6948
- const { handleSuccess } = useRouteModal();
6949
- const { searchValue, onSearchValueChange, query: query2 } = useDebouncedSearch();
6950
- const { hasPermission } = usePermissions();
6951
- const canReadVariants = hasPermission("product_variant:read");
6952
- const { mutateAsync: confirmOrderEdit } = useDraftOrderConfirmEdit(preview.id);
6953
- const { mutateAsync: requestOrderEdit } = useDraftOrderRequestEdit(preview.id);
6954
- const itemCount = preview.items?.reduce((acc, item) => acc + item.quantity, 0) || 0;
6955
- const matches = useMemo(() => {
6956
- return matchSorter(preview.items, query2, {
6957
- keys: ["product_title", "variant_title", "variant_sku", "title"]
6958
- });
6959
- }, [preview.items, query2]);
7117
+ const columns = useColumns();
7118
+ const { mutateAsync } = useDraftOrderAddItems(orderId);
6960
7119
  const onSubmit = async () => {
6961
- setIsSubmitting(true);
6962
- let requestSucceeded = false;
6963
- await requestOrderEdit(void 0, {
6964
- onError: (e) => {
6965
- toast.error(`Failed to request order edit: ${e.message}`);
6966
- },
6967
- onSuccess: () => {
6968
- requestSucceeded = true;
6969
- }
6970
- });
6971
- if (!requestSucceeded) {
6972
- setIsSubmitting(false);
6973
- return;
6974
- }
6975
- await confirmOrderEdit(void 0, {
6976
- onError: (e) => {
6977
- toast.error(`Failed to confirm order edit: ${e.message}`);
6978
- },
6979
- onSuccess: () => {
6980
- handleSuccess();
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
+ }))
6981
7129
  },
6982
- onSettled: () => {
6983
- setIsSubmitting(false);
7130
+ {
7131
+ onSuccess: () => {
7132
+ setRowSelection({});
7133
+ setIsOpen(STACKED_MODAL_ID, false);
7134
+ },
7135
+ onError: (e) => {
7136
+ toast.error(e.message);
7137
+ }
6984
7138
  }
6985
- });
7139
+ );
6986
7140
  };
6987
- const onKeyDown = useCallback(
6988
- (e) => {
6989
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
6990
- if (modalContent || isSubmitting) {
6991
- return;
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();
6992
7154
  }
6993
- onSubmit();
6994
- }
6995
- },
6996
- [modalContent, isSubmitting, onSubmit]
7155
+ },
7156
+ 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);
7176
+ }
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" })
7184
+ ] }) })
7185
+ ]
7186
+ }
6997
7187
  );
6998
- useEffect(() => {
6999
- document.addEventListener("keydown", onKeyDown);
7000
- return () => {
7001
- document.removeEventListener("keydown", onKeyDown);
7002
- };
7003
- }, [onKeyDown]);
7004
- return /* @__PURE__ */ jsxs("div", { className: "flex h-full flex-col overflow-hidden", children: [
7005
- /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
7006
- /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsxs(
7007
- StackedFocusModal,
7008
- {
7009
- id: STACKED_MODAL_ID,
7010
- onOpenChangeCallback: (open) => {
7011
- if (!open) {
7012
- setModalContent(null);
7013
- }
7188
+ };
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 };
7206
+ };
7207
+ const useColumns = () => {
7208
+ return useMemo(() => {
7209
+ 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
+ ] });
7014
7224
  },
7015
- children: [
7016
- /* @__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: [
7017
- /* @__PURE__ */ jsxs("div", { children: [
7018
- /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Items" }) }),
7019
- /* @__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" }) })
7020
- ] }),
7021
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7022
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-6", children: [
7023
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 items-center gap-3", children: [
7024
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
7025
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Items" }),
7026
- /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Choose items from the product catalog." })
7027
- ] }),
7028
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
7029
- /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
7030
- Input,
7031
- {
7032
- type: "search",
7033
- placeholder: "Search items",
7034
- value: searchValue,
7035
- onChange: (e) => onSearchValueChange(e.target.value)
7036
- }
7037
- ) }),
7038
- /* @__PURE__ */ jsxs(DropdownMenu, { children: [
7039
- /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(IconButton, { type: "button", children: /* @__PURE__ */ jsx(Plus, {}) }) }),
7040
- /* @__PURE__ */ jsxs(DropdownMenu.Content, { children: [
7041
- canReadVariants && /* @__PURE__ */ jsx(
7042
- StackedModalTrigger$1,
7043
- {
7044
- type: "add-items",
7045
- setModalContent
7046
- }
7047
- ),
7048
- /* @__PURE__ */ jsx(
7049
- StackedModalTrigger$1,
7050
- {
7051
- type: "add-custom-item",
7052
- setModalContent
7053
- }
7054
- )
7055
- ] })
7056
- ] })
7057
- ] })
7058
- ] }),
7059
- /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-subtle shadow-elevation-card-rest rounded-xl", children: [
7060
- /* @__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: [
7061
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Item" }) }),
7062
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Quantity" }) }),
7063
- /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: "Price" }) }),
7064
- /* @__PURE__ */ jsx("div", {})
7065
- ] }) }),
7066
- /* @__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: [
7067
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "There are no items in this order" }),
7068
- /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: "Add items to the order to get started." })
7069
- ] }) : matches.length > 0 ? matches?.map((item) => /* @__PURE__ */ jsx(
7070
- Item,
7071
- {
7072
- item,
7073
- preview,
7074
- currencyCode
7075
- },
7076
- item.id
7077
- )) : /* @__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: [
7078
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "No items found" }),
7079
- /* @__PURE__ */ jsxs(Text, { size: "small", className: "text-ui-fg-subtle", children: [
7080
- 'No items found for "',
7081
- query2,
7082
- '".'
7083
- ] })
7084
- ] }) })
7085
- ] })
7086
- ] }),
7087
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7088
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[1fr_0.5fr_0.5fr] gap-3", children: [
7089
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: "Subtotal" }) }),
7090
- /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(
7091
- Text,
7092
- {
7093
- size: "small",
7094
- leading: "compact",
7095
- className: "text-ui-fg-subtle",
7096
- children: [
7097
- itemCount,
7098
- " ",
7099
- itemCount === 1 ? "item" : "items"
7100
- ]
7101
- }
7102
- ) }),
7103
- /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: getStylizedAmount(preview.item_subtotal, currencyCode) }) })
7104
- ] })
7105
- ] }) }),
7106
- modalContent && (modalContent === "add-items" ? /* @__PURE__ */ jsx(ExistingItemsForm, { orderId: preview.id, items: preview.items }) : modalContent === "add-custom-item" ? /* @__PURE__ */ jsx(
7107
- CustomItemForm,
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,
7108
7243
  {
7109
- orderId: preview.id,
7110
- currencyCode
7244
+ content: getFullDate({ date: getValue(), includeTime: true }),
7245
+ children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
7111
7246
  }
7112
- ) : null)
7113
- ]
7114
- }
7115
- ) }),
7116
- /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7117
- /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7118
- /* @__PURE__ */ jsx(
7119
- Button,
7120
- {
7121
- size: "small",
7122
- type: "button",
7123
- onClick: onSubmit,
7124
- isLoading: isSubmitting,
7125
- children: "Save"
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
+ ] }) });
7126
7285
  }
7127
- )
7128
- ] }) })
7129
- ] });
7130
- };
7131
- const Item = ({ item, preview, currencyCode }) => {
7132
- if (item.variant_id) {
7133
- return /* @__PURE__ */ jsx(VariantItem, { item, preview, currencyCode });
7134
- }
7135
- return /* @__PURE__ */ jsx(CustomItem, { item, preview, currencyCode });
7286
+ })
7287
+ ];
7288
+ }, []);
7136
7289
  };
7137
- const VariantItem = ({ item, preview, currencyCode }) => {
7138
- const [editing, setEditing] = useState(false);
7290
+ const CustomItemForm = ({ orderId, currencyCode }) => {
7291
+ const { setIsOpen } = useStackedModal();
7292
+ const { mutateAsync: addItems } = useDraftOrderAddItems(orderId);
7139
7293
  const form = useForm({
7140
7294
  defaultValues: {
7141
- quantity: item.quantity,
7142
- unit_price: item.unit_price
7295
+ title: "",
7296
+ quantity: 1,
7297
+ unit_price: ""
7143
7298
  },
7144
- resolver: zodResolver(variantItemSchema)
7299
+ resolver: zodResolver(customItemSchema)
7145
7300
  });
7146
- const actionId = useMemo(() => {
7147
- return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
7148
- }, [item]);
7149
- const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
7150
- const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
7151
- const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
7152
- const isPending = isUpdatingActionItem || isUpdatingOriginalItem || isRemovingActionItem;
7153
7301
  const onSubmit = form.handleSubmit(async (data) => {
7154
- if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity) {
7155
- setEditing(false);
7156
- return;
7157
- }
7158
- if (!actionId) {
7159
- await updateOriginalItem(
7160
- {
7161
- item_id: item.id,
7162
- quantity: data.quantity,
7163
- unit_price: convertNumber(data.unit_price)
7164
- },
7165
- {
7166
- onSuccess: () => {
7167
- setEditing(false);
7168
- },
7169
- onError: (e) => {
7170
- toast.error(e.message);
7171
- }
7172
- }
7173
- );
7174
- return;
7175
- }
7176
- if (data.quantity === 0) {
7177
- await removeActionItem(actionId, {
7178
- onSuccess: () => {
7179
- setEditing(false);
7180
- },
7181
- onError: (e) => {
7182
- toast.error(e.message);
7183
- }
7184
- });
7185
- return;
7186
- }
7187
- await updateActionItem(
7302
+ await addItems(
7188
7303
  {
7189
- action_id: actionId,
7190
- quantity: data.quantity,
7191
- unit_price: convertNumber(data.unit_price)
7304
+ items: [
7305
+ {
7306
+ title: data.title,
7307
+ quantity: data.quantity,
7308
+ unit_price: convertNumber(data.unit_price)
7309
+ }
7310
+ ]
7192
7311
  },
7193
7312
  {
7194
7313
  onSuccess: () => {
7195
- setEditing(false);
7314
+ setIsOpen(STACKED_MODAL_ID, false);
7196
7315
  },
7197
7316
  onError: (e) => {
7198
7317
  toast.error(e.message);
@@ -7200,559 +7319,440 @@ const VariantItem = ({ item, preview, currencyCode }) => {
7200
7319
  }
7201
7320
  );
7202
7321
  });
7203
- 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: [
7204
- /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center gap-x-3", children: [
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" }),
7205
7330
  /* @__PURE__ */ jsx(
7206
- Thumbnail,
7331
+ Form$2.Field,
7207
7332
  {
7208
- thumbnail: item.thumbnail,
7209
- alt: item.product_title ?? void 0
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
+ ] }) })
7210
7345
  }
7211
7346
  ),
7212
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
7213
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
7214
- /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: item.product_title }),
7215
- /* @__PURE__ */ jsxs(
7216
- Text,
7217
- {
7218
- size: "small",
7219
- leading: "compact",
7220
- className: "text-ui-fg-subtle",
7221
- children: [
7222
- "(",
7223
- item.variant_title,
7224
- ")"
7225
- ]
7226
- }
7227
- )
7228
- ] }),
7229
- /* @__PURE__ */ jsx(
7230
- Text,
7231
- {
7232
- size: "small",
7233
- leading: "compact",
7234
- className: "text-ui-fg-subtle",
7235
- children: item.variant_sku
7236
- }
7237
- )
7238
- ] })
7239
- ] }),
7240
- editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
7241
- Form$2.Field,
7242
- {
7243
- control: form.control,
7244
- name: "quantity",
7245
- render: ({ field }) => {
7246
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
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
+ ] }) })
7247
7371
  }
7248
- }
7249
- ) }) : /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }) }),
7250
- editing ? /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(
7251
- Form$2.Field,
7252
- {
7253
- control: form.control,
7254
- name: "unit_price",
7255
- render: ({ field: { onChange, ...field } }) => {
7256
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7257
- CurrencyInput,
7258
- {
7259
- ...field,
7260
- symbol: getNativeSymbol(currencyCode),
7261
- code: currencyCode,
7262
- onValueChange: (_value, _name, values) => onChange(values?.value)
7263
- }
7264
- ) }) });
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
+ ] }) })
7265
7389
  }
7266
- }
7267
- ) }) : /* @__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) }) }),
7268
- /* @__PURE__ */ jsx(
7269
- IconButton,
7270
- {
7271
- type: "button",
7272
- size: "small",
7273
- onClick: editing ? onSubmit : () => {
7274
- setEditing(true);
7275
- },
7276
- disabled: isPending,
7277
- children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
7278
- }
7279
- )
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
+ ] }) })
7280
7396
  ] }) }) });
7281
7397
  };
7282
- const variantItemSchema = z.object({
7398
+ const customItemSchema = z.object({
7399
+ title: z.string().min(1),
7283
7400
  quantity: z.number(),
7284
7401
  unit_price: z.union([z.number(), z.string()])
7285
7402
  });
7286
- const CustomItem = ({ item, preview, currencyCode }) => {
7287
- const [editing, setEditing] = useState(false);
7288
- const { quantity, unit_price, title } = item;
7403
+ const handle$6 = {
7404
+ permissions: EDIT_DRAFT_ORDER_PERMISSIONS
7405
+ };
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
+ ]
7437
+ }
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 = () => {
7451
+ const { id } = useParams();
7452
+ const { order, isPending, isError, error } = useOrder(id, {
7453
+ fields: "metadata"
7454
+ });
7455
+ if (isError) {
7456
+ throw error;
7457
+ }
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 })
7465
+ ] });
7466
+ };
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 }) => {
7470
+ const { handleSuccess } = useRouteModal();
7471
+ const hasUneditableRows = getHasUneditableRows(metadata);
7472
+ const { mutateAsync, isPending } = useUpdateDraftOrder(orderId);
7289
7473
  const form = useForm({
7290
7474
  defaultValues: {
7291
- title,
7292
- quantity,
7293
- unit_price
7475
+ metadata: getDefaultValues(metadata)
7294
7476
  },
7295
- resolver: zodResolver(customItemSchema)
7477
+ resolver: zodResolver(MetadataSchema)
7296
7478
  });
7297
- useEffect(() => {
7298
- form.reset({
7299
- title,
7300
- quantity,
7301
- unit_price
7302
- });
7303
- }, [form, title, quantity, unit_price]);
7304
- const actionId = useMemo(() => {
7305
- return item.actions?.find((a) => a.action === "ITEM_ADD")?.id;
7306
- }, [item]);
7307
- const { mutateAsync: updateActionItem, isPending: isUpdatingActionItem } = useDraftOrderUpdateActionItem(preview.id);
7308
- const { mutateAsync: removeActionItem, isPending: isRemovingActionItem } = useDraftOrderRemoveActionItem(preview.id);
7309
- const { mutateAsync: updateOriginalItem, isPending: isUpdatingOriginalItem } = useDraftOrderUpdateItem(preview.id);
7310
- const isPending = isUpdatingActionItem || isUpdatingOriginalItem;
7311
- const onSubmit = form.handleSubmit(async (data) => {
7312
- if (convertNumber(data.unit_price) === item.unit_price && data.quantity === item.quantity && data.title === item.title) {
7313
- setEditing(false);
7314
- return;
7315
- }
7316
- if (!actionId) {
7317
- await updateOriginalItem(
7318
- {
7319
- item_id: item.id,
7320
- quantity: data.quantity,
7321
- unit_price: convertNumber(data.unit_price)
7322
- },
7323
- {
7324
- onSuccess: () => {
7325
- setEditing(false);
7326
- },
7327
- onError: (e) => {
7328
- toast.error(e.message);
7329
- }
7330
- }
7331
- );
7332
- return;
7333
- }
7334
- if (data.quantity === 0) {
7335
- await removeActionItem(actionId, {
7336
- onSuccess: () => {
7337
- setEditing(false);
7338
- },
7339
- onError: (e) => {
7340
- toast.error(e.message);
7341
- }
7342
- });
7343
- return;
7344
- }
7345
- await updateActionItem(
7479
+ const handleSubmit = form.handleSubmit(async (data) => {
7480
+ const parsedData = parseValues(data);
7481
+ await mutateAsync(
7346
7482
  {
7347
- action_id: actionId,
7348
- quantity: data.quantity,
7349
- unit_price: convertNumber(data.unit_price)
7483
+ metadata: parsedData
7350
7484
  },
7351
7485
  {
7352
7486
  onSuccess: () => {
7353
- setEditing(false);
7487
+ toast.success("Metadata updated");
7488
+ handleSuccess();
7354
7489
  },
7355
- onError: (e) => {
7356
- toast.error(e.message);
7490
+ onError: (error) => {
7491
+ toast.error(error.message);
7357
7492
  }
7358
7493
  }
7359
7494
  );
7360
7495
  });
7361
- 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: [
7362
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
7363
- /* @__PURE__ */ jsx(
7364
- Thumbnail,
7365
- {
7366
- thumbnail: item.thumbnail,
7367
- alt: item.title ?? void 0
7368
- }
7369
- ),
7370
- editing ? /* @__PURE__ */ jsx(
7371
- Form$2.Field,
7372
- {
7373
- control: form.control,
7374
- name: "title",
7375
- render: ({ field }) => {
7376
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }) });
7377
- }
7378
- }
7379
- ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.title })
7380
- ] }),
7381
- editing ? /* @__PURE__ */ jsx(
7382
- Form$2.Field,
7383
- {
7384
- control: form.control,
7385
- name: "quantity",
7386
- render: ({ field }) => {
7387
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(NumberInput, { ...field }) }) });
7388
- }
7389
- }
7390
- ) : /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", children: item.quantity }),
7391
- editing ? /* @__PURE__ */ jsx(
7392
- Form$2.Field,
7393
- {
7394
- control: form.control,
7395
- name: "unit_price",
7396
- render: ({ field: { onChange, ...field } }) => {
7397
- return /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7398
- CurrencyInput,
7399
- {
7400
- ...field,
7401
- symbol: getNativeSymbol(currencyCode),
7402
- code: currencyCode,
7403
- onValueChange: (_value, _name, values) => onChange(values?.value)
7404
- }
7405
- ) }) });
7406
- }
7407
- }
7408
- ) : /* @__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) }) }),
7409
- /* @__PURE__ */ jsx(
7410
- IconButton,
7411
- {
7412
- type: "button",
7413
- size: "small",
7414
- onClick: editing ? onSubmit : () => {
7415
- setEditing(true);
7416
- },
7417
- disabled: isPending,
7418
- children: editing ? /* @__PURE__ */ jsx(Check, {}) : /* @__PURE__ */ jsx(PencilSquare, {})
7419
- }
7420
- )
7421
- ] }) }) });
7422
- };
7423
- const StackedModalTrigger$1 = ({
7424
- type,
7425
- setModalContent
7426
- }) => {
7427
- const { setIsOpen } = useStackedModal();
7428
- const onClick = useCallback(() => {
7429
- setModalContent(type);
7430
- setIsOpen(STACKED_MODAL_ID, true);
7431
- }, [setModalContent, setIsOpen, type]);
7432
- return /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick, children: type === "add-items" ? "Add items" : "Add custom item" }) });
7433
- };
7434
- const VARIANT_PREFIX = "items";
7435
- const LIMIT = 50;
7436
- const ExistingItemsForm = ({ orderId, items }) => {
7437
- const { setIsOpen } = useStackedModal();
7438
- const [rowSelection, setRowSelection] = useState(
7439
- items.reduce((acc, item) => {
7440
- acc[item.variant_id] = true;
7441
- return acc;
7442
- }, {})
7443
- );
7444
- useEffect(() => {
7445
- setRowSelection(
7446
- items.reduce((acc, item) => {
7447
- if (item.variant_id) {
7448
- acc[item.variant_id] = true;
7449
- }
7450
- return acc;
7451
- }, {})
7452
- );
7453
- }, [items]);
7454
- const { q, order, offset } = useQueryParams(
7455
- ["q", "order", "offset"],
7456
- VARIANT_PREFIX
7457
- );
7458
- const { variants, count, isPending, isError, error } = useProductVariants(
7459
- {
7460
- q,
7461
- order,
7462
- offset: offset ? parseInt(offset) : void 0,
7463
- limit: LIMIT,
7464
- fields: "*inventory_items.inventory.location_levels,+inventory_quantity,+manage_inventory"
7465
- },
7466
- {
7467
- placeholderData: keepPreviousData
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
+ });
7468
7508
  }
7469
- );
7470
- const columns = useColumns();
7471
- const { mutateAsync } = useDraftOrderAddItems(orderId);
7472
- const onSubmit = async () => {
7473
- const ids = Object.keys(rowSelection).filter(
7474
- (id) => !items.find((i) => i.variant_id === id)
7475
- );
7476
- await mutateAsync(
7477
- {
7478
- items: ids.map((id) => ({
7479
- variant_id: id,
7480
- quantity: 1
7481
- }))
7482
- },
7483
- {
7484
- onSuccess: () => {
7485
- setRowSelection({});
7486
- setIsOpen(STACKED_MODAL_ID, false);
7487
- },
7488
- onError: (e) => {
7489
- toast.error(e.message);
7490
- }
7491
- }
7492
- );
7493
- };
7494
- if (isError) {
7495
- throw error;
7496
7509
  }
7497
- return /* @__PURE__ */ jsxs(
7498
- StackedFocusModal.Content,
7510
+ function insertRow(index, position) {
7511
+ insert(index + (position === "above" ? 0 : 1), {
7512
+ key: "",
7513
+ value: "",
7514
+ disabled: false
7515
+ });
7516
+ }
7517
+ return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
7518
+ KeyboundForm,
7499
7519
  {
7500
- onOpenAutoFocus: (e) => {
7501
- e.preventDefault();
7502
- const searchInput = document.querySelector(
7503
- "[data-modal-id='modal-search-input']"
7504
- );
7505
- if (searchInput) {
7506
- searchInput.focus();
7507
- }
7508
- },
7520
+ onSubmit: handleSubmit,
7521
+ className: "flex flex-1 flex-col overflow-hidden",
7509
7522
  children: [
7510
- /* @__PURE__ */ jsxs(StackedFocusModal.Header, { children: [
7511
- /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Product Variants" }) }),
7512
- /* @__PURE__ */ jsx(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Choose product variants to add to the order." }) })
7513
- ] }),
7514
- /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
7515
- DataTable,
7516
- {
7517
- data: variants,
7518
- columns,
7519
- isLoading: isPending,
7520
- getRowId: (row) => row.id,
7521
- rowCount: count,
7522
- prefix: VARIANT_PREFIX,
7523
- layout: "fill",
7524
- rowSelection: {
7525
- state: rowSelection,
7526
- onRowSelectionChange: setRowSelection,
7527
- enableRowSelection: (row) => {
7528
- return !items.find((i) => i.variant_id === row.original.id);
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 = "{ ... }";
7529
7534
  }
7530
- },
7531
- autoFocusSearch: true
7532
- }
7533
- ) }),
7534
- /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7535
- /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7536
- /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Update items" })
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." })
7650
+ ] }),
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" })
7537
7654
  ] }) })
7538
7655
  ]
7539
7656
  }
7540
- );
7657
+ ) });
7541
7658
  };
7542
- const columnHelper = createDataTableColumnHelper();
7543
- const getVariantInventory = (variant) => {
7544
- if (!variant.manage_inventory) {
7545
- return { text: "Not managed", hasInventoryKit: false, notManaged: true };
7546
- }
7547
- const quantity = variant.inventory_quantity;
7548
- const inventoryItems = variant.inventory_items?.map((i) => i.inventory).filter(Boolean) ?? [];
7549
- const hasInventoryKit = inventoryItems.length > 1;
7550
- const locations = {};
7551
- inventoryItems.forEach((i) => {
7552
- i.location_levels?.forEach((l) => {
7553
- locations[l.id] = true;
7554
- });
7555
- });
7556
- const locationCount = Object.keys(locations).length;
7557
- const text = hasInventoryKit ? `${quantity} available` : `${quantity} available at ${locationCount} location${locationCount === 1 ? "" : "s"}`;
7558
- return { text, hasInventoryKit, quantity, notManaged: false };
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
7669
+ )
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
+ ] }) })
7681
+ ] });
7559
7682
  };
7560
- const useColumns = () => {
7561
- return useMemo(() => {
7683
+ const EDITABLE_TYPES = ["string", "number", "boolean"];
7684
+ function getDefaultValues(metadata) {
7685
+ if (!metadata || !Object.keys(metadata).length) {
7562
7686
  return [
7563
- columnHelper.select(),
7564
- columnHelper.accessor("product.title", {
7565
- header: "Product",
7566
- cell: ({ row }) => {
7567
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
7568
- /* @__PURE__ */ jsx(
7569
- Thumbnail,
7570
- {
7571
- thumbnail: row.original.product?.thumbnail,
7572
- alt: row.original.product?.title
7573
- }
7574
- ),
7575
- /* @__PURE__ */ jsx("span", { children: row.original.product?.title })
7576
- ] });
7577
- },
7578
- enableSorting: true
7579
- }),
7580
- columnHelper.accessor("title", {
7581
- header: "Variant",
7582
- enableSorting: true
7583
- }),
7584
- columnHelper.accessor("sku", {
7585
- header: "SKU",
7586
- cell: ({ getValue }) => {
7587
- return getValue() ?? "-";
7588
- },
7589
- enableSorting: true
7590
- }),
7591
- columnHelper.accessor("updated_at", {
7592
- header: "Updated",
7593
- cell: ({ getValue }) => {
7594
- return /* @__PURE__ */ jsx(
7595
- Tooltip,
7596
- {
7597
- content: getFullDate({ date: getValue(), includeTime: true }),
7598
- children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
7599
- }
7600
- );
7601
- },
7602
- enableSorting: true,
7603
- sortAscLabel: "Oldest first",
7604
- sortDescLabel: "Newest first"
7605
- }),
7606
- columnHelper.accessor("created_at", {
7607
- header: "Created",
7608
- cell: ({ getValue }) => {
7609
- return /* @__PURE__ */ jsx(
7610
- Tooltip,
7611
- {
7612
- content: getFullDate({ date: getValue(), includeTime: true }),
7613
- children: /* @__PURE__ */ jsx("span", { children: getFullDate({ date: getValue() }) })
7614
- }
7615
- );
7616
- },
7617
- enableSorting: true,
7618
- sortAscLabel: "Oldest first",
7619
- sortDescLabel: "Newest first"
7620
- }),
7621
- columnHelper.display({
7622
- id: "inventory",
7623
- header: "Stock",
7624
- cell: ({ row }) => {
7625
- const { text, hasInventoryKit, quantity, notManaged } = getVariantInventory(row.original);
7626
- return /* @__PURE__ */ jsx(Tooltip, { content: text, children: /* @__PURE__ */ jsxs("div", { className: "flex h-full w-full items-center gap-2 overflow-hidden", children: [
7627
- hasInventoryKit && /* @__PURE__ */ jsx(Component, {}),
7628
- /* @__PURE__ */ jsx(
7629
- "span",
7630
- {
7631
- className: clx("truncate", {
7632
- "text-ui-fg-error": !quantity && !notManaged
7633
- }),
7634
- children: text
7635
- }
7636
- )
7637
- ] }) });
7638
- }
7639
- })
7640
- ];
7641
- }, []);
7642
- };
7643
- const CustomItemForm = ({ orderId, currencyCode }) => {
7644
- const { setIsOpen } = useStackedModal();
7645
- const { mutateAsync: addItems } = useDraftOrderAddItems(orderId);
7646
- const form = useForm({
7647
- defaultValues: {
7648
- title: "",
7649
- quantity: 1,
7650
- unit_price: ""
7651
- },
7652
- resolver: zodResolver(customItemSchema)
7653
- });
7654
- const onSubmit = form.handleSubmit(async (data) => {
7655
- await addItems(
7656
7687
  {
7657
- items: [
7658
- {
7659
- title: data.title,
7660
- quantity: data.quantity,
7661
- unit_price: convertNumber(data.unit_price)
7662
- }
7663
- ]
7664
- },
7665
- {
7666
- onSuccess: () => {
7667
- setIsOpen(STACKED_MODAL_ID, false);
7668
- },
7669
- onError: (e) => {
7670
- toast.error(e.message);
7671
- }
7688
+ key: "",
7689
+ value: "",
7690
+ disabled: false
7672
7691
  }
7673
- );
7692
+ ];
7693
+ }
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
+ };
7701
+ }
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
+ };
7674
7711
  });
7675
- return /* @__PURE__ */ jsx(Form$2, { ...form, children: /* @__PURE__ */ jsx(KeyboundForm, { onSubmit, children: /* @__PURE__ */ jsxs(StackedFocusModal.Content, { children: [
7676
- /* @__PURE__ */ jsx(StackedFocusModal.Header, {}),
7677
- /* @__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: [
7678
- /* @__PURE__ */ jsxs("div", { children: [
7679
- /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Add custom item" }) }),
7680
- /* @__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." }) })
7681
- ] }),
7682
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7683
- /* @__PURE__ */ jsx(
7684
- Form$2.Field,
7685
- {
7686
- control: form.control,
7687
- name: "title",
7688
- render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7689
- /* @__PURE__ */ jsxs("div", { children: [
7690
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Title" }),
7691
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the title of the item" })
7692
- ] }),
7693
- /* @__PURE__ */ jsxs("div", { children: [
7694
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
7695
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7696
- ] })
7697
- ] }) })
7698
- }
7699
- ),
7700
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7701
- /* @__PURE__ */ jsx(
7702
- Form$2.Field,
7703
- {
7704
- control: form.control,
7705
- name: "unit_price",
7706
- render: ({ field: { onChange, ...field } }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7707
- /* @__PURE__ */ jsxs("div", { children: [
7708
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Unit price" }),
7709
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the unit price of the item" })
7710
- ] }),
7711
- /* @__PURE__ */ jsxs("div", { children: [
7712
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
7713
- CurrencyInput,
7714
- {
7715
- symbol: getNativeSymbol(currencyCode),
7716
- code: currencyCode,
7717
- onValueChange: (_value, _name, values) => onChange(values?.value),
7718
- ...field
7719
- }
7720
- ) }),
7721
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7722
- ] })
7723
- ] }) })
7724
- }
7725
- ),
7726
- /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
7727
- /* @__PURE__ */ jsx(
7728
- Form$2.Field,
7729
- {
7730
- control: form.control,
7731
- name: "quantity",
7732
- render: ({ field }) => /* @__PURE__ */ jsx(Form$2.Item, { children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-x-3", children: [
7733
- /* @__PURE__ */ jsxs("div", { children: [
7734
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Quantity" }),
7735
- /* @__PURE__ */ jsx(Form$2.Hint, { children: "Enter the quantity of the item" })
7736
- ] }),
7737
- /* @__PURE__ */ jsxs("div", { className: "w-full flex-1", children: [
7738
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx("div", { className: "w-full flex-1", children: /* @__PURE__ */ jsx(NumberInput, { ...field, className: "w-full" }) }) }),
7739
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
7740
- ] })
7741
- ] }) })
7742
- }
7743
- )
7744
- ] }) }) }),
7745
- /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
7746
- /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: "Cancel" }) }),
7747
- /* @__PURE__ */ jsx(Button, { size: "small", type: "button", onClick: onSubmit, children: "Add item" })
7748
- ] }) })
7749
- ] }) }) });
7750
- };
7751
- const customItemSchema = z.object({
7752
- title: z.string().min(1),
7753
- quantity: z.number(),
7754
- unit_price: z.union([z.number(), z.string()])
7755
- });
7712
+ }
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;
7718
+ }
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;
7730
+ }
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;
7743
+ }
7744
+ }
7745
+ });
7746
+ return update;
7747
+ }
7748
+ function getHasUneditableRows(metadata) {
7749
+ if (!metadata) {
7750
+ return false;
7751
+ }
7752
+ return Object.values(metadata).some(
7753
+ (value) => !EDITABLE_TYPES.includes(typeof value)
7754
+ );
7755
+ }
7756
7756
  const handle$5 = {
7757
7757
  permissions: EDIT_DRAFT_ORDER_PERMISSIONS
7758
7758
  };
@@ -8034,6 +8034,115 @@ function getPromotionIds(items, shippingMethods) {
8034
8034
  const handle$4 = {
8035
8035
  permissions: EDIT_DRAFT_ORDER_PROMOTIONS_PERMISSIONS
8036
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
+ },
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
+ };
8037
8146
  const STACKED_FOCUS_MODAL_ID = "shipping-form";
8038
8147
  const Shipping = () => {
8039
8148
  const { id } = useParams();
@@ -8828,117 +8937,8 @@ const CustomAmountField = ({
8828
8937
  }
8829
8938
  );
8830
8939
  };
8831
- const handle$3 = {
8832
- permissions: EDIT_DRAFT_ORDER_SHIPPING_PERMISSIONS
8833
- };
8834
- const SalesChannel = () => {
8835
- const { id } = useParams();
8836
- const { draft_order, isPending, isError, error } = useDraftOrder(
8837
- id,
8838
- {
8839
- fields: "+sales_channel_id"
8840
- },
8841
- {
8842
- enabled: !!id
8843
- }
8844
- );
8845
- if (isError) {
8846
- throw error;
8847
- }
8848
- const ISrEADY = !!draft_order && !isPending;
8849
- return /* @__PURE__ */ jsxs(RouteDrawer, { children: [
8850
- /* @__PURE__ */ jsxs(RouteDrawer.Header, { children: [
8851
- /* @__PURE__ */ jsx(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx(Heading, { children: "Edit Sales Channel" }) }),
8852
- /* @__PURE__ */ jsx(RouteDrawer.Description, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Update which sales channel the draft order is associated with" }) })
8853
- ] }),
8854
- ISrEADY && /* @__PURE__ */ jsx(SalesChannelForm, { order: draft_order })
8855
- ] });
8856
- };
8857
- const SalesChannelForm = ({ order }) => {
8858
- const form = useForm({
8859
- defaultValues: {
8860
- sales_channel_id: order.sales_channel_id || ""
8861
- },
8862
- resolver: zodResolver(schema$2)
8863
- });
8864
- const { mutateAsync, isPending } = useUpdateDraftOrder(order.id);
8865
- const { handleSuccess } = useRouteModal();
8866
- const onSubmit = form.handleSubmit(async (data) => {
8867
- await mutateAsync(
8868
- {
8869
- sales_channel_id: data.sales_channel_id
8870
- },
8871
- {
8872
- onSuccess: () => {
8873
- toast.success("Sales channel updated");
8874
- handleSuccess();
8875
- },
8876
- onError: (error) => {
8877
- toast.error(error.message);
8878
- }
8879
- }
8880
- );
8881
- });
8882
- return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
8883
- KeyboundForm,
8884
- {
8885
- className: "flex flex-1 flex-col overflow-hidden",
8886
- onSubmit,
8887
- children: [
8888
- /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "flex flex-col gap-y-6 overflow-y-auto", children: /* @__PURE__ */ jsx(SalesChannelField, { control: form.control, order }) }),
8889
- /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
8890
- /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: "Cancel" }) }),
8891
- /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: "Save" })
8892
- ] }) })
8893
- ]
8894
- }
8895
- ) });
8896
- };
8897
- const SalesChannelField = ({ control, order }) => {
8898
- const salesChannels = useComboboxData({
8899
- queryFn: async (params) => {
8900
- return await sdk.admin.salesChannel.list(params);
8901
- },
8902
- queryKey: ["sales-channels"],
8903
- getOptions: (data) => {
8904
- return data.sales_channels.map((salesChannel) => ({
8905
- label: salesChannel.name,
8906
- value: salesChannel.id
8907
- }));
8908
- },
8909
- defaultValue: order.sales_channel_id || void 0
8910
- });
8911
- return /* @__PURE__ */ jsx(
8912
- Form$2.Field,
8913
- {
8914
- control,
8915
- name: "sales_channel_id",
8916
- render: ({ field }) => {
8917
- return /* @__PURE__ */ jsxs(Form$2.Item, { children: [
8918
- /* @__PURE__ */ jsx(Form$2.Label, { children: "Sales Channel" }),
8919
- /* @__PURE__ */ jsx(Form$2.Control, { children: /* @__PURE__ */ jsx(
8920
- Combobox,
8921
- {
8922
- options: salesChannels.options,
8923
- fetchNextPage: salesChannels.fetchNextPage,
8924
- isFetchingNextPage: salesChannels.isFetchingNextPage,
8925
- searchValue: salesChannels.searchValue,
8926
- onSearchValueChange: salesChannels.onSearchValueChange,
8927
- placeholder: "Select sales channel",
8928
- ...field
8929
- }
8930
- ) }),
8931
- /* @__PURE__ */ jsx(Form$2.ErrorMessage, {})
8932
- ] });
8933
- }
8934
- }
8935
- );
8936
- };
8937
- const schema$2 = z.object({
8938
- sales_channel_id: z.string().min(1)
8939
- });
8940
8940
  const handle$2 = {
8941
- permissions: EDIT_DRAFT_ORDER_SALES_CHANNEL_PERMISSIONS
8941
+ permissions: EDIT_DRAFT_ORDER_SHIPPING_PERMISSIONS
8942
8942
  };
8943
8943
  const ShippingAddress = () => {
8944
8944
  const { id } = useParams();
@@ -9662,13 +9662,13 @@ const routeModule = {
9662
9662
  handle: handle$7
9663
9663
  },
9664
9664
  {
9665
- Component: Metadata,
9666
- path: "/draft-orders/:id/metadata",
9665
+ Component: Items,
9666
+ path: "/draft-orders/:id/items",
9667
9667
  handle: handle$6
9668
9668
  },
9669
9669
  {
9670
- Component: Items,
9671
- path: "/draft-orders/:id/items",
9670
+ Component: Metadata,
9671
+ path: "/draft-orders/:id/metadata",
9672
9672
  handle: handle$5
9673
9673
  },
9674
9674
  {
@@ -9677,13 +9677,13 @@ const routeModule = {
9677
9677
  handle: handle$4
9678
9678
  },
9679
9679
  {
9680
- Component: Shipping,
9681
- path: "/draft-orders/:id/shipping",
9680
+ Component: SalesChannel,
9681
+ path: "/draft-orders/:id/sales-channel",
9682
9682
  handle: handle$3
9683
9683
  },
9684
9684
  {
9685
- Component: SalesChannel,
9686
- path: "/draft-orders/:id/sales-channel",
9685
+ Component: Shipping,
9686
+ path: "/draft-orders/:id/shipping",
9687
9687
  handle: handle$2
9688
9688
  },
9689
9689
  {