import { ref as B, defineComponent as pe, computed as b, resolveComponent as C, openBlock as c, createElementBlock as T, Fragment as X, unref as l, createVNode as s, withModifiers as Bt, createCommentVNode as L, withCtx as g, createElementVNode as n, toDisplayString as F, normalizeClass as te, renderList as ue, createBlock as O, h as Q, renderSlot as xe, createSlots as He, createTextVNode as Ye, mergeModels as dt, onMounted as Dt, watch as Tt, useModel as Ot, isRef as ut, normalizeStyle as Nt, Teleport as ct, normalizeProps as zt, guardReactiveProps as Lt } from "vue";
import { a as Ce, c as wt, S as jt, g as mt, d as pt, e as Wt, f as vt, h as ft, i as yt, j as gt, u as qt, k as Ht } from "./app-Bpb4394e.js";
import { useDialog as Ge, useSnackbar as Fe, components as Oe, useProxiedModel as bt, useDialogChild as Yt, useBreakpoints as Gt } from "@feedmepos/ui-library";
import { i as Kt, _ as Jt } from "./is-linked-ingredient-error-fJ2TJb3z.js";
import { F as q } from "./form-mode.enum-BKiNVH6A.js";
import { useI18n as ve, useCoreStore as Ke } from "@feedmepos/mf-common";
import { defineStore as Zt, storeToRefs as Qt } from "pinia";
import { D as ht, R as Me } from "./row-action.enum-DQ9bJ_uv.js";
import { c as Xt } from "./component-kqxARxvM.js";
import { u as Ae, _ as en } from "./netsuite-BGUUAOqe.js";
import { F as Re } from "./FmAdminBadge-DjnBAgyv.js";
import { u as tn, _ as nn } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { A as Pe, R as Ne, U as on, M as ln } from "./rules-CoimOM7X.js";
import { g as an, _ as ze, S as Le, a as sn } from "./SubsidiaryTreeDialog.vue_vue_type_script_setup_true_lang-C-OhTH0B.js";
import { _ as rn } from "./InventoryBindingForm.vue_vue_type_script_setup_true_lang-D8wXZyxi.js";
import { _ as je } from "./IngredientBindedItem.vue_vue_type_script_setup_true_lang-BBfMiiPT.js";
import { u as Vt } from "./feature-Cz6F0_cm.js";
import { a as dn, t as un, g as cn } from "./number-BVg7EKPV.js";
import { _ as he } from "./PreviewBadge.vue_vue_type_script_setup_true_lang-CRZiQHjx.js";
import { d as Ue, g as mn, e as pn, a as vn } from "./import-export.helper-BnI8EiMF.js";
import { _ as fn } from "./FmCustomAttribute.vue_vue_type_script_setup_true_lang-D-IWRjRD.js";
import { F as yn, a as We } from "./FmMultiselectDialog-D-38fV59.js";
import { u as It } from "./purchase-order-template-BBNXnta7.js";
import { u as St, a as Ct } from "./closing-template-ar_kUs4X.js";
import { _ as gn, F as _t } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { r as bn } from "./xlsx.util-BPV2vsSD.js";
import { F as hn } from "./FmDroppableField-J0xUsOTV.js";
import { _ as _n } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { u as xn } from "./FmMultiselectDialog-DHiMw0t6.js";
import { P as kn, J as Tn } from "./app-DiX-EfV6.js";
const qe = Zt("ingredientForm", function() {
  const r = Ge(), k = Fe(), d = Ce(), h = B(!1), { t: I } = ve(), E = B();
  function P() {
    const a = {
      sku: {},
      mode: q.CREATE,
      show: !0,
      "onUpdate:show"(i) {
        E.value.show = i;
      }
    };
    E.value = a;
  }
  async function o(a) {
    const i = {
      sku: wt(a),
      mode: q.UPDATE,
      show: !0,
      "onUpdate:show"(m) {
        E.value.show = m;
      }
    };
    E.value = i;
  }
  async function u(a) {
    h.value = !0;
    try {
      await d.deleteSku(a), k.open({
        title: "Success",
        message: `Deleted ${a.name}`,
        type: "success"
      });
    } catch (i) {
      i instanceof jt && Kt(i) ? r.open({
        title: "Cannot delete ingredient",
        contentComponent: Jt,
        contentComponentProps: {
          subject: (a == null ? void 0 : a.name) ?? "",
          items: i.errorResponse.message
        },
        secondaryActions: {
          text: "Close",
          close: !0
        }
      }) : console.log("unable to delete ingredient", i), k.open({
        title: `Cannot delete ${a.name}`,
        message: "Please try again.",
        type: "error"
      }), console.error("failed to delete ingredient", i);
    } finally {
      h.value = !1;
    }
  }
  function p(a) {
    r.open({
      title: I("inventory.ingredient.delete.title", [(a == null ? void 0 : a.name) ?? ""]),
      closeButton: !1,
      message: I("inventory.ingredient.delete.message"),
      primaryActions: {
        text: I("common.delete"),
        close: !0,
        variant: "destructive"
      },
      secondaryActions: {
        text: I("common.cancel"),
        close: !0
      }
    }).onPrimary(() => u(a));
  }
  return {
    createIngredient: P,
    updateIngredient: o,
    deleteIngredient: p,
    ingredientDialogProps: E,
    ingredientViewLoading: h
  };
}), wn = {
  key: 0,
  class: "flex items-center gap-8"
}, Vn = { class: "flex flex-col gap-1" }, In = { class: "fm-typo-en-heading-lg-600" }, Sn = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Cn = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Fn = {
  key: 0,
  class: "fm-typo-en-body-md-400 text-fm-color-system-warning-300"
}, An = {
  key: 1,
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, En = { class: "flex flex-col gap-2 mt-4" }, $n = { class: "flex items-center gap-2 fm-typo-en-body-md-400" }, Mn = { class: "flex flex-wrap gap-2" }, Un = { class: "flex flex-col" }, Pn = { class: "flex flex-col bg-fm-color-bg-secondary font-mono p-4 rounded-md" }, Rn = { class: "text-fm-color-typo-tertiary flex-shrink-0 fm-typo-en-body-md-400 whitespace-pre flex items-center" }, Bn = { class: "px-2 py-1 rounded-md bg-blue-200 border-2 border-blue-400" }, Dn = { class: "fm-typo-en-body-md-600 text-fm-color-typo-primary" }, On = /* @__PURE__ */ pe({
  __name: "ItemSubsidiaryTreeDialog",
  props: {
    skuId: {},
    itemName: {},
    itemCode: {}
  },
  setup(W) {
    const r = W, { t: k } = ve(), d = Ke(), h = Ae(), I = B(!1), E = b(() => {
      var m;
      return ((m = d.sessionUser.value) == null ? void 0 : m.role.isAdmin) ?? !1;
    }), P = b(() => h.getSkuSubsidiaries(r.skuId)), o = b(() => {
      const m = /* @__PURE__ */ new Set();
      function f(A) {
        for (const v of A)
          v.isAssigned && (m.add(v.id), P.value.includeChildren && w(v)), v.children && v.children.length > 0 && f(v.children);
      }
      function w(A) {
        if (A.children)
          for (const v of A.children)
            m.add(v.id), w(v);
      }
      return f(P.value.subsidiaryTree), m;
    });
    function u(m, f = [], w = !1) {
      const A = [];
      return m.forEach((v, N) => {
        const D = N === m.length - 1, fe = [...f, D];
        let ne = "";
        for (let ee = 0; ee < f.length; ee++)
          ne += f[ee] ? "    " : "│   ";
        ne += D ? "└── " : "├── ";
        const ce = o.value.has(v.id), oe = v.isAssigned === !0, le = w && !oe;
        if (A.push({
          id: v.id,
          name: v.name,
          prefix: f.length === 0 ? "" : ne,
          isHighlighted: ce,
          isDirectlyBound: oe,
          isParentIncludedChild: le,
          isRoot: f.length === 0
        }), v.children && v.children.length > 0) {
          const ee = w || oe && P.value.includeChildren;
          A.push(...u(v.children, fe, ee));
        }
      }), A;
    }
    function p(m, f = []) {
      const w = /* @__PURE__ */ new Set();
      for (const A of m) {
        const v = [...f, A.id];
        A.isAssigned === !0 && v.forEach((N) => w.add(N)), A.children && A.children.length > 0 && p(A.children, v).forEach((D) => w.add(D));
      }
      return w;
    }
    function a(m, f) {
      return m.map((w) => f.has(w.id) || w.isAssigned === !0 ? {
        ...w,
        // Recursively filter children
        children: w.children ? a(w.children, f) : []
      } : null).filter(Boolean);
    }
    const i = b(() => {
      let m = P.value.subsidiaryTree;
      if ((!m || m.length === 0) && (m = h.getBusinessSubsidiaryTree()), !E.value) {
        const f = p(m);
        m = a(m, f);
      }
      return u(m, []);
    });
    return (m, f) => {
      const w = C("FmButton"), A = C("FmDialog");
      return c(), T(X, null, [
        l(h).isEnabled ? (c(), T("div", wn, [
          s(w, {
            "prepend-icon": "info",
            variant: "tertiary",
            onClick: f[0] || (f[0] = Bt((v) => I.value = !0, ["stop"]))
          })
        ])) : L("", !0),
        s(A, {
          modelValue: I.value,
          "onUpdate:modelValue": f[1] || (f[1] = (v) => I.value = v),
          "close-button": "",
          dismissAway: ""
        }, {
          "dialog-header": g(() => [
            n("div", Vn, [
              n("div", In, F(l(k)("inventory.integration.netsuite.subsidiaryHierarchy.title")), 1),
              n("p", Sn, " Name: " + F(r.itemName), 1),
              n("p", Cn, " Code: " + F(r.itemCode), 1),
              E.value ? (c(), T("p", Fn, " All subsidiaries are shown since you are an admin. ")) : (c(), T("p", An, " Only showing subsidiaries in your business path and bound subsidiaries. ")),
              n("div", En, [
                n("div", $n, [
                  f[2] || (f[2] = n("span", { class: "font-semibold" }, "Include Children Subsidiaries:", -1)),
                  n("span", {
                    class: te(
                      P.value.includeChildren ? "text-green-600 font-semibold" : "text-red-600 font-semibold"
                    )
                  }, F(P.value.includeChildren ? "Yes" : "No"), 3)
                ]),
                n("div", Mn, [
                  f[4] || (f[4] = n("div", { class: "flex items-center gap-2 px-2 py-1 bg-fm-color-bg-brand-secondary rounded-md" }, [
                    n("span", { class: "w-3 h-3 rounded-sm bg-green-400" }),
                    n("span", { class: "fm-typo-en-body-sm-400" }, "Directly Bound")
                  ], -1)),
                  s(Re, null, {
                    default: g(() => f[3] || (f[3] = [
                      n("div", { class: "flex items-center gap-2 px-2 py-1 rounded-md" }, [
                        n("span", { class: "w-3 h-3 rounded-sm bg-blue-400" }),
                        n("span", { class: "fm-typo-en-body-sm-400" }, "Included as Child")
                      ], -1)
                    ])),
                    _: 1
                  })
                ])
              ])
            ])
          ]),
          default: g(() => [
            n("div", Un, [
              n("div", Pn, [
                (c(!0), T(X, null, ue(i.value, (v) => (c(), T("div", {
                  key: v.id,
                  class: "flex items-stretch"
                }, [
                  n("span", Rn, F(v.prefix), 1),
                  v.isParentIncludedChild ? (c(), O(Re, {
                    key: 0,
                    class: "flex-1"
                  }, {
                    default: g(() => [
                      n("div", Bn, [
                        n("span", Dn, F(v.name), 1)
                      ])
                    ]),
                    _: 2
                  }, 1024)) : (c(), T("div", {
                    key: 1,
                    class: te([
                      "px-2 py-1 rounded-md flex-1",
                      v.isDirectlyBound ? "border-2 bg-green-200 border-green-400" : "bg-fm-color-bg-primary border border-fm-color-border-secondary"
                    ])
                  }, [
                    n("span", {
                      class: te([
                        v.isHighlighted ? "fm-typo-en-body-md-600 text-fm-color-typo-primary" : "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
                      ])
                    }, F(v.name), 3)
                  ], 2))
                ]))), 128))
              ])
            ])
          ]),
          _: 1
        }, 8, ["modelValue"])
      ], 64);
    };
  }
});
function Nn() {
  var o;
  const { updateIngredient: W, deleteIngredient: r } = qe(), k = Ce(), d = Ae(), { t: h } = ve(), I = Ke();
  async function E(u, p) {
    const a = wt(p);
    if (u === Me.Edit) {
      await W(a);
      return;
    }
    if (u === Me.Delete) {
      await r(a);
      return;
    }
  }
  return { columnDefs: [
    ...(o = I.sessionUser.value) != null && o.role.isAdmin ? [
      {
        accessorKey: "_id",
        header: () => Q(Re, {}, () => "ID"),
        size: 200
      }
    ] : [],
    {
      accessorKey: "code",
      header: () => h("inventory.ingredient.code"),
      enableSorting: !0,
      size: 200
    },
    {
      accessorKey: "name",
      header: () => h("inventory.ingredient.name"),
      enableSorting: !0,
      size: 300,
      cell(u) {
        const p = u.row.original, a = k.skuBindingFlattenCache[p._id], i = a == null ? void 0 : a.inventoryBindings.some(
          (m) => "error" in m && m.reason === "circularDependency"
        );
        return Q("div", { class: "flex items-center w-full gap-4" }, [
          i ? Q(
            Oe.FmTooltip,
            { class: "text-left" },
            {
              default() {
                return Q(Oe.FmIcon, {
                  name: "info",
                  color: "system-error-300",
                  size: "sm"
                });
              },
              content() {
                return h("inventory.inventoryBindings.circularError");
              }
            }
          ) : null,
          p.name
        ]);
      }
    },
    {
      id: "unit",
      header: () => h("inventory.ingredient.unit"),
      accessorFn: (u) => xt(u),
      cell(u) {
        const p = u.row.original, a = xt(p);
        return Q(
          Oe.FmTooltip,
          { zIndex: 51, content: a },
          Q(
            "span",
            {
              class: "flex-auto line-clamp-2 text-ellipsis break-all"
            },
            a
          )
        );
      },
      enableSorting: !1,
      size: 300
    },
    {
      accessorKey: "isInactive",
      header: () => h("inventory.ingredient.status.title"),
      cell(u) {
        const p = u.row.original.isInactive;
        return Q(
          "span",
          {
            class: [
              "inline-block px-3 py-1 rounded-full text-xs font-semibold",
              p ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"
            ].join(" ")
          },
          h(p ? "inventory.ingredient.status.inactive" : "inventory.ingredient.status.active")
        );
      },
      enableSorting: !0
    },
    {
      id: "netsuiteSubsidiary",
      accessorFn: (u) => d.getSkuSubsidiaries(u._id),
      header: () => "NetSuite Subsidiary",
      cell(u) {
        const p = u.row.original, { flattenedSubsidiaryNames: a } = d.getSkuSubsidiaries(p._id);
        return Q("div", { class: "flex gap-2 items-start" }, [
          Q(
            "span",
            {
              class: "flex-1 line-clamp-2 text-ellipsis break-all whitespace-pre-wrap"
            },
            a.join(", ")
          ),
          Q(On, { skuId: p._id, itemName: p.name, itemCode: p.code })
        ]);
      },
      enableSorting: !1,
      size: "auto"
    },
    {
      id: "action",
      header: "",
      cell(u) {
        return Xt(
          [ht[Me.Edit], ht[Me.Delete]],
          (p) => {
            E(p, u.row.original);
          }
        );
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    }
  ] };
}
function xt(W) {
  var r;
  if (W.trackingMeasurement) {
    const k = (r = W.unit.measurements) == null ? void 0 : r.find((d) => d.id === W.trackingMeasurement);
    if (k)
      return `${k.name} (${k.abbrev})`;
  }
  return `${W.unit.name} (${W.unit.abbrev})`;
}
const zn = /* @__PURE__ */ pe({
  __name: "ConvertForm",
  props: {
    modelValue: {},
    rootValue: {},
    disabled: { type: Boolean },
    readonly: { type: Boolean }
  },
  emits: ["update:modelValue"],
  setup(W, { emit: r }) {
    const k = W, d = b(() => {
      var i;
      return (i = k.rootValue) == null ? void 0 : i.unit;
    }), h = b(() => {
      var i;
      return (i = k.rootValue) == null ? void 0 : i._id;
    }), I = r, { t: E } = ve(), P = b({
      get() {
        return !!k.modelValue;
      },
      set(i) {
        i ? I("update:modelValue", {
          measurement: null,
          inventoryBindings: []
        }) : I("update:modelValue", null);
      }
    }), o = b(() => an(d.value));
    function u(i) {
      const m = k.modelValue ?? {};
      m.measurement = i ? `${i}` : null, I("update:modelValue", m);
    }
    function p(i) {
      const m = k.modelValue ?? {};
      m.inventoryBindings = i, I("update:modelValue", m);
    }
    const a = b(() => {
      if (!k.modelValue) return null;
      const i = k.modelValue;
      return i.measurement ? o.value.find((m) => m.value === i.measurement) ?? null : o.value.find((m) => m.value === null) ?? null;
    });
    return (i, m) => {
      const f = C("FmSwitch"), w = C("FmSelect"), A = C("FmCard");
      return c(), O(A, {
        variant: "outlined",
        class: "p-16 flex flex-col gap-16"
      }, {
        default: g(() => {
          var v, N;
          return [
            s(f, {
              value: "",
              "model-value": P.value,
              "onUpdate:modelValue": m[0] || (m[0] = (D) => P.value = D),
              label: l(E)("inventory.ingredient.convertible.title"),
              sublabel: l(E)("inventory.ingredient.convertible.subtitle"),
              labelPlacement: "right",
              disabled: i.readonly
            }, null, 8, ["model-value", "label", "sublabel", "disabled"]),
            P.value ? (c(), T(X, { key: 0 }, [
              n("div", null, [
                s(w, {
                  label: l(E)("inventory.ingredient.convertible.convertTo"),
                  modelValue: (v = a.value) == null ? void 0 : v.value,
                  "onUpdate:modelValue": u,
                  items: o.value,
                  disabled: i.readonly
                }, null, 8, ["label", "modelValue", "items", "disabled"])
              ]),
              s(rn, {
                id: h.value,
                "model-value": ((N = i.modelValue) == null ? void 0 : N.inventoryBindings) ?? [],
                "onUpdate:modelValue": p,
                "exclude-binding-id": h.value,
                rules: [l(Pe)(1)],
                readonly: i.readonly
              }, null, 8, ["id", "model-value", "exclude-binding-id", "rules", "readonly"])
            ], 64)) : L("", !0)
          ];
        }),
        _: 1
      });
    };
  }
}), Ln = {
  key: 0,
  class: "flex flex-col gap-4"
}, jn = { class: "text-fm-color-typo-secondary whitespace-nowrap" }, Se = /* @__PURE__ */ pe({
  __name: "FmLockableField",
  props: {
    locked: { type: Boolean },
    disabled: { type: Boolean },
    label: {},
    helperText: {},
    modelValue: {},
    tooltipMessage: {},
    tooltipPlacement: {},
    tooltipZIndex: {},
    appendText: {}
  },
  setup(W) {
    return (r, k) => {
      const d = C("FmLabel"), h = C("FmIcon"), I = C("FmTooltip"), E = C("FmField");
      return r.locked ? (c(), T("div", Ln, [
        xe(r.$slots, "label", {}, () => [
          s(d, {
            label: r.label,
            disabled: r.disabled
          }, null, 8, ["label", "disabled"])
        ]),
        xe(r.$slots, "field", {}, () => [
          s(E, { disabled: r.disabled }, He({
            prepend: g(() => [
              r.tooltipMessage ? (c(), O(I, {
                key: 0,
                placement: r.tooltipPlacement,
                "z-index": r.tooltipZIndex
              }, {
                content: g(() => [
                  Ye(F(r.tooltipMessage), 1)
                ]),
                default: g(() => [
                  s(h, {
                    name: "lock",
                    color: "neutral-gray-400"
                  })
                ]),
                _: 1
              }, 8, ["placement", "z-index"])) : (c(), O(h, {
                key: 1,
                name: "lock",
                color: "neutral-gray-400"
              }))
            ]),
            default: g(() => [
              xe(r.$slots, "modelValue", {}, () => [
                n("div", {
                  class: te([
                    r.disabled ? "text-fm-color-typo-disabled" : "text-fm-color-typo-primary",
                    "line-clamp-1 text-ellipsis break-all"
                  ])
                }, F(r.modelValue), 3)
              ])
            ]),
            _: 2
          }, [
            r.appendText || r.$slots.fieldAppend ? {
              name: "append",
              fn: g(() => [
                xe(r.$slots, "fieldAppend", {}, () => [
                  n("div", jn, F(r.appendText), 1)
                ])
              ]),
              key: "0"
            } : void 0
          ]), 1032, ["disabled"])
        ]),
        xe(r.$slots, "helper-text", {}, () => [
          n("div", {
            class: te([
              "fm-typo-en-body-sm-400  line-clamp-1",
              r.disabled ? "text-fm-color-typo-disabled" : "text-fm-color-typo-secondary"
            ])
          }, F(r.helperText), 3)
        ])
      ])) : xe(r.$slots, "default", { key: 1 });
    };
  }
}), Wn = { class: "flex gap-8" }, qn = { class: "flex-1" }, Hn = { class: "flex-1" }, Yn = { class: "flex flex-col gap-5" }, Gn = { class: "text-fm-color-typo-secondary" }, Kn = { class: "text-fm-color-typo-secondary whitespace-nowrap" }, Jn = {
  key: 3,
  class: "border-1 border-fm-color-neutral-gray-200 fm-corner-radius-lg flex flex-col p-16 gap-16"
}, Zn = { class: "flex flex-col" }, Qn = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Xn = {
  key: 4,
  class: "border-1 border-fm-color-neutral-gray-200 fm-corner-radius-lg flex flex-col p-16 gap-16"
}, eo = { class: "flex flex-col gap-12" }, to = { class: "flex flex-col gap-4" }, no = { class: "fm-typo-en-title-sm-600" }, oo = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, lo = { class: "flex flex-col gap-4" }, ao = { class: "flex fm-corner-radius-md border-1 border-fm-color-neutral-gray-200" }, so = { class: "flex-1 p-12 flex flex-col gap-8" }, ro = { class: "mx-auto" }, io = { class: "flex flex-col" }, uo = { class: "fm-typo-en-body-sm-600 translate-y-4" }, co = { class: "flex-1 p-12 flex flex-col gap-8" }, mo = { class: "mx-auto" }, po = { class: "flex flex-col" }, vo = { class: "fm-typo-en-body-sm-600 translate-y-4" }, fo = { class: "flex-1 p-12 flex flex-col gap-8" }, yo = { class: "mx-auto" }, go = { class: "flex flex-col" }, bo = { class: "fm-typo-en-body-sm-600 translate-y-4" }, ho = {
  key: 5,
  class: "flex flex-col gap-12"
}, _o = { class: "flex flex-col" }, xo = { class: "flex items-center justify-between" }, ko = { class: "fm-typo-en-title-sm-600" }, To = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, wo = {
  key: 0,
  class: "flex flex-col gap-8"
}, Vo = { class: "flex flex-wrap gap-8" }, Io = {
  key: 6,
  class: "flex flex-col gap-12"
}, So = { class: "flex flex-col" }, Co = { class: "flex items-center justify-between" }, Fo = { class: "fm-typo-en-title-sm-600" }, Ao = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Eo = {
  key: 0,
  class: "flex flex-col gap-8"
}, $o = { class: "flex flex-wrap gap-8" }, Mo = {
  key: 7,
  class: "flex flex-col gap-12"
}, Uo = { class: "flex flex-col" }, Po = { class: "flex items-center justify-between" }, Ro = { class: "fm-typo-en-title-sm-600" }, Bo = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Do = {
  key: 0,
  class: "flex flex-col gap-8"
}, Oo = { class: "flex flex-wrap gap-8" }, No = /* @__PURE__ */ pe({
  __name: "IngredientForm",
  props: /* @__PURE__ */ dt({
    mode: {},
    modelValue: {},
    disabled: { type: Boolean },
    purchaseOrderTemplateIds: {},
    wastageTemplateIds: {},
    closingTemplateIds: {}
  }, {
    search: {},
    searchModifiers: {}
  }),
  emits: /* @__PURE__ */ dt(["update:modelValue", "click:submit", "update:purchaseOrderTemplateIds", "update:wastageTemplateIds", "update:closingTemplateIds"], ["update:search"]),
  setup(W, { expose: r, emit: k }) {
    var tt;
    const { t: d } = ve(), h = Ge();
    Fe();
    const I = It(), E = St(), P = Ct(), o = W, u = k, p = Ce(), a = Ke(), i = Vt(), m = Ae(), f = b(() => m.isEnabled);
    B(void 0);
    const w = B([]), A = B([]), v = B([]), N = B(!1);
    function D(e) {
      if (e.length === 0) return;
      const t = e[0], x = o.modelValue ?? {
        unit: p.units.find((S) => S)
      };
      x.unit || (x.unit = t, u("update:modelValue", x));
    }
    Dt(() => {
      D(p.units), o.mode === q.CREATE && (i.mustUsePoTemplate && ne(), i.enableWastageTemplate && ce(), i.enableClosingTemplate && oe());
    }), Tt([() => p.units], ([e]) => {
      D(e);
    });
    function fe() {
      u("click:submit");
    }
    async function ne() {
      w.value = [], N.value = !0;
      try {
        const [e] = await Promise.all([I.readTemplates()]).delayed(1e3);
        w.value = e;
      } catch (e) {
        console.log("Something went wrong when fetching templates:", e);
      } finally {
        N.value = !1;
      }
    }
    async function ce() {
      A.value = [], N.value = !0;
      try {
        const [e] = await Promise.all([E.readTemplates()]).delayed(
          1e3
        );
        A.value = e;
      } catch (e) {
        console.log("Something went wrong when fetching wastage templates:", e);
      } finally {
        N.value = !1;
      }
    }
    async function oe() {
      v.value = [], N.value = !0;
      try {
        const [e] = await Promise.all([P.readTemplates()]).delayed(
          1e3
        );
        v.value = e;
      } catch (e) {
        console.log("Something went wrong when fetching closing templates:", e);
      } finally {
        N.value = !1;
      }
    }
    const le = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.code) ?? "";
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.code = e, u("update:modelValue", t);
      }
    }), ee = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.isInactive) ?? !1;
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.isInactive = e, u("update:modelValue", t);
      }
    }), ae = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.name) ?? "";
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.name = e, u("update:modelValue", t);
      }
    }), ye = b({
      get() {
        var t, x;
        const e = (x = (t = o.modelValue) == null ? void 0 : t.defaultCost) == null ? void 0 : x.costPerUnit;
        return e ? +dn(e) : 0;
      },
      set(e) {
        var x, S, Y, z;
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.defaultCost ?? (t.defaultCost = {
          costPerUnit: {
            amount: 0,
            precision: 2,
            currency: ((x = mt(a.currentCountry.value)) == null ? void 0 : x.currency) ?? "MYR"
          },
          measurement: (z = (Y = (S = o.modelValue) == null ? void 0 : S.unit) == null ? void 0 : Y.measurements) == null ? void 0 : z.find(
            (re) => {
              var ie;
              return re.id === ((ie = o.modelValue) == null ? void 0 : ie.trackingMeasurement);
            }
          )
        }), t.defaultCost.costPerUnit = {
          ...t.defaultCost.costPerUnit,
          ...un(+e, 4)
        }, u("update:modelValue", t);
      }
    }), ge = b(() => {
      var t, x, S;
      const e = ((t = o.modelValue) == null ? void 0 : t.unit) ?? p.units.find((Y) => Y);
      return e ? {
        _id: e._id,
        measurement: (x = o.modelValue) == null ? void 0 : x.trackingMeasurement,
        name: ((S = e.measurements.find((Y) => {
          var z;
          return Y.id === ((z = o.modelValue) == null ? void 0 : z.trackingMeasurement);
        })) == null ? void 0 : S.name) ?? e.name
      } : null;
    }), ke = b(
      () => p.units.flatMap(({ name: e, _id: t, abbrev: x, measurements: S }) => [
        {
          label: `${e}`,
          value: null,
          displayAsSection: !0
        },
        {
          label: `${e} (${x})`,
          value: { _id: t },
          displayAsSection: !1
        },
        ...S.map(({ id: Y, name: z, abbrev: re }) => ({
          label: `${z} (${re})`,
          value: { _id: t, measurement: Y },
          displayAsSection: !1
        }))
      ])
    ), _ = Ot(W, "search"), U = b(
      () => new yn(ke.value, ["label", "value"], {
        caseSensitive: !1,
        sort: !0
      })
    ), G = b(() => U.value.search(_.value));
    function $(e) {
      var t, x, S, Y, z;
      return ((x = (t = o.modelValue) == null ? void 0 : t.unit) == null ? void 0 : x._id) === ((S = e.value) == null ? void 0 : S._id) && ((Y = o.modelValue) == null ? void 0 : Y.trackingMeasurement) === ((z = e.value) == null ? void 0 : z.measurement);
    }
    function y(e) {
      var re, ie;
      if (!e) return;
      const { _id: t, measurement: x } = e, S = x || void 0, Y = p.units.find((Ie) => Ie._id === t);
      if (!Y)
        return;
      const z = o.modelValue ?? {};
      z.unit = Y, z.trackingMeasurement = S, z.convert && (z.convert.measurement = S || null), i.enableTotalCost && (z.defaultCost = {
        measurement: Y.measurements.find((Ie) => Ie.id === S),
        costPerUnit: {
          ...((re = z.defaultCost) == null ? void 0 : re.costPerUnit) ?? {
            amount: 0,
            precision: 2,
            currency: ((ie = mt(a.currentCountry.value)) == null ? void 0 : ie.currency) ?? "MYR"
          }
        }
      }), u("update:modelValue", z);
    }
    const j = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.convert) ?? null;
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        e ? t.convert = e : t.convert = null, u("update:modelValue", t);
      }
    }), K = b(() => pt.options.filter(
      (e) => (
        // e === F_INVENTORY_VALUATION_METHODS.enum.FIFO ||
        e === pt.enum.WAVG
      )
    ).map((e) => ({
      label: d(`inventory.ingredient.valuationMethod.${e}`),
      value: e
    }))), me = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.valuation) ?? "WAVG";
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.valuation = e, u("update:modelValue", t);
      }
    }), J = b({
      get() {
        var e;
        return ((e = o.modelValue) == null ? void 0 : e.customAttributes) ?? {};
      },
      set(e) {
        const t = o.modelValue ? {
          ...o.modelValue
        } : {};
        t.customAttributes = e, u("update:modelValue", t);
      }
    }), M = B();
    r({
      validateInputs: () => {
        var e, t;
        (t = (e = M.value) == null ? void 0 : e.validateInputs) == null || t.call(e);
      },
      resetInputsValidation: () => {
        var e, t;
        (t = (e = M.value) == null ? void 0 : e.resetInputsValidation) == null || t.call(e);
      },
      resetInputs: () => {
        var e, t;
        (t = (e = M.value) == null ? void 0 : e.resetInputs) == null || t.call(e);
      }
    });
    const R = B(!1), H = b(
      () => {
        var e, t, x;
        return (e = o.modelValue) != null && e._id ? ((x = p.menu.bindedBySkuId[(t = o.modelValue) == null ? void 0 : t._id]) == null ? void 0 : x.filter(
          (S) => S.from === "INGREDIENT"
        )) ?? [] : [];
      }
    ), de = b(
      () => {
        var e, t, x;
        return (e = o.modelValue) != null && e._id ? ((x = p.menu.bindedBySkuId[(t = o.modelValue) == null ? void 0 : t._id]) == null ? void 0 : x.filter(
          (S) => S.from === "RECIPE"
        )) ?? [] : [];
      }
    ), Te = b(
      () => {
        var e, t, x;
        return (e = o.modelValue) != null && e._id ? ((x = p.menu.bindedBySkuId[(t = o.modelValue) == null ? void 0 : t._id]) == null ? void 0 : x.filter((S) => S.from === "MENU")) ?? [] : [];
      }
    ), _e = b(
      () => p.skus.map((e) => ({ label: e.name, value: e.code }))
    ), Ee = B((tt = o.modelValue) == null ? void 0 : tt.code);
    function $e(e) {
      var x;
      const t = e.el;
      t && ((x = t.querySelector("[x-should-scroll-into=true]")) == null || x.scrollIntoView());
    }
    const we = b(
      () => {
        var e, t, x, S, Y, z;
        return ((S = (x = (t = (e = o.modelValue) == null ? void 0 : e.unit) == null ? void 0 : t.measurements) == null ? void 0 : x.find(
          (re) => {
            var ie;
            return re.id === ((ie = o.modelValue) == null ? void 0 : ie.trackingMeasurement);
          }
        )) == null ? void 0 : S.abbrev) ?? ((z = (Y = o.modelValue) == null ? void 0 : Y.unit) == null ? void 0 : z.abbrev);
      }
    ), be = b({
      get() {
        var e, t;
        return ((t = (e = o.modelValue) == null ? void 0 : e.thresholds) == null ? void 0 : t.low) ?? Ue().low;
      },
      set(e) {
        var S;
        const t = ((S = o.modelValue) == null ? void 0 : S.thresholds) ?? Ue();
        t.low = e;
        const x = o.modelValue ? {
          ...o.modelValue
        } : {};
        x.thresholds = t, u("update:modelValue", x);
      }
    }), se = b({
      get() {
        var e, t;
        return ((t = (e = o.modelValue) == null ? void 0 : e.thresholds) == null ? void 0 : t.mid) ?? Ue().mid;
      },
      set(e) {
        var S;
        const t = ((S = o.modelValue) == null ? void 0 : S.thresholds) ?? Ue();
        t.mid = e;
        const x = o.modelValue ? {
          ...o.modelValue
        } : {};
        x.thresholds = t, u("update:modelValue", x);
      }
    }), Ve = b(() => i.mustUsePoTemplate && o.mode === q.CREATE && w.value.length > 0 ? w.value.map((e) => ({
      label: e.name || "Template",
      value: e._id || "template_" + e.name
    })) : []), Je = b(() => Ve.value.filter(
      (e) => (o.purchaseOrderTemplateIds ?? []).includes(e.value)
    )), Ze = b(() => i.enableWastageTemplate && o.mode === q.CREATE && A.value.length > 0 ? A.value.map((e) => ({
      label: e.name || "Template",
      value: e._id || "template_" + e.name
    })) : []), Qe = b(() => Ze.value.filter(
      (e) => (o.wastageTemplateIds ?? []).includes(e.value)
    )), Xe = b(() => i.enableClosingTemplate && o.mode === q.CREATE && v.value.length > 0 ? v.value.map((e) => ({
      label: e.name || "Template",
      value: e._id || "template_" + e.name
    })) : []), et = b(() => Xe.value.filter(
      (e) => (o.closingTemplateIds ?? []).includes(e.value)
    ));
    function Ft() {
      h.open({
        title: d("inventory.ingredient.purchaseOrderTemplates.selectTitle"),
        closeButton: !0,
        contentComponent: We,
        contentComponentProps: {
          modelValue: o.purchaseOrderTemplateIds ?? [],
          items: Ve.value
        },
        primaryActions: {
          text: d("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: d("common.cancel"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((e) => {
        u("update:purchaseOrderTemplateIds", e);
      });
    }
    function At() {
      h.open({
        title: d("inventory.ingredient.wastageTemplates.selectTitle"),
        closeButton: !0,
        contentComponent: We,
        contentComponentProps: {
          modelValue: o.wastageTemplateIds ?? [],
          items: Ze.value
        },
        primaryActions: {
          text: d("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: d("common.cancel"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((e) => {
        u("update:wastageTemplateIds", e);
      });
    }
    function Et() {
      h.open({
        title: d("inventory.ingredient.closingTemplates.selectTitle"),
        closeButton: !0,
        contentComponent: We,
        contentComponentProps: {
          modelValue: o.closingTemplateIds ?? [],
          items: Xe.value
        },
        primaryActions: {
          text: d("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: d("common.cancel"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((e) => {
        u("update:closingTemplateIds", e);
      });
    }
    function $t() {
      return function(t) {
        return typeof (t == null ? void 0 : t.low) != "number" || typeof (t == null ? void 0 : t.mid) != "number" ? "Required" : t.low >= t.mid ? "Days for red indicator should be less than yellow indicator." : !0;
      };
    }
    return (e, t) => {
      const x = C("FmTextField"), S = C("FmLabel"), Y = C("FmField"), z = C("FmIcon"), re = C("FmMenuHeader"), ie = C("FmMenuDivider"), Ie = C("FmMenuItem"), Mt = C("FmMenu"), nt = C("FmFormGroup"), Ut = C("FmSelect"), ot = C("FmSwitch"), lt = C("FmStepperField"), Be = C("FmButton"), De = C("FmChip"), Pt = C("FmForm");
      return c(), O(Pt, {
        disabled: e.disabled,
        ref_key: "formRef",
        ref: M,
        class: "flex flex-col gap-32",
        onValidationSuccess: fe
      }, {
        default: g(() => {
          var at, st, rt, it;
          return [
            n("div", Wn, [
              n("div", qn, [
                s(Se, {
                  "tooltip-message": "This field is managed by NetSuite",
                  "tooltip-z-index": 50,
                  label: l(d)("inventory.ingredient.code"),
                  "model-value": le.value,
                  "onUpdate:modelValue": t[1] || (t[1] = (V) => le.value = V),
                  locked: f.value,
                  disabled: e.disabled
                }, {
                  default: g(() => [
                    s(x, {
                      label: l(d)("inventory.ingredient.code"),
                      "model-value": le.value,
                      "onUpdate:modelValue": t[0] || (t[0] = (V) => le.value = V),
                      rules: [l(Ne)(), l(on)(_e.value, Ee.value)],
                      "label-mark": "required"
                    }, null, 8, ["label", "model-value", "rules"])
                  ]),
                  _: 1
                }, 8, ["label", "model-value", "locked", "disabled"])
              ]),
              n("div", Hn, [
                s(Se, {
                  "tooltip-message": "This field is managed by NetSuite",
                  "tooltip-z-index": 50,
                  label: l(d)("inventory.ingredient.name"),
                  "model-value": ae.value,
                  "onUpdate:modelValue": t[3] || (t[3] = (V) => ae.value = V),
                  locked: f.value,
                  disabled: e.disabled
                }, {
                  default: g(() => [
                    s(x, {
                      label: l(d)("inventory.ingredient.name"),
                      "model-value": ae.value,
                      "onUpdate:modelValue": t[2] || (t[2] = (V) => ae.value = V),
                      rules: [l(Ne)()],
                      "label-mark": "required"
                    }, null, 8, ["label", "model-value", "rules"])
                  ]),
                  _: 1
                }, 8, ["label", "model-value", "locked", "disabled"])
              ])
            ]),
            s(Se, {
              "tooltip-message": "This field is managed by NetSuite",
              "tooltip-z-index": 50,
              label: l(d)("inventory.ingredient.unit"),
              "helper-text": (at = e.modelValue) != null && at.trackingMeasurement ? `Base unit: ${(rt = (st = e.modelValue) == null ? void 0 : st.unit) == null ? void 0 : rt.name}` : void 0,
              "model-value": (it = ge.value) == null ? void 0 : it.name,
              locked: f.value,
              disabled: e.disabled
            }, {
              default: g(() => [
                s(nt, {
                  "model-value": ge.value,
                  rules: [l(Ne)()],
                  "label-mark": "required"
                }, {
                  label: g(() => [
                    s(S, {
                      label: l(d)("inventory.ingredient.unit")
                    }, null, 8, ["label"])
                  ]),
                  default: g(({ invalid: V }) => [
                    s(Mt, null, {
                      "menu-button": g(() => [
                        s(Y, {
                          class: te([
                            "fm-typo-en-body-lg-400",
                            {
                              "text-fm-color-typo-primary": !e.disabled,
                              "text-fm-color-typo-disabled": e.disabled
                            }
                          ]),
                          invalid: V,
                          "append-icon": "expand_more"
                        }, {
                          default: g(() => {
                            var Z;
                            return [
                              Ye(F((Z = ge.value) == null ? void 0 : Z.name), 1)
                            ];
                          }),
                          _: 2
                        }, 1032, ["class", "invalid"])
                      ]),
                      default: g(() => [
                        n("div", Yn, [
                          s(x, {
                            modelValue: _.value,
                            "onUpdate:modelValue": t[4] || (t[4] = (Z) => _.value = Z),
                            placeholder: "Filter options"
                          }, {
                            prepend: g(() => [
                              s(z, { name: "search" })
                            ]),
                            _: 1
                          }, 8, ["modelValue"]),
                          n("div", {
                            class: "overflow-x-hidden overflow-y-auto max-h-[300px]",
                            onVnodeMounted: $e
                          }, [
                            (c(!0), T(X, null, ue(G.value, (Z, Rt) => (c(), T(X, { key: Rt }, [
                              Z.displayAsSection ? (c(), T(X, { key: 0 }, [
                                s(re, {
                                  label: Z.label
                                }, null, 8, ["label"]),
                                s(ie)
                              ], 64)) : (c(), O(Ie, {
                                key: 1,
                                label: Z.label,
                                "model-value": $(Z),
                                onClick: (cl) => y(Z.value),
                                "x-should-scroll-into": `${$(Z)}`
                              }, null, 8, ["label", "model-value", "onClick", "x-should-scroll-into"]))
                            ], 64))), 128))
                          ], 512)
                        ])
                      ]),
                      _: 2
                    }, 1024)
                  ]),
                  _: 1
                }, 8, ["model-value", "rules"])
              ]),
              _: 1
            }, 8, ["label", "helper-text", "model-value", "locked", "disabled"]),
            l(i).enableTotalCost ? (c(), O(Se, {
              key: 0,
              "tooltip-message": "This field is managed by NetSuite",
              "tooltip-z-index": 50,
              label: l(d)("inventory.ingredient.valuationMethod.title"),
              "model-value": l(d)("inventory.ingredient.valuationMethod." + me.value),
              locked: f.value,
              disabled: e.disabled
            }, {
              label: g(() => [
                s(he, { "z-index": 50 }, {
                  default: g(() => [
                    s(S, {
                      label: l(d)("inventory.ingredient.valuationMethod.title")
                    }, null, 8, ["label"])
                  ]),
                  _: 1
                })
              ]),
              default: g(() => [
                s(Ut, {
                  class: "col-span-2",
                  label: l(d)("inventory.ingredient.valuationMethod.title"),
                  "model-value": me.value,
                  "onUpdate:modelValue": t[5] || (t[5] = (V) => me.value = V),
                  items: K.value
                }, null, 8, ["label", "model-value", "items"])
              ]),
              _: 1
            }, 8, ["label", "model-value", "locked", "disabled"])) : L("", !0),
            l(i).enableTotalCost ? (c(), O(Se, {
              key: 1,
              "tooltip-message": "This field is managed by NetSuite",
              "tooltip-z-index": 50,
              "model-value": `${l(Wt)()} ${ye.value}`,
              locked: f.value,
              "append-text": `/ ${we.value}`,
              disabled: e.disabled
            }, {
              label: g(() => [
                s(he, { "z-index": 50 }, {
                  default: g(() => [
                    s(S, {
                      label: l(d)("inventory.ingredient.pricePerUnit")
                    }, null, 8, ["label"])
                  ]),
                  _: 1
                })
              ]),
              default: g(() => [
                s(x, {
                  "model-value": ye.value,
                  "onUpdate:modelValue": t[6] || (t[6] = (V) => ye.value = V),
                  rules: [l(Pe)(0), l(ln)(4)]
                }, {
                  label: g(() => [
                    s(he, { "z-index": 50 }, {
                      default: g(() => [
                        s(S, {
                          label: l(d)("inventory.ingredient.pricePerUnit")
                        }, null, 8, ["label"])
                      ]),
                      _: 1
                    })
                  ]),
                  prepend: g(() => {
                    var V, Z;
                    return [
                      n("div", Gn, F(l(vt)(((V = l(a).currentCountry) == null ? void 0 : V.value) ?? l(ft)) === "MYR" ? "RM" : l(vt)(((Z = l(a).currentCountry) == null ? void 0 : Z.value) ?? l(ft))), 1)
                    ];
                  }),
                  append: g(() => [
                    n("div", Kn, " / " + F(we.value), 1)
                  ]),
                  _: 1
                }, 8, ["model-value", "rules"])
              ]),
              _: 1
            }, 8, ["model-value", "locked", "append-text", "disabled"])) : L("", !0),
            !f.value || j.value ? (c(), O(zn, {
              key: 2,
              "model-value": j.value,
              "onUpdate:modelValue": t[7] || (t[7] = (V) => j.value = V),
              "root-value": e.modelValue,
              readonly: f.value
            }, null, 8, ["model-value", "root-value", "readonly"])) : L("", !0),
            e.mode !== l(q).CREATE ? (c(), T("div", Jn, [
              s(ot, {
                label: l(d)("inventory.ingredient.status.inactive"),
                "model-value": ee.value,
                "onUpdate:modelValue": t[8] || (t[8] = (V) => ee.value = V),
                "label-placement": "right",
                disabled: f.value
              }, null, 8, ["label", "model-value", "disabled"]),
              n("div", Zn, [
                n("div", Qn, F(l(d)("inventory.ingredient.status.preventFromOrder")), 1)
              ])
            ])) : L("", !0),
            e.mode !== l(q).CREATE ? (c(), T("div", Xn, [
              n("div", null, [
                s(ot, {
                  label: l(d)("inventory.ingredient.bindedItems.title"),
                  modelValue: R.value,
                  "onUpdate:modelValue": t[9] || (t[9] = (V) => R.value = V),
                  "label-placement": "right"
                }, null, 8, ["label", "modelValue"])
              ]),
              R.value && H.value.length ? (c(), O(je, {
                key: 0,
                name: l(d)("inventory.ingredient.bindedItems.ingredient"),
                bindings: H.value
              }, null, 8, ["name", "bindings"])) : L("", !0),
              R.value && de.value.length ? (c(), O(je, {
                key: 1,
                name: l(d)("inventory.ingredient.bindedItems.recipe"),
                bindings: de.value
              }, null, 8, ["name", "bindings"])) : L("", !0),
              R.value && Te.value.length ? (c(), O(je, {
                key: 2,
                name: l(d)("inventory.ingredient.bindedItems.menu"),
                bindings: Te.value
              }, null, 8, ["name", "bindings"])) : L("", !0)
            ])) : L("", !0),
            n("div", eo, [
              n("div", to, [
                s(he, null, {
                  default: g(() => [
                    n("div", no, F(l(d)("inventory.ingredient.threshold.title")), 1)
                  ]),
                  _: 1
                }),
                n("div", oo, F(l(d)("inventory.ingredient.threshold.subtitle")), 1)
              ]),
              n("div", lo, [
                s(nt, {
                  "model-value": { low: be.value, mid: se.value },
                  rules: [$t()]
                }, null, 8, ["model-value", "rules"]),
                n("div", ao, [
                  n("div", so, [
                    n("div", ro, [
                      s(ze, {
                        days: be.value,
                        level: l(Le).low
                      }, null, 8, ["days", "level"])
                    ]),
                    n("div", io, [
                      n("div", uo, F(l(d)("inventory.ingredient.threshold.whenRemaining")), 1),
                      s(lt, {
                        modelValue: be.value,
                        "onUpdate:modelValue": t[10] || (t[10] = (V) => be.value = V),
                        rules: [l(Pe)(0)]
                      }, {
                        append: g(() => t[13] || (t[13] = [
                          n("div", {
                            class: "text-fm-color-typo-secondary",
                            style: { "padding-right": "32px" }
                          }, "days", -1)
                        ])),
                        _: 1
                      }, 8, ["modelValue", "rules"])
                    ])
                  ]),
                  t[15] || (t[15] = n("div", {
                    class: "h-full bg-fm-color-neutral-gray-200 relative",
                    style: { width: "1px" }
                  }, [
                    n("div", {
                      class: "absolute bg-white",
                      style: { transform: "translate(-50%, -50%)", left: "50%", top: "24px" }
                    }, " < ")
                  ], -1)),
                  n("div", co, [
                    n("div", mo, [
                      s(ze, {
                        days: se.value,
                        level: l(Le).mid
                      }, null, 8, ["days", "level"])
                    ]),
                    n("div", po, [
                      n("div", vo, F(l(d)("inventory.ingredient.threshold.whenRemaining")), 1),
                      s(lt, {
                        modelValue: se.value,
                        "onUpdate:modelValue": t[11] || (t[11] = (V) => se.value = V),
                        rules: [l(Pe)(0)]
                      }, {
                        append: g(() => t[14] || (t[14] = [
                          n("div", {
                            class: "text-fm-color-typo-secondary",
                            style: { "padding-right": "32px" }
                          }, "days", -1)
                        ])),
                        _: 1
                      }, 8, ["modelValue", "rules"])
                    ])
                  ]),
                  t[16] || (t[16] = n("div", {
                    class: "h-full bg-fm-color-neutral-gray-200 relative",
                    style: { width: "1px" }
                  }, [
                    n("div", {
                      class: "absolute bg-white",
                      style: { transform: "translate(-50%, -50%)", left: "50%", top: "24px" }
                    }, " < ")
                  ], -1)),
                  n("div", fo, [
                    n("div", yo, [
                      s(ze, {
                        days: se.value + 1,
                        level: l(Le).high
                      }, null, 8, ["days", "level"])
                    ]),
                    n("div", go, [
                      n("div", bo, F(l(d)("inventory.ingredient.threshold.stockIsStaple")), 1)
                    ])
                  ])
                ])
              ])
            ]),
            l(i).mustUsePoTemplate && e.mode === l(q).CREATE ? (c(), T("div", ho, [
              n("div", _o, [
                n("div", xo, [
                  s(he, null, {
                    default: g(() => [
                      n("div", ko, F(l(d)("inventory.ingredient.purchaseOrderTemplates.title")), 1)
                    ]),
                    _: 1
                  }),
                  s(Be, {
                    variant: "secondary",
                    "text-color": "primary",
                    "border-color": "primary",
                    "prepend-icon": "add",
                    onClick: Ft
                  })
                ]),
                n("div", To, F(l(d)("inventory.ingredient.purchaseOrderTemplates.description")), 1)
              ]),
              Je.value.length > 0 ? (c(), T("div", wo, [
                n("div", Vo, [
                  (c(!0), T(X, null, ue(Je.value, (V) => (c(), O(De, {
                    key: V.value,
                    label: V.label,
                    variant: "info",
                    compact: ""
                  }, null, 8, ["label"]))), 128))
                ])
              ])) : L("", !0)
            ])) : L("", !0),
            l(i).enableWastageTemplate && e.mode === l(q).CREATE ? (c(), T("div", Io, [
              n("div", So, [
                n("div", Co, [
                  s(he, null, {
                    default: g(() => [
                      n("div", Fo, F(l(d)("inventory.ingredient.wastageTemplates.title")), 1)
                    ]),
                    _: 1
                  }),
                  s(Be, {
                    variant: "secondary",
                    "text-color": "primary",
                    "border-color": "primary",
                    "prepend-icon": "add",
                    onClick: At
                  })
                ]),
                n("div", Ao, F(l(d)("inventory.ingredient.wastageTemplates.description")), 1)
              ]),
              Qe.value.length > 0 ? (c(), T("div", Eo, [
                n("div", $o, [
                  (c(!0), T(X, null, ue(Qe.value, (V) => (c(), O(De, {
                    key: V.value,
                    label: V.label,
                    variant: "info",
                    compact: ""
                  }, null, 8, ["label"]))), 128))
                ])
              ])) : L("", !0)
            ])) : L("", !0),
            l(i).enableClosingTemplate && e.mode === l(q).CREATE ? (c(), T("div", Mo, [
              n("div", Uo, [
                n("div", Po, [
                  s(he, null, {
                    default: g(() => [
                      n("div", Ro, F(l(d)("inventory.ingredient.closingTemplates.title")), 1)
                    ]),
                    _: 1
                  }),
                  s(Be, {
                    variant: "secondary",
                    "text-color": "primary",
                    "border-color": "primary",
                    "prepend-icon": "add",
                    onClick: Et
                  })
                ]),
                n("div", Bo, F(l(d)("inventory.ingredient.closingTemplates.description")), 1)
              ]),
              et.value.length > 0 ? (c(), T("div", Do, [
                n("div", Oo, [
                  (c(!0), T(X, null, ue(et.value, (V) => (c(), O(De, {
                    key: V.value,
                    label: V.label,
                    variant: "info",
                    compact: ""
                  }, null, 8, ["label"]))), 128))
                ])
              ])) : L("", !0)
            ])) : L("", !0),
            n("div", null, [
              s(fn, {
                entity: "inventorySku",
                modelValue: J.value,
                "onUpdate:modelValue": t[12] || (t[12] = (V) => J.value = V)
              }, null, 8, ["modelValue"])
            ])
          ];
        }),
        _: 1
      }, 8, ["disabled"]);
    };
  }
}), zo = { class: "flex flex-col gap-32" }, Lo = {
  key: 0,
  class: "flex justify-between items-center"
}, jo = { class: "flex gap-4" }, Wo = /* @__PURE__ */ pe({
  __name: "IngredientDialog",
  props: {
    show: { type: Boolean },
    sku: {},
    mode: { default: q.READ }
  },
  emits: ["update:show"],
  setup(W) {
    const r = W, k = Ce(), d = Vt(), h = Ae(), I = It(), E = St(), P = Ct(), o = Fe(), { t: u } = ve(), p = bt(r, "show"), a = bt(r, "sku"), i = B([]), m = B([]), f = B([]), w = b(
      () => {
        var _;
        return h.isEnabled && h.netSuiteItemBySkuId.has((_ = r.sku) == null ? void 0 : _._id);
      }
    ), A = b(() => {
      switch (r.mode) {
        case q.READ:
          return "";
        case q.UPDATE:
          return u("inventory.ingredient.update.title");
        case q.CREATE:
          return u("inventory.ingredient.create.title");
      }
      return "";
    }), v = b(() => {
      switch (r.mode) {
        case q.READ:
          return "";
        case q.UPDATE:
          return u("common.save");
        case q.CREATE:
          return u("common.add");
      }
      return "";
    }), N = B(), D = B(!1);
    async function fe() {
      D.value = !0;
      try {
        await k.createSku(a.value);
        const _ = k.skuByCode[a.value.code];
        d.enablePoTemplate && i.value.length > 0 && await ce(_), d.enableWastageTemplate && m.value.length > 0 && await oe(_), d.enableClosingTemplate && f.value.length > 0 && await le(_), p.value = !1, o.open({
          title: u("inventory.common.success"),
          message: u("inventory.ingredient.create.success", { name: a.value.name }),
          type: "success"
        });
      } catch (_) {
        _ instanceof yt || o.open({
          title: u("inventory.ingredient.create.error.title"),
          message: u("inventory.ingredient.create.error.message"),
          type: "error"
        });
      } finally {
        D.value = !1;
      }
    }
    async function ne() {
      D.value = !0;
      try {
        await k.updateSku(a.value), D.value = !1, p.value = !1, o.open({
          title: u("inventory.common.success"),
          message: u("inventory.ingredient.update.success", { name: a.value.name }),
          type: "success"
        });
      } catch (_) {
        _ instanceof yt || o.open({
          title: u("inventory.ingredient.update.error.title"),
          message: u("inventory.ingredient.update.error.message"),
          type: "error"
        });
      } finally {
        D.value = !1;
      }
    }
    async function ce(_) {
      var U, G, $, y;
      try {
        for (const j of i.value) {
          const K = await I.getTemplate(j);
          if (!K) {
            console.warn(`Template with ID ${j} not found`);
            continue;
          }
          if (!K.purchaseOrder.items.find(
            (J) => J.sku._id === _._id
          )) {
            const J = { amount: 1, precision: cn(_.unit) }, M = {
              sku: _,
              name: _.name,
              code: _.code,
              quantity: J,
              minimumQuantity: J,
              quantityStep: J,
              measurement: ((G = (U = _.unit) == null ? void 0 : U.measurements) == null ? void 0 : G[0]) || null
            }, R = {
              ...K,
              purchaseOrder: {
                ...K.purchaseOrder,
                items: [...K.purchaseOrder.items, M]
              }
            };
            ((($ = R.purchaseOrder.supplier) == null ? void 0 : $.internal) === gt.enum.warehouse || ((y = R.purchaseOrder.supplier) == null ? void 0 : y.internal) === gt.enum.restaurant) && (R.purchaseOrder.items = R.purchaseOrder.items.map(
              ({ totalCost: H, ...de }) => de
            )), await I.updateTemplate(R), await new Promise((H) => setTimeout(H, 1e3));
          }
        }
      } catch (j) {
        o.open({
          title: u("inventory.transfer.template.update.error"),
          message: u("inventory.transfer.template.update.errorMessage"),
          type: "error"
        }), console.error("Error in updating transfer template", j);
      }
    }
    async function oe(_) {
      try {
        for (const U of m.value) {
          const G = await E.getTemplate(U);
          if (!G) {
            console.warn(`Wastage Template with ID ${U} not found`);
            continue;
          }
          if (!G.items.find((y) => y.id === _._id)) {
            const y = {
              id: _._id,
              name: _.name,
              code: _.code,
              type: "sku",
              disabledMeasurements: []
            }, j = {
              ...G,
              items: [...G.items, y]
            };
            await E.updateTemplate(j), await new Promise((K) => setTimeout(K, 1e3));
          }
        }
      } catch (U) {
        o.open({
          title: u("inventory.wastage.template.update.error"),
          message: u("inventory.wastage.template.update.errorMessage"),
          type: "error"
        }), console.error("Error in updating wastage template", U);
      }
    }
    async function le(_) {
      try {
        for (const U of f.value) {
          const G = await P.getTemplate(U);
          if (!G) {
            console.warn(`Closing Template with ID ${U} not found`);
            continue;
          }
          if (!G.items.find((y) => y.sku._id === _._id)) {
            const y = {
              sku: _
            }, j = {
              ...G,
              items: [...G.items, y]
            };
            await P.updateTemplate(j), await new Promise((K) => setTimeout(K, 1e3));
          }
        }
      } catch (U) {
        o.open({
          title: u("inventory.closing.template.update.error"),
          message: u("inventory.closing.template.update.errorMessage"),
          type: "error"
        }), console.error("Error in updating closing template", U);
      }
    }
    function ee() {
      var _, U;
      (U = (_ = N.value) == null ? void 0 : _.validateInputs) == null || U.call(_);
    }
    function ae() {
      switch (r.mode) {
        case q.READ:
          return;
        case q.UPDATE:
          return ne();
        case q.CREATE:
          return fe();
      }
    }
    function ye(_) {
      i.value = _;
    }
    function ge(_) {
      m.value = _;
    }
    function ke(_) {
      f.value = _;
    }
    return (_, U) => {
      const G = C("FmChip"), $ = C("FmButton"), y = C("FmSideSheet");
      return c(), O(y, {
        "model-value": l(p),
        "onUpdate:modelValue": U[3] || (U[3] = (j) => ut(p) ? p.value = j : null),
        header: A.value,
        "close-button": "",
        "dismiss-away": "",
        "max-width": 500
      }, {
        "side-sheet-footer": g(() => [
          n("div", jo, [
            s($, {
              loading: D.value,
              label: v.value,
              onClick: ee
            }, null, 8, ["loading", "label"]),
            s($, {
              disabled: D.value,
              label: l(u)("common.close"),
              variant: "tertiary",
              onClick: U[2] || (U[2] = (j) => p.value = !1)
            }, null, 8, ["disabled", "label"])
          ])
        ]),
        default: g(() => [
          n("div", zo, [
            w.value ? (c(), T("div", Lo, [
              s(G, {
                label: "Managed by Netsuite",
                compact: ""
              }),
              s(en, {
                readonly: "",
                sku: _.sku,
                settingOptions: l(h).skuSettingOptions
              }, null, 8, ["sku", "settingOptions"])
            ])) : L("", !0),
            s(No, {
              class: "w-full",
              ref_key: "hasValidationExpose",
              ref: N,
              modelValue: l(a),
              "onUpdate:modelValue": U[0] || (U[0] = (j) => ut(a) ? a.value = j : null),
              mode: _.mode,
              disabled: D.value,
              purchaseOrderTemplateIds: i.value,
              wastageTemplateIds: m.value,
              closingTemplateIds: f.value,
              "onClick:submit": U[1] || (U[1] = (j) => ae()),
              "onUpdate:purchaseOrderTemplateIds": ye,
              "onUpdate:wastageTemplateIds": ge,
              "onUpdate:closingTemplateIds": ke
            }, null, 8, ["modelValue", "mode", "disabled", "purchaseOrderTemplateIds", "wastageTemplateIds", "closingTemplateIds"])
          ])
        ]),
        _: 1
      }, 8, ["model-value", "header"]);
    };
  }
}), qo = { class: "flex items-center gap-12 pl-8" }, Ho = { class: "flex flex-col" }, Yo = { class: "fm-typo-en-body-md-400 text-fm-color-typo-primary flex items-center gap-4" }, Go = {
  key: 0,
  class: "text-fm-color-typo-secondary fm-typo-en-body-sm-400"
}, Ko = { key: 0 }, kt = /* @__PURE__ */ pe({
  __name: "ImportIngredientItem",
  props: {
    type: {},
    code: {},
    name: {},
    errors: {}
  },
  setup(W) {
    return (r, k) => {
      const d = C("FmIcon"), h = C("FmTooltip");
      return c(), T("div", qo, [
        k[0] || (k[0] = n("div", null, "•", -1)),
        n("div", Ho, [
          n("div", Yo, [
            n("div", {
              class: te({
                "text-fm-color-system-error-300": r.errors.length
              })
            }, [
              Ye(F(r.name) + " ", 1),
              r.type === "create" ? (c(), T("span", Go, "(new)")) : L("", !0)
            ], 2),
            r.errors.length ? (c(), T("div", Ko, [
              s(h, { "z-index": 50 }, {
                content: g(() => [
                  n("ol", null, [
                    (c(!0), T(X, null, ue(r.errors, (I, E) => (c(), T("li", { key: E }, F(I), 1))), 128))
                  ])
                ]),
                default: g(() => [
                  s(d, {
                    name: "error",
                    size: "sm",
                    color: "system-error-300"
                  })
                ]),
                _: 1
              })
            ])) : L("", !0)
          ]),
          n("div", {
            class: te([
              "fm-typo-en-body-sm-400",
              {
                "text-fm-color-system-error-200": r.errors.length,
                "text-fm-color-typo-secondary": !r.errors.length
              }
            ])
          }, F(r.code), 3)
        ])
      ]);
    };
  }
}), Jo = { class: "flex flex-col gap-24" }, Zo = { class: "fm-typo-en-body-md-400" }, Qo = { class: "flex flex-col gap-8" }, Xo = { class: "line-clamp-2 text-ellipsis break-all" }, el = {
  key: 2,
  class: "shrink-0"
}, tl = {
  key: 0,
  class: "flex flex-col"
}, nl = { class: "text-fm-color-system-error-300 fm-typo-en-body-sm-400" }, ol = {
  key: 0,
  class: "max-h-[200px] overflow-y-auto flex flex-col gap-8"
}, ll = { class: "fm-typo-en-body-lg-600" }, al = /* @__PURE__ */ pe({
  __name: "ImportIngredients",
  setup(W) {
    const r = B(null), k = Yt(), d = Fe(), h = B(!1), I = B(new Array()), E = B([]), P = B([]), o = b(
      () => !!I.value.length || E.value.some((i) => i.errors.length) || P.value.some((i) => i.errors.length)
    ), u = b(
      () => !!E.value.length || !!P.value.length
    ), { t: p } = ve();
    async function a(i) {
      I.value = [], E.value = [], P.value = [];
      try {
        h.value = !0;
        const [m] = await Promise.all([
          bn(i),
          // fake buffer
          new Promise((A) => setTimeout(A, 1e3))
        ]), f = m.SheetNames.find((A) => A);
        if (!f) {
          I.value.push(p("inventory.ingredient.import.fileError.noSheet"));
          return;
        }
        const w = mn(m.Sheets[f]);
        if (w.invalidExcel) {
          I.value.push(w.invalidExcelMessage ?? p("inventory.ingredient.import.fileError.invalidExcel"));
          return;
        }
        if (E.value = w.importCreateResult, P.value = w.importUpdateResult, !E.value.length && !P.value.length) {
          I.value.push(p("inventory.ingredient.import.fileError.noData"));
          return;
        }
        k.emitData(w);
      } catch (m) {
        d.open({
          title: p("inventory.ingredient.import.fileError.unableToRead"),
          message: m == null ? void 0 : m.message,
          type: "error"
        }), console.error("Error in reading file", m);
      } finally {
        I.value.length && d.open({
          title: p("inventory.ingredient.import.fileError.invalidExcel"),
          type: "error"
        }), h.value = !1;
      }
    }
    return Tt(r, (i) => {
      i && a(i);
    }), (i, m) => {
      const f = C("FmCircularProgress"), w = C("FmIcon"), A = C("FmButton");
      return c(), T("div", Jo, [
        n("div", Zo, F(l(p)("inventory.ingredient.import.uploadDescription")), 1),
        s(hn, {
          class: te({
            "w-full": !0,
            "h-[200px]": !r.value
          }),
          accept: ".xlsx",
          onFileUpload: m[0] || (m[0] = (v) => r.value = v),
          label: l(p)("inventory.ingredient.import.uploadTemplate"),
          "button-label": l(p)("inventory.ingredient.import.selectFile")
        }, He({ _: 2 }, [
          r.value ? {
            name: "default",
            fn: g(({ openFileDialog: v }) => [
              n("div", Qo, [
                n("div", {
                  class: te([
                    "fm-corner-radius-md p-16 flex items-center gap-16",
                    {
                      "border border-fm-color-neutral-gray-100": h.value,
                      "border border-fm-color-neutral-gray-200": !h.value && !o.value,
                      "border border-fm-color-system-error-200": o.value
                    }
                  ])
                }, [
                  h.value ? (c(), O(f, {
                    key: 0,
                    size: "md",
                    color: "neutral-gray-200"
                  })) : (c(), O(w, {
                    key: 1,
                    name: o.value ? "error" : "attach_file",
                    outline: "",
                    color: o.value ? "system-error-300" : void 0
                  }, null, 8, ["name", "color"])),
                  n("div", {
                    class: te([
                      "fm-typo-en-body-md-400 flex-1 h-[36px] flex items-center",
                      {
                        "text-fm-color-typo-disabled": h.value,
                        "text-fm-color-typo-primary": !h.value
                      }
                    ])
                  }, [
                    n("div", Xo, F(r.value.name), 1)
                  ], 2),
                  h.value ? L("", !0) : (c(), T("div", el, [
                    s(A, {
                      label: l(p)("inventory.ingredient.import.replaceFile"),
                      variant: o.value ? "destructive" : "secondary",
                      "prepend-icon": o.value ? void 0 : "autorenew",
                      onClick: v
                    }, null, 8, ["label", "variant", "prepend-icon", "onClick"])
                  ]))
                ], 2),
                I.value.length ? (c(), T("div", tl, [
                  (c(!0), T(X, null, ue(I.value, (N, D) => (c(), T("div", {
                    key: D,
                    class: "flex gap-8 items-center"
                  }, [
                    s(w, {
                      name: "error",
                      size: "sm",
                      color: "system-error-300"
                    }),
                    n("div", nl, F(N), 1)
                  ]))), 128))
                ])) : L("", !0)
              ])
            ]),
            key: "0"
          } : void 0
        ]), 1032, ["class", "label", "button-label"]),
        u.value ? (c(), T("div", ol, [
          n("div", ll, F(l(p)("inventory.ingredient.import.summary")), 1),
          (c(!0), T(X, null, ue(E.value, (v) => (c(), O(kt, {
            key: v.sku._id,
            code: v.sku.code,
            name: v.sku.name,
            errors: v.errors,
            type: "create"
          }, null, 8, ["code", "name", "errors"]))), 128)),
          (c(!0), T(X, null, ue(P.value, (v) => (c(), O(kt, {
            key: v.sku._id,
            code: v.sku.code,
            name: v.sku.name,
            errors: v.errors,
            type: "update"
          }, null, 8, ["code", "name", "errors"]))), 128))
        ])) : L("", !0)
      ]);
    };
  }
}), sl = {
  key: 0,
  class: "flex items-center gap-1"
}, rl = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, il = { class: "flex flex-col py-8" }, dl = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, ul = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, Ll = /* @__PURE__ */ pe({
  __name: "IngredientsView",
  setup(W) {
    const r = Ce(), k = Ae(), d = b(() => [
      {
        type: "string",
        key: "skuCode",
        entity: "sku",
        values: r.skus.map((y) => y.code)
      },
      {
        type: "string",
        key: "skuUnitAbbrev",
        entity: "sku",
        values: r.units.map((y) => y.abbrev)
      },
      {
        type: "string",
        key: "status",
        entity: "sku",
        values: ["Active", "Inactive"]
      }
    ]), h = B({
      logic: "AND",
      rules: [
        {
          property: "status",
          operator: "$in",
          value: ["Active"],
          type: "string"
        }
      ]
    }), I = b(
      () => new Set(k.getAvailableItems(k.businessSubsidiaryId))
    ), E = b(() => {
      if (!h.value)
        return r.skus;
      const $ = kn.build(h.value);
      return r.skus.filter((y) => k.isEnabled && ne.value && I.value && !I.value.has(y._id) ? !1 : Tn(
        {
          skuCode: y.code,
          skuUnitAbbrev: y.unit.abbrev,
          status: y.isInactive ? "Inactive" : "Active"
        },
        $
      ));
    }), P = qt(), o = Ge(), u = xn(), p = Fe(), { t: a } = ve(), { createIngredient: i, updateIngredient: m } = qe(), { ingredientDialogProps: f, ingredientViewLoading: w } = Qt(qe()), { columnDefs: A } = Nn();
    function v($) {
      switch ($) {
        case "add":
          return k.isEnabled ? void 0 : i();
        case "import":
          return U();
        case "export":
          return _();
      }
    }
    const N = B(""), D = B(!1), fe = b(() => D.value || w.value), ne = B(!0), { breakpoints: ce } = Gt(), oe = b(() => ce.value.xs || ce.value.sm), le = b(() => oe.value ? 10 : 20), ee = tn(), ae = B(!1), ye = [
      {
        value: "import",
        label: a("common.import")
      },
      {
        value: "export",
        label: a("common.export")
      }
    ];
    function ge($) {
      switch (ae.value = !1, $) {
        case "import":
          return U();
        case "export":
          return _();
      }
    }
    const ke = b(() => [
      ...k.isEnabled ? [] : [
        {
          label: a("inventory.ingredient.create.title"),
          value: "add",
          isPrimary: !0,
          prependIcon: "add"
        }
      ],
      { label: a("common.import"), value: "import" },
      { label: a("common.export"), value: "export" }
    ]);
    function _() {
      const $ = pn();
      p.open({
        title: a("inventory.ingredient.export.success"),
        message: a("inventory.ingredient.export.filename", [$]),
        type: "success"
      });
    }
    function U() {
      o.open({
        title: a("inventory.ingredient.import.title"),
        contentComponent: al,
        overlay: !0,
        closeButton: !0,
        primaryActions: {
          text: a("common.import"),
          close: !1
        },
        secondaryActions: {
          text: a("common.close"),
          close: !0
        },
        tertiaryActions: {
          text: a("inventory.ingredient.import.actions.downloadTemplate"),
          close: !1,
          variant: "plain"
        }
      }).onPrimary(($) => {
        if (!$) {
          p.open({
            title: a("inventory.ingredient.import.error.noData"),
            type: "error"
          });
          return;
        }
        if (!$.importCreateResult.length && !$.importUpdateResult.length) {
          p.open({
            title: a("inventory.ingredient.import.error.invalidContent"),
            message: a("inventory.ingredient.import.error.noImportData"),
            type: "error"
          });
          return;
        }
        if ($.importCreateResult.some((y) => y.errors.length) || $.importUpdateResult.some((y) => y.errors.length)) {
          p.open({
            title: a("inventory.ingredient.import.error.invalidContent"),
            message: a("inventory.ingredient.import.error.hasErrors"),
            type: "error"
          });
          return;
        }
        o.close(), G($);
      }).onTertiary(vn);
    }
    async function G($) {
      D.value = !0;
      try {
        const y = [
          ...$.importCreateResult.map(({ sku: M }) => ({ type: "create", sku: M })),
          ...$.importUpdateResult.map(({ sku: M }) => ({ type: "update", sku: M }))
        ], j = 100;
        let K = 0;
        const me = () => {
          K += j, p.open({
            title: a("inventory.ingredient.import.progress", [
              Math.min(K, y.length),
              y.length
            ])
          });
        }, J = new Array();
        for (const M of y.chunk(100)) {
          me();
          try {
            const R = await r.importSkus({
              create: M.filter((H) => H.type === "create").map((H) => H.sku),
              update: M.filter((H) => H.type === "update").map((H) => H.sku)
            });
            J.push(...R.errors);
          } catch (R) {
            J.push(
              ...M.map((H) => {
                const de = {
                  module: Ht.enum.sku,
                  _id: H.sku._id,
                  name: H.sku.name,
                  message: (R == null ? void 0 : R.stack) ?? R
                };
                return {
                  data: H.sku,
                  error: [de]
                };
              })
            );
          }
        }
        p.open({
          title: a("inventory.ingredient.import.success"),
          type: "success"
        }), J.length && u.alert(
          "Some operation failed",
          Q(
            "div",
            { class: "flex flex-col gap-8" },
            J.map(
              (M) => Q("div", { class: "flex flex-col" }, [
                Q("div", { class: "fm-typo-en-body-lg-600" }, `(${M.data.code}) ${M.data.name}`),
                Q(
                  "div",
                  { class: "fm-typo-en-body-lg-400" },
                  `${M.error.map((R) => (R == null ? void 0 : R.message) ?? "Unknown error").join(", ")}`
                )
              ])
            )
          )
        );
      } catch (y) {
        p.open({
          title: a("inventory.ingredient.import.error.failed"),
          message: a("inventory.ingredient.import.error.systemMessage", [y == null ? void 0 : y.message]),
          type: "error"
        }), console.error("Error in importing skus", $, y);
      } finally {
        D.value = !1;
      }
    }
    return ($, y) => {
      const j = C("FmSwitch"), K = C("FmTable"), me = C("FmCollapsibleTabs"), J = C("FmBottomSheet");
      return c(), O(nn, {
        title: l(a)("inventory.ingredient.title"),
        actions: ke.value,
        "onClick:action": v
      }, {
        default: g(() => [
          n("div", {
            class: te([
              "flex flex-col gap-8 max-h-full",
              {
                "p-0": oe.value,
                "px-24 ": !oe.value
              }
            ])
          }, [
            s(_n, {
              searchable: "",
              search: N.value,
              "onUpdate:search": y[1] || (y[1] = (M) => N.value = M),
              filterable: "",
              "filter-attributes": d.value,
              filter: h.value,
              "onUpdate:filter": y[2] || (y[2] = (M) => h.value = M)
            }, {
              default: g(() => [
                l(k).isEnabled ? (c(), T("div", sl, [
                  n("span", rl, F(l(a)("inventory.integration.netsuite.subsidiaryHierarchy.filtering")), 1),
                  s(sn),
                  s(Re, null, {
                    default: g(() => [
                      s(j, {
                        modelValue: ne.value,
                        "onUpdate:modelValue": y[0] || (y[0] = (M) => ne.value = M)
                      }, null, 8, ["modelValue"])
                    ]),
                    _: 1
                  })
                ])) : L("", !0)
              ]),
              _: 1
            }, 8, ["search", "filter-attributes", "filter"]),
            (c(), O(K, {
              key: JSON.stringify(h.value),
              style: Nt(l(ee).tableHeight),
              "column-defs": l(A),
              "row-data": E.value,
              "search-value": N.value,
              columnVisibility: {
                netsuiteSubsidiary: l(k).isEnabled
              },
              loading: (!l(P)._currentLocation || fe.value) && l(k).isReady,
              "loading-text": "Loading",
              onRowClick: y[3] || (y[3] = (M) => l(m)(M.original)),
              "page-size": le.value
            }, {
              "list-row": g((M) => [
                s(gn, {
                  row: M,
                  onRowClick: l(m)
                }, He({
                  default: g((R) => {
                    var H, de, Te, _e, Ee, $e, we, be, se, Ve;
                    return [
                      n("div", il, [
                        n("div", dl, [
                          s(l(_t), {
                            render: (Te = (de = (H = R.code) == null ? void 0 : H.column) == null ? void 0 : de.columnDef) == null ? void 0 : Te.cell,
                            props: (Ee = (_e = R.code) == null ? void 0 : _e.getContext) == null ? void 0 : Ee.call(_e)
                          }, null, 8, ["render", "props"])
                        ]),
                        n("div", ul, [
                          s(l(_t), {
                            render: (be = (we = ($e = R.name) == null ? void 0 : $e.column) == null ? void 0 : we.columnDef) == null ? void 0 : be.cell,
                            props: (Ve = (se = R.name) == null ? void 0 : se.getContext) == null ? void 0 : Ve.call(se)
                          }, null, 8, ["render", "props"])
                        ])
                      ])
                    ];
                  }),
                  _: 2
                }, [
                  D.value ? {
                    name: "loading-text",
                    fn: g(() => [
                      n("div", null, F(l(a)("inventory.ingredient.table.importing")), 1)
                    ]),
                    key: "0"
                  } : void 0
                ]), 1032, ["row", "onRowClick"])
              ]),
              _: 1
            }, 8, ["style", "column-defs", "row-data", "search-value", "columnVisibility", "loading", "page-size"]))
          ], 2),
          (c(), O(ct, { to: "body" }, [
            s(Wo, zt(Lt(l(f))), null, 16)
          ])),
          (c(), O(ct, { to: "body" }, [
            s(J, {
              "dismiss-away": "",
              modelValue: ae.value,
              "onUpdate:modelValue": y[5] || (y[5] = (M) => ae.value = M)
            }, {
              default: g(() => [
                s(me, {
                  class: "pb-8",
                  items: ye,
                  "onUpdate:modelValue": y[4] || (y[4] = (M) => ge(M))
                })
              ]),
              _: 1
            }, 8, ["modelValue"])
          ]))
        ]),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  Ll as default
};
