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