import { defineComponent as O, computed as b, openBlock as f, createElementBlock as C, createElementVNode as s, Fragment as K, renderList as G, toDisplayString as h, createCommentVNode as J, ref as I, watch as ne, resolveComponent as $, createBlock as T, withCtx as A, createVNode as y, unref as i, isRef as le, normalizeClass as me, normalizeStyle as ce, Teleport as pe, normalizeProps as ve, guardReactiveProps as fe } from "vue";
import { a as W, S as ye, c as ie, w as be, i as se, u as ge } from "./app-D3gm3Lsw.js";
import { useDialog as ue, useSnackbar as Z, useProxiedModel as ae, useBreakpoints as xe } from "@feedmepos/ui-library";
import { i as _e, _ as he, m as Ve } from "./menu-usage-module-D7cxkbEk.js";
import { F as w } from "./form-mode.enum-BKiNVH6A.js";
import { defineStore as Ue, storeToRefs as we } from "pinia";
import { D as re, R as q } from "./row-action.enum-DQ9bJ_uv.js";
import { c as Ce } from "./component-kqxARxvM.js";
import { useI18n as Y } from "@feedmepos/mf-common";
import { u as Se, _ as Fe } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-DGlWE5I8.js";
import { R as H, A as ke, c as Ee } from "./rules-BK8yTx5p.js";
import { a as Q, c as $e } from "./number-BfNWSAkN.js";
import { F as Ie } from "./decimal-BPZo97WQ.js";
import { _ as Ae } from "./NumberPrecisionInput.vue_vue_type_script_setup_true_lang-DFj3HtnZ.js";
import { _ as De, F as Re } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { _ as Me } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-KTtYD7qS.js";
import { u as Pe } from "./netsuite-DmXOUJo-.js";
const Te = { class: "flex flex-col gap-8" }, Be = {
  key: 0,
  class: "flex flex-col"
}, Ne = { class: "flex-1 py-8 px-16" }, Le = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, ze = {
  key: 1,
  class: "flex flex-col"
}, je = { class: "flex-1 py-8 px-16" }, qe = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, He = {
  key: 2,
  class: "flex flex-col"
}, Ke = { class: "flex-1 py-8 px-16" }, Ge = {
  class: "flex-0 py-8 px-16",
  style: { "flex-basis": "240px" }
}, Oe = /* @__PURE__ */ O({
  __name: "UnitUsedBy",
  props: {
    unit: {}
  },
  setup(F) {
    const p = F, g = W(), c = b(() => g.validateUnitUsage(p.unit)), l = b(() => c.value.filter((o) => o.from === "INGREDIENT")), a = b(() => c.value.filter((o) => o.from === "RECIPE")), d = b(() => c.value.filter((o) => o.from === "MENU"));
    return (o, v) => (f(), C("div", Te, [
      v[3] || (v[3] = s("div", { class: "fm-typo-en-body-md-400" }, "Sorry, this unit is used in the following modules:", -1)),
      l.value.length ? (f(), C("div", Be, [
        v[0] || (v[0] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Ingredient"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (f(!0), C(K, null, G(l.value, (r) => {
          var t;
          return f(), C("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", Ne, h(r.code) + " " + h(r.name), 1),
            s("div", Le, h((t = r.bindedIngredient) != null && t.length ? "Convert binding" : "Item unit"), 1)
          ]);
        }), 128))
      ])) : J("", !0),
      a.value.length ? (f(), C("div", ze, [
        v[1] || (v[1] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Recipe"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (f(!0), C(K, null, G(a.value, (r) => {
          var t, u, m;
          return f(), C("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", je, h(r.code) + " " + h(r.name), 1),
            s("div", qe, h((t = r.bindedIngredient) == null ? void 0 : t.slice(0, 3).map((V) => V.code).join(", ")) + " " + h(r.bindedIngredient && ((u = r.bindedIngredient) == null ? void 0 : u.length) > 3 ? `and ${((m = r.bindedIngredient) == null ? void 0 : m.length) - 3} more` : ""), 1)
          ]);
        }), 128))
      ])) : J("", !0),
      d.value.length ? (f(), C("div", He, [
        v[2] || (v[2] = s("div", { class: "flex flex-row fm-typo-en-body-md-600 bg-fm-color-neutral-gray-100 text-fm-color-typo-secondary h-48 items-center" }, [
          s("div", { class: "flex-1 py-8 px-16" }, "Menu"),
          s("div", {
            class: "flex-0 py-8 px-16",
            style: { "flex-basis": "240px" }
          }, "Used in")
        ], -1)),
        (f(!0), C(K, null, G(d.value, (r) => {
          var t, u, m;
          return f(), C("div", {
            key: r.code,
            class: "flex flex-row fm-typo-en-body-md-400 h-48 items-center border-b border-b-fm-color-neutral-gray-100"
          }, [
            s("div", Ke, h(r.code) + " " + h(r.name), 1),
            s("div", Ge, h((t = r.bindedIngredient) == null ? void 0 : t.slice(0, 3).map((V) => V.code).join(", ")) + " " + h(r.bindedIngredient && ((u = r.bindedIngredient) == null ? void 0 : u.length) > 3 ? `and ${((m = r.bindedIngredient) == null ? void 0 : m.length) - 3} more` : ""), 1)
          ]);
        }), 128))
      ])) : J("", !0)
    ]));
  }
}), X = Ue("unitForm", function() {
  const p = ue(), g = Z(), c = W(), l = I(!1), a = I();
  function d() {
    const t = {
      unit: {},
      mode: w.CREATE,
      show: !0,
      "onUpdate:show"(u) {
        a.value.show = u;
      }
    };
    a.value = t;
  }
  async function o(t) {
    const u = {
      unit: t,
      mode: w.UPDATE,
      show: !0,
      "onUpdate:show"(m) {
        a.value.show = m;
      }
    };
    a.value = u;
  }
  async function v(t) {
    l.value = !0;
    try {
      await c.deleteUnit(t), g.open({
        title: "Success",
        message: `Deleted ${t.name}`,
        type: "success"
      });
    } catch (u) {
      u instanceof ye && _e(u) ? p.open({
        title: "Cannot delete unit",
        contentComponent: he,
        contentComponentProps: {
          subject: (t == null ? void 0 : t.name) ?? "",
          items: u.errorResponse.errors.map((m) => {
            var V;
            return {
              chain: [
                {
                  itemName: m.name,
                  moduleKey: (V = m.message) != null && V.startsWith("modules.") ? Ve(m.message) : m.module
                }
              ]
            };
          })
        },
        secondaryActions: {
          text: "Close",
          close: !0
        }
      }) : console.log("unable to delete unit", u), g.open({
        title: `Cannot delete ${t.name}`,
        message: "Please try again.",
        type: "error"
      }), console.error("failed to delete unit", u);
    } finally {
      l.value = !1;
    }
  }
  function r(t) {
    if (c.validateUnitUsage(t).length) {
      p.open({
        title: `Cannot delete ${(t == null ? void 0 : t.name) ?? "unit"}`,
        overlay: !0,
        dismissAway: !0,
        closeButton: !0,
        contentComponent: Oe,
        contentComponentProps: {
          unit: t
        },
        primaryActions: {
          text: "Confirm",
          close: !0
        }
      });
      return;
    }
    p.open({
      title: `Delete ${(t == null ? void 0 : t.name) ?? "unit"}?`,
      closeButton: !1,
      message: "You may not be able to delete this unit if it is linked in any of the inventory modules.",
      primaryActions: {
        text: "Delete",
        close: !0,
        variant: "destructive"
      },
      secondaryActions: {
        text: "Cancel",
        close: !0
      }
    }).onPrimary(() => v(t));
  }
  return {
    createUnit: d,
    updateUnit: o,
    deleteUnit: r,
    unitDialogProps: a,
    unitViewLoading: l
  };
});
function We() {
  const { updateUnit: F, deleteUnit: p } = X(), { t: g } = Y();
  async function c(a, d) {
    const o = ie(d);
    if (a === q.Edit) {
      await F(o);
      return;
    }
    if (a === q.Delete) {
      await p(o);
      return;
    }
  }
  return { columnDefs: [
    {
      accessorKey: "name",
      header: g("inventory.unit.table.name"),
      enableSorting: !0,
      size: 300
    },
    {
      accessorKey: "abbrev",
      header: g("inventory.unit.table.symbol"),
      enableSorting: !1,
      size: "auto"
    },
    {
      id: "action",
      header: "",
      cell(a) {
        return Ce(
          [re[q.Edit], re[q.Delete]],
          (d) => {
            c(d, a.row.original);
          }
        );
      },
      enableSorting: !1,
      size: 40,
      meta: {
        cellClass: "",
        headerClass: ""
      }
    }
  ] };
}
const Ye = { class: "flex flex-col gap-24" }, Je = { class: "flex gap-24" }, Qe = { class: "flex-1" }, Xe = { class: "flex-1" }, Ze = { class: "flex" }, et = { class: "flex items-center" }, tt = { class: "fm-typo-en-body-lg-600 flex-grow" }, ot = { class: "flex flex-col gap-24" }, nt = { class: "flex gap-24" }, lt = { class: "flex-1" }, st = { class: "flex-1" }, at = /* @__PURE__ */ O({
  __name: "UnitForm",
  props: {
    mode: {},
    modelValue: {},
    disabled: { type: Boolean }
  },
  emits: ["update:modelValue", "click:submit"],
  setup(F, { expose: p, emit: g }) {
    const c = F, l = g, { t: a } = Y();
    function d() {
      l("click:submit");
    }
    const o = I(c.modelValue);
    ne(
      () => c.modelValue,
      (e) => {
        o.value = e;
      }
    );
    const v = b({
      get() {
        var e;
        return ((e = o.value) == null ? void 0 : e.name) ?? "";
      },
      set(e) {
        o.value.name = e, l("update:modelValue", o.value);
      }
    }), r = b({
      get() {
        var e;
        return ((e = o.value) == null ? void 0 : e.abbrev) ?? "";
      },
      set(e) {
        o.value.abbrev = e, l("update:modelValue", o.value);
      }
    }), t = b({
      get() {
        var e;
        return ((e = o.value) == null ? void 0 : e.precision) ?? 0;
      },
      set(e) {
        o.value.precision = e, l("update:modelValue", o.value);
      }
    }), u = b({
      get() {
        var e;
        return ((e = o.value) == null ? void 0 : e.measurements) ?? [];
      },
      set(e) {
        o.value.measurements = e, l("update:modelValue", o.value);
      }
    });
    ne(
      () => t.value,
      (e) => {
        if (typeof e == "number" && !isNaN(e)) {
          const n = u.value.map((U) => ({
            ...U,
            conversion: be.convertPrecision({
              value: U.conversion,
              precision: e
            })
          }));
          o.value.measurements = n, l("update:modelValue", o.value);
        }
      },
      { immediate: !0 }
    );
    function m() {
      const e = o.value.measurements ?? [];
      o.value.measurements = [
        ...e,
        {
          id: `measurement_${(/* @__PURE__ */ new Date()).toISOString()}_${Math.random().toString(16).slice(2, 8)}`,
          name: "",
          abbrev: "",
          conversion: {
            amount: 1,
            precision: 0
          }
        }
      ], l("update:modelValue", o.value);
    }
    function V(e) {
      const n = o.value.measurements ?? [];
      n.splice(e, 1), o.value.measurements = n, l("update:modelValue", o.value);
    }
    const E = I();
    return p({
      validateInputs: () => {
        var e, n;
        (n = (e = E.value) == null ? void 0 : e.validateInputs) == null || n.call(e);
      },
      resetInputsValidation: () => {
        var e, n;
        (n = (e = E.value) == null ? void 0 : e.resetInputsValidation) == null || n.call(e);
      },
      resetInputs: () => {
        var e, n;
        (n = (e = E.value) == null ? void 0 : e.resetInputs) == null || n.call(e);
      }
    }), (e, n) => {
      const U = $("FmTextField"), R = $("FmStepperField"), S = $("FmButton"), M = $("FmCard"), D = $("FmForm");
      return f(), T(D, {
        ref_key: "formRef",
        ref: E,
        class: "flex flex-col gap-40",
        onValidationSuccess: d
      }, {
        default: A(() => {
          var B;
          return [
            s("div", Ye, [
              s("div", Je, [
                s("div", Qe, [
                  y(U, {
                    disabled: e.disabled,
                    label: i(a)("inventory.unit.name"),
                    modelValue: v.value,
                    "onUpdate:modelValue": n[0] || (n[0] = (x) => v.value = x),
                    rules: [i(H)()],
                    "label-mark": "required"
                  }, null, 8, ["disabled", "label", "modelValue", "rules"])
                ]),
                s("div", Xe, [
                  y(U, {
                    disabled: e.disabled,
                    label: i(a)("inventory.unit.symbol"),
                    modelValue: r.value,
                    "onUpdate:modelValue": n[1] || (n[1] = (x) => r.value = x),
                    rules: [i(H)()],
                    "label-mark": "required"
                  }, null, 8, ["disabled", "label", "modelValue", "rules"])
                ])
              ]),
              s("div", null, [
                y(R, {
                  disabled: e.disabled,
                  class: "col-span-3",
                  label: i(a)("inventory.unit.precision"),
                  modelValue: t.value,
                  "onUpdate:modelValue": n[2] || (n[2] = (x) => t.value = x),
                  rules: [i(ke)(0)]
                }, null, 8, ["disabled", "label", "modelValue", "rules"])
              ])
            ]),
            s("div", Ze, [
              y(S, {
                disabled: e.disabled,
                type: "button",
                "prepend-icon": "add",
                label: i(a)("inventory.unit.measurement.addMeasurement"),
                variant: "plain",
                onClick: m
              }, null, 8, ["disabled", "label"])
            ]),
            (f(!0), C(K, null, G((B = e.modelValue) == null ? void 0 : B.measurements, (x, _) => (f(), T(M, {
              class: "flex flex-col gap-16 p-16",
              variant: "outlined",
              key: x.id
            }, {
              default: A(() => [
                s("div", et, [
                  s("div", tt, h(i(a)("inventory.unit.measurement.measurementDefault", [_ + 1])), 1),
                  y(S, {
                    disabled: e.disabled,
                    variant: "tertiary",
                    "prepend-icon": "delete",
                    onClick: (k) => V(_)
                  }, null, 8, ["disabled", "onClick"])
                ]),
                s("div", ot, [
                  s("div", nt, [
                    s("div", lt, [
                      y(U, {
                        disabled: e.disabled,
                        class: "col-span-2",
                        label: i(a)("inventory.unit.measurement.name"),
                        modelValue: e.modelValue.measurements[_].name,
                        "onUpdate:modelValue": (k) => e.modelValue.measurements[_].name = k,
                        rules: [i(H)()],
                        "label-mark": "required"
                      }, null, 8, ["disabled", "label", "modelValue", "onUpdate:modelValue", "rules"])
                    ]),
                    s("div", st, [
                      y(U, {
                        disabled: e.disabled,
                        label: i(a)("inventory.unit.measurement.symbol"),
                        modelValue: e.modelValue.measurements[_].abbrev,
                        "onUpdate:modelValue": (k) => e.modelValue.measurements[_].abbrev = k,
                        rules: [i(H)()],
                        "label-mark": "required"
                      }, null, 8, ["disabled", "label", "modelValue", "onUpdate:modelValue", "rules"])
                    ])
                  ]),
                  y(Ae, {
                    disabled: e.disabled,
                    class: "col-span-3",
                    label: i(a)("inventory.unit.measurement.conversion"),
                    "model-value": +i(Q)(e.modelValue.measurements[_].conversion),
                    "onUpdate:modelValue": (k) => u.value = u.value.map(
                      (P, N) => N === _ ? {
                        ...P,
                        conversion: i(Ie).toPrecision(
                          i($e)(k),
                          t.value
                        )
                      } : P
                    ),
                    rules: [i(Ee)(0)],
                    step: +i(Q)({ amount: 1, precision: t.value }),
                    "helper-text": i(a)("inventory.unit.measurement.conversionHelper", {
                      measurementSymbol: e.modelValue.measurements[_].name || " measurement unit",
                      conversion: +i(Q)(e.modelValue.measurements[_].conversion),
                      unitSymbol: r.value || "base unit"
                    })
                  }, null, 8, ["disabled", "label", "model-value", "onUpdate:modelValue", "rules", "step", "helper-text"])
                ])
              ]),
              _: 2
            }, 1024))), 128))
          ];
        }),
        _: 1
      }, 512);
    };
  }
}), rt = { class: "flex gap-4" }, it = /* @__PURE__ */ O({
  __name: "UnitDialog",
  props: {
    show: { type: Boolean },
    unit: {},
    mode: { default: w.READ }
  },
  emits: ["update:show"],
  setup(F) {
    const p = F, g = W(), c = Z(), { t: l } = Y(), a = ae(p, "show"), d = ae(p, "unit"), o = b(() => {
      switch (p.mode) {
        case w.READ:
          return "";
        case w.UPDATE:
          return l("inventory.unit.update.title");
        case w.CREATE:
          return l("inventory.unit.create.title");
      }
      return "";
    }), v = b(() => {
      switch (p.mode) {
        case w.READ:
          return "";
        case w.UPDATE:
          return l("common.save");
        case w.CREATE:
          return l("common.add");
      }
      return "";
    }), r = I(), t = I(!1);
    async function u() {
      t.value = !0;
      try {
        const e = ie(d.value);
        e.precision ?? (e.precision = 0), e.measurements ?? (e.measurements = []), await g.createUnit(e), a.value = !1, c.open({
          title: l("inventory.common.success"),
          message: l("inventory.unit.create.success", { name: d.value.name }),
          type: "success"
        });
      } catch (e) {
        e instanceof se || c.open({
          title: l("inventory.unit.create.error.title"),
          message: l("inventory.unit.create.error.message"),
          type: "error"
        });
      } finally {
        t.value = !1;
      }
    }
    async function m() {
      t.value = !0;
      try {
        await g.updateUnit(d.value), a.value = !1, c.open({
          title: l("inventory.common.success"),
          message: l("inventory.unit.update.success", { name: d.value.name }),
          type: "success"
        });
      } catch (e) {
        e instanceof se || c.open({
          title: l("inventory.unit.update.error.title"),
          message: l("inventory.unit.update.error.message"),
          type: "error"
        });
      } finally {
        t.value = !1;
      }
    }
    function V() {
      var e, n;
      (n = (e = r.value) == null ? void 0 : e.validateInputs) == null || n.call(e);
    }
    function E() {
      switch (p.mode) {
        case w.READ:
          return;
        case w.UPDATE:
          return m();
        case w.CREATE:
          return u();
      }
    }
    return (e, n) => {
      const U = $("FmButton"), R = $("FmSideSheet");
      return f(), T(R, {
        "model-value": i(a),
        "onUpdate:modelValue": n[3] || (n[3] = (S) => le(a) ? a.value = S : null),
        header: o.value,
        "close-button": "",
        "dismiss-away": "",
        "max-width": 500
      }, {
        "side-sheet-footer": A(() => [
          s("div", rt, [
            y(U, {
              loading: t.value,
              label: v.value,
              onClick: V
            }, null, 8, ["loading", "label"]),
            y(U, {
              disabled: t.value,
              label: i(l)("common.close"),
              variant: "tertiary",
              onClick: n[2] || (n[2] = (S) => a.value = !1)
            }, null, 8, ["disabled", "label"])
          ])
        ]),
        default: A(() => [
          y(at, {
            class: "w-full",
            ref_key: "hasValidationExpose",
            ref: r,
            modelValue: i(d),
            "onUpdate:modelValue": n[0] || (n[0] = (S) => le(d) ? d.value = S : null),
            mode: e.mode,
            disabled: t.value,
            "onClick:submit": n[1] || (n[1] = (S) => E())
          }, null, 8, ["modelValue", "mode", "disabled"])
        ]),
        _: 1
      }, 8, ["model-value", "header"]);
    };
  }
}), ut = { class: "flex flex-col py-8" }, dt = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, mt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Et = /* @__PURE__ */ O({
  __name: "UnitView",
  setup(F) {
    const p = W(), g = ge(), c = Pe();
    ue(), Z();
    const { t: l } = Y(), a = b(() => p.units), { createUnit: d, updateUnit: o } = X(), { unitDialogProps: v, unitViewLoading: r } = we(X()), { columnDefs: t } = We();
    function u(M) {
      switch (M) {
        case "add":
          return c.isEnabled ? void 0 : d();
      }
    }
    const m = I(""), V = I(!1), E = b(() => V.value || r.value), { breakpoints: e } = xe(), n = b(() => e.value.xs || e.value.sm), U = b(() => n.value ? 10 : 20), R = Se(), S = b(() => [
      ...c.isEnabled ? [] : [
        {
          label: l("inventory.unit.create.title"),
          value: "add",
          isPrimary: !0,
          prependIcon: "add"
        }
      ]
    ]);
    return (M, D) => {
      const B = $("FmTable");
      return f(), T(Fe, {
        title: i(l)("inventory.unit.title"),
        actions: S.value,
        "onClick:action": u
      }, {
        default: A(() => [
          s("div", {
            class: me([
              "flex flex-col gap-8 max-h-full",
              {
                "p-0": n.value,
                "px-24 ": !n.value
              }
            ])
          }, [
            y(Me, {
              searchable: "",
              search: m.value,
              "onUpdate:search": D[0] || (D[0] = (x) => m.value = x)
            }, null, 8, ["search"]),
            y(B, {
              style: ce(i(R).tableHeight),
              "column-defs": i(t),
              "row-data": a.value,
              "search-value": m.value,
              loading: !i(g)._currentLocation || E.value,
              onRowClick: D[1] || (D[1] = (x) => i(o)(x.original)),
              "page-size": U.value
            }, {
              "list-row": A((x) => [
                y(De, {
                  row: x,
                  onRowClick: i(o)
                }, {
                  default: A((_) => {
                    var k, P, N, L, ee, z, te, j, oe;
                    return [
                      s("div", ut, [
                        s("div", dt, [
                          y(i(Re), {
                            render: (N = (P = (k = _.name) == null ? void 0 : k.column) == null ? void 0 : P.columnDef) == null ? void 0 : N.cell,
                            props: (ee = (L = _.name) == null ? void 0 : L.getContext) == null ? void 0 : ee.call(L)
                          }, null, 8, ["render", "props"])
                        ]),
                        s("div", mt, h((oe = (j = (te = (z = x.original.measurements) == null ? void 0 : z.map) == null ? void 0 : te.call(z, (de) => de.name)) == null ? void 0 : j.join) == null ? void 0 : oe.call(j, ", ")), 1)
                      ])
                    ];
                  }),
                  _: 2
                }, 1032, ["row", "onRowClick"])
              ]),
              _: 1
            }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"])
          ], 2),
          (f(), T(pe, { to: "body" }, [
            y(it, ve(fe(i(v))), null, 16)
          ]))
        ]),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  Et as default
};
