import { defineComponent as ne, ref as g, computed as D, watch as de, resolveComponent as w, openBlock as n, createElementBlock as p, createBlock as M, withModifiers as ue, createCommentVNode as b, createVNode as _, withCtx as T, createElementVNode as o, toDisplayString as l, unref as i, Fragment as z, createTextVNode as Z, renderList as le, normalizeClass as me, h as X, Teleport as pe } from "vue";
import { _ as ve } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { useI18n as se, useCoreStore as ge } from "@feedmepos/mf-common";
import { E as ie, B as P, a as he, u as _e } from "./app-Bpb4394e.js";
import { F as re } from "./FmAdminBadge-DjnBAgyv.js";
import { _ as be } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { useSnackbar as ce, useDialog as ke } from "@feedmepos/ui-library";
import { u as fe } from "./stock-DWkfMCtv.js";
import { g as ye, f as xe } from "./recalculationUtils-CbjBkJQt.js";
import { _ as De } from "./UnitDisplayControl.vue_vue_type_script_setup_true_lang-IYlWKszA.js";
const we = { class: "fm-typo-en-heading-lg-600" }, Se = { class: "flex flex-col gap-16" }, Ce = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Ve = { class: "flex flex-col gap-8" }, $e = { class: "fm-typo-en-body-md-600" }, Ae = { class: "flex flex-col gap-8" }, Fe = { class: "fm-typo-en-body-md-600" }, Re = { class: "flex items-center gap-8 mb-8" }, Ie = {
  key: 2,
  class: "text-red-500 text-sm mt-2"
}, Te = { class: "fm-typo-en-body-sm-400" }, Be = {
  key: 1,
  class: "p-12 border border-fm-color-border-primary rounded-8 bg-fm-color-background-secondary"
}, Le = {
  key: 0,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, Oe = {
  key: 1,
  class: "flex flex-col gap-8"
}, Ee = { class: "fm-typo-en-body-sm-600" }, Pe = { class: "flex flex-col gap-4" }, Ue = { key: 0 }, Ne = {
  key: 1,
  class: "flex flex-col gap-8"
}, Me = { class: "fm-typo-en-body-md-600" }, Ke = { class: "flex flex-col gap-8 max-h-[300px] overflow-y-auto" }, He = { class: "flex items-center justify-between" }, je = { class: "fm-typo-en-body-sm-600" }, ze = { class: "flex items-center gap-8" }, We = {
  key: 0,
  class: "fm-typo-en-body-xs-600 px-8 py-4 rounded-4 bg-fm-color-neutral-100 text-fm-color-typo-secondary"
}, Ye = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Ge = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Je = {
  key: 0,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, Qe = {
  key: 1,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, Xe = {
  key: 2,
  class: "fm-typo-en-body-xs-400 text-fm-color-system-error-500"
}, Ze = {
  key: 0,
  class: "flex gap-8 ml-auto"
}, qe = {
  key: 1,
  class: "flex gap-8 ml-auto"
}, et = /* @__PURE__ */ ne({
  __name: "RecalculationDialog",
  props: {
    showButton: { type: Boolean }
  },
  emits: ["submitted"],
  setup(ae, { expose: S, emit: C }) {
    const U = C, { t } = se(), L = fe(), O = ie(), V = ce(), $ = g(!1), f = g(""), m = g(""), F = g(!1), v = g([]), a = g(!1), k = g([]), A = g(!1), h = g([]), x = g(!1), W = D(() => ye(v.value)), Y = D(() => {
      if (!f.value) return [];
      const r = W.value.find((e) => e.value === f.value);
      return r ? W.value.filter((e) => e.date.getTime() > r.date.getTime()).sort((e, d) => d.date.getTime() - e.date.getTime()) : [];
    }), G = D({
      get: () => {
        if (F.value && m.value) {
          const r = v.value.find((e) => P(e._id) === m.value);
          return (r == null ? void 0 : r._id) || m.value;
        }
        return m.value;
      },
      set: (r) => {
        F.value && r ? m.value = P(r) : m.value = r;
      }
    }), K = D(() => {
      if (f.value)
        try {
          const r = P(f.value);
          if (r)
            return r;
        } catch (r) {
          console.error("Error parsing date from closing ID:", r);
        }
    }), E = D(() => {
      if (!f.value || !m.value) return "";
      const r = P(f.value), e = m.value;
      if (r && e) {
        const d = new Date(r).getTime();
        if (new Date(e).getTime() <= d)
          return t("inventory.stock.recalculation.error.endDateBeforeOpening");
      }
      return "";
    }), N = D(() => !!f.value && !!m.value && !E.value), J = D(() => k.value.some(
      (r) => !r.completedAt && !r.failedReason
    ));
    async function Q() {
      $.value = !0, await Promise.all([ee(), H()]), f.value = "", m.value = "", F.value = !1;
    }
    function q() {
      $.value = !1;
    }
    S({
      open: Q,
      close: q
    });
    async function ee() {
      a.value = !0;
      try {
        const r = await O.getLastNClosings(30);
        v.value = r;
      } catch (r) {
        console.error("Error fetching recent closings:", r), V.open({
          title: t("common.error"),
          message: "Failed to fetch recent closings",
          type: "error"
        });
      } finally {
        a.value = !1;
      }
    }
    async function H() {
      A.value = !0;
      try {
        const r = await L.recalculation.recalculationRequests();
        k.value = r;
      } catch (r) {
        console.error("Error fetching recalculation requests:", r);
      } finally {
        A.value = !1;
      }
    }
    async function j() {
      if (!f.value || !m.value) {
        h.value = [];
        return;
      }
      x.value = !0;
      try {
        const r = await L.recalculation.getAffectedClosingDrafts(
          f.value,
          m.value
        );
        h.value = r;
      } catch {
        V.open({
          title: t("common.error"),
          message: "Failed to fetch affected closing drafts",
          type: "error"
        }), h.value = [];
      } finally {
        x.value = !1;
      }
    }
    de(
      [f, m],
      () => {
        f.value && m.value && !E.value ? j() : h.value = [];
      },
      { immediate: !1 }
    );
    async function te() {
      if (N.value) {
        a.value = !0;
        try {
          if (await L.recalculation.scheduleRecalculation({
            openingId: f.value,
            untilDate: m.value
          }), h.value.length > 0) {
            const r = h.value.map((e) => e._id);
            await L.recalculation.scheduleInvalidateClosingDraftCache(r);
          }
          V.open({
            title: t("common.success"),
            message: "Stock recalculation has been scheduled successfully",
            type: "success"
          }), await H(), $.value = !1, U("submitted");
        } catch (r) {
          console.error("Error scheduling recalculation:", r), V.open({
            title: t("common.error"),
            message: "Failed to schedule stock recalculation",
            type: "error"
          });
        } finally {
          a.value = !1;
        }
      }
    }
    return (r, e) => {
      const d = w("FmButton"), s = w("FmSelect"), u = w("FmRadio"), I = w("FmDatePicker"), B = w("FmAlert"), oe = w("FmDialog");
      return n(), p("div", null, [
        r.showButton ? (n(), M(d, {
          key: 0,
          "prepend-icon": "info",
          variant: "tertiary",
          onClick: ue(Q, ["stop"])
        })) : b("", !0),
        _(oe, {
          modelValue: $.value,
          "onUpdate:modelValue": e[7] || (e[7] = (c) => $.value = c),
          "close-button": "",
          dismissAway: "",
          "max-width": "600px"
        }, {
          "dialog-header": T(() => [
            o("div", we, l(i(t)("inventory.stock.recalculation.title")), 1)
          ]),
          "dialog-footer": T(() => [
            J.value ? (n(), p("div", qe, [
              _(d, {
                variant: "tertiary",
                onClick: e[6] || (e[6] = (c) => $.value = !1),
                label: i(t)("common.close")
              }, null, 8, ["label"])
            ])) : (n(), p("div", Ze, [
              _(d, {
                variant: "tertiary",
                onClick: e[5] || (e[5] = (c) => $.value = !1),
                disabled: a.value,
                label: i(t)("common.cancel")
              }, null, 8, ["disabled", "label"]),
              _(d, {
                variant: "primary",
                onClick: te,
                disabled: !N.value || a.value,
                loading: a.value,
                label: i(t)("inventory.stock.recalculation.schedule")
              }, null, 8, ["disabled", "loading", "label"])
            ]))
          ]),
          default: T(() => [
            o("div", Se, [
              o("div", Ce, l(i(t)("inventory.stock.recalculation.description")), 1),
              J.value ? b("", !0) : (n(), p(z, { key: 0 }, [
                o("div", Ve, [
                  o("p", $e, [
                    Z(l(i(t)("inventory.stock.recalculation.openingDate")) + " ", 1),
                    e[8] || (e[8] = o("span", { class: "text-fm-color-system-error-300" }, "*", -1))
                  ]),
                  e[9] || (e[9] = o("div", { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary mb-4" }, " Showing the last 30 closing records. Select the opening date to start recalculation. ", -1)),
                  _(s, {
                    modelValue: f.value,
                    "onUpdate:modelValue": e[0] || (e[0] = (c) => f.value = c),
                    items: W.value,
                    placeholder: i(t)("inventory.stock.recalculation.selectOpening"),
                    loading: a.value,
                    disabled: a.value
                  }, null, 8, ["modelValue", "items", "placeholder", "loading", "disabled"])
                ]),
                o("div", Ae, [
                  o("p", Fe, [
                    Z(l(i(t)("inventory.stock.recalculation.untilDate")) + " ", 1),
                    e[10] || (e[10] = o("span", { class: "text-fm-color-system-error-300" }, "*", -1))
                  ]),
                  o("div", Re, [
                    _(u, {
                      modelValue: F.value,
                      "onUpdate:modelValue": e[1] || (e[1] = (c) => F.value = c),
                      value: !1,
                      label: i(t)("inventory.stock.recalculation.selectByDate")
                    }, null, 8, ["modelValue", "label"]),
                    _(u, {
                      modelValue: F.value,
                      "onUpdate:modelValue": e[2] || (e[2] = (c) => F.value = c),
                      value: !0,
                      label: i(t)("inventory.stock.recalculation.selectByClosing")
                    }, null, 8, ["modelValue", "label"])
                  ]),
                  F.value ? (n(), M(s, {
                    key: 1,
                    modelValue: G.value,
                    "onUpdate:modelValue": e[4] || (e[4] = (c) => G.value = c),
                    items: Y.value,
                    placeholder: i(t)("inventory.stock.recalculation.selectClosing"),
                    loading: a.value,
                    disabled: !f.value || a.value
                  }, null, 8, ["modelValue", "items", "placeholder", "loading", "disabled"])) : (n(), M(I, {
                    key: 0,
                    modelValue: m.value,
                    "onUpdate:modelValue": e[3] || (e[3] = (c) => m.value = c),
                    placeholder: i(t)("inventory.stock.recalculation.selectDate"),
                    min: K.value,
                    disabled: !f.value || a.value
                  }, null, 8, ["modelValue", "placeholder", "min", "disabled"])),
                  E.value ? (n(), p("div", Ie, l(E.value), 1)) : b("", !0)
                ]),
                f.value && m.value && !E.value ? (n(), M(B, {
                  key: 0,
                  type: "info"
                }, {
                  default: T(() => [
                    o("div", Te, l(i(t)("inventory.stock.recalculation.info")), 1)
                  ]),
                  _: 1
                })) : b("", !0),
                h.value.length > 0 ? (n(), p("div", Be, [
                  x.value ? (n(), p("div", Le, " Loading affected closing drafts... ")) : (n(), p("div", Oe, [
                    o("div", Ee, " Affected closing draft(s): " + l(h.value.length), 1),
                    o("div", Pe, [
                      (n(!0), p(z, null, le(h.value, (c) => (n(), p("div", {
                        key: c._id,
                        class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
                      }, [
                        Z(" • " + l(c._id) + " ", 1),
                        c.effectiveAt ? (n(), p("span", Ue, " (" + l(new Date(c.effectiveAt).toLocaleString()) + ") ", 1)) : b("", !0)
                      ]))), 128))
                    ])
                  ]))
                ])) : b("", !0)
              ], 64)),
              k.value.length > 0 ? (n(), p("div", Ne, [
                o("p", Me, l(i(t)("inventory.stock.recalculation.recentRequests")), 1),
                o("div", Ke, [
                  (n(!0), p(z, null, le(k.value, (c) => {
                    var y;
                    return n(), p("div", {
                      key: c._id,
                      class: "p-12 border border-fm-color-border-primary rounded-8 flex flex-col gap-4"
                    }, [
                      o("div", He, [
                        o("div", je, l(i(t)("inventory.stock.recalculation.requestedAt")) + ": " + l(new Date(c.createdAt).toLocaleString()), 1),
                        o("div", ze, [
                          (y = c.meta) != null && y.openingType ? (n(), p("div", We, l(c.meta.openingType === "stockSnapshot" ? "Snapshot" : "Closing"), 1)) : b("", !0),
                          o("div", {
                            class: me(["fm-typo-en-body-xs-600 px-8 py-4 rounded-4", {
                              "bg-fm-color-system-error-100 text-fm-color-system-error-500": c.failedReason,
                              "bg-fm-color-system-success-100 text-fm-color-system-success-500": c.completedAt,
                              "bg-fm-color-system-info-100 text-fm-color-system-info-500": !c.failedReason && !c.completedAt
                            }])
                          }, l(c.failedReason ? i(t)("inventory.stock.recalculation.status.failed") : c.completedAt ? i(t)("inventory.stock.recalculation.status.completed") : i(t)("inventory.stock.recalculation.status.inProgress")), 3)
                        ])
                      ]),
                      o("div", Ye, l(i(t)("inventory.stock.recalculation.from")) + ": " + l(new Date(c.recalculateStartDate).toLocaleDateString()), 1),
                      o("div", Ge, l(i(t)("inventory.stock.recalculation.to")) + ": " + l(new Date(c.recalculateEndDate).toLocaleDateString()), 1),
                      c.createdBy ? (n(), p("div", Je, l(i(t)("inventory.stock.recalculation.requestedBy")) + ": " + l(c.createdBy.name || c.createdBy.id), 1)) : b("", !0),
                      c.completedAt ? (n(), p("div", Qe, l(i(t)("inventory.stock.recalculation.completedAt")) + ": " + l(new Date(c.completedAt).toLocaleString()), 1)) : b("", !0),
                      c.failedReason ? (n(), p("div", Xe, l(c.failedReason), 1)) : b("", !0)
                    ]);
                  }), 128))
                ])
              ])) : b("", !0)
            ])
          ]),
          _: 1
        }, 8, ["modelValue"])
      ]);
    };
  }
}), tt = { class: "fm-typo-en-heading-lg-600" }, ot = { class: "flex flex-col gap-16" }, at = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, lt = { class: "flex flex-col gap-8" }, nt = { class: "fm-typo-en-body-md-600" }, st = { class: "flex flex-col gap-8" }, it = { class: "fm-typo-en-body-md-600" }, ct = {
  key: 0,
  class: "text-red-500 text-sm mt-2"
}, rt = { class: "fm-typo-en-body-sm-400" }, dt = {
  key: 1,
  class: "p-12 border border-fm-color-border-primary rounded-8 bg-fm-color-background-secondary"
}, ut = {
  key: 0,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, mt = {
  key: 1,
  class: "flex flex-col gap-8"
}, ft = { class: "fm-typo-en-body-sm-600" }, yt = { class: "flex flex-col gap-4" }, pt = { key: 0 }, vt = { key: 1 }, gt = { key: 2 }, ht = {
  key: 1,
  class: "flex flex-col gap-8"
}, _t = { class: "fm-typo-en-body-md-600" }, bt = { class: "flex flex-col gap-8 max-h-[300px] overflow-y-auto" }, kt = { class: "flex items-center justify-between" }, xt = { class: "fm-typo-en-body-sm-600" }, Dt = { class: "flex items-center gap-8" }, wt = {
  key: 0,
  class: "fm-typo-en-body-xs-600 px-8 py-4 rounded-4 bg-fm-color-neutral-100 text-fm-color-typo-secondary"
}, St = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Ct = { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, Vt = {
  key: 0,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, $t = {
  key: 1,
  class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
}, At = {
  key: 2,
  class: "fm-typo-en-body-xs-400 text-fm-color-system-error-500"
}, Ft = {
  key: 0,
  class: "flex gap-8 ml-auto"
}, Rt = {
  key: 1,
  class: "flex gap-8 ml-auto"
}, It = /* @__PURE__ */ ne({
  __name: "SnapshotRecalculationDialog",
  props: {
    showButton: { type: Boolean }
  },
  emits: ["submitted"],
  setup(ae, { expose: S, emit: C }) {
    const U = C, { t } = se(), L = fe(), O = ie(), V = ce(), $ = g(!1), f = g(""), m = g(""), F = g([]), v = g([]), a = g(!1), k = g([]), A = g(!1), h = g([]), x = g(!1), W = D(
      () => ye(F.value, v.value)
    ), Y = D(() => xe(
      h.value.filter((e) => !!e.closingId).map((e) => ({ closingId: e.closingId, draftCreatedAt: new Date(P(e._id)) }))
    )), G = D(() => {
      if (f.value)
        try {
          const e = P(f.value);
          if (e)
            return e;
        } catch (e) {
          console.error("Error parsing date from opening ID:", e);
        }
    }), K = D(() => {
      if (!f.value || !m.value) return "";
      const e = P(f.value);
      if (e && m.value) {
        const d = new Date(e).getTime();
        if (new Date(m.value).getTime() <= d)
          return t("inventory.stock.recalculation.error.endDateBeforeOpening");
      }
      return "";
    }), E = D(() => {
      if (!m.value) return !1;
      const e = new Date(m.value), d = /* @__PURE__ */ new Date();
      return d.setHours(0, 0, 0, 0), e.setHours(0, 0, 0, 0), e >= d;
    }), N = D(() => !!f.value && !!m.value && !K.value), J = D(() => k.value.some(
      (e) => !e.completedAt && !e.failedReason
    ));
    async function Q() {
      $.value = !0, await Promise.all([ee(), H(), j()]), f.value = "", m.value = "";
    }
    function q() {
      $.value = !1;
    }
    S({
      open: Q,
      close: q
    });
    async function ee() {
      a.value = !0;
      try {
        const e = await O.getLastNClosings(30);
        F.value = e;
      } catch (e) {
        console.error("Error fetching recent closings:", e), V.open({
          title: t("common.error"),
          message: "Failed to fetch recent closings",
          type: "error"
        });
      } finally {
        a.value = !1;
      }
    }
    async function H() {
      try {
        const e = await O.getLastNStockSnapshots(30);
        v.value = e;
      } catch (e) {
        console.error("Error fetching recent snapshots:", e);
      }
    }
    async function j() {
      A.value = !0;
      try {
        const e = await L.recalculation.recalculationRequests();
        k.value = e;
      } catch (e) {
        console.error("Error fetching recalculation requests:", e);
      } finally {
        A.value = !1;
      }
    }
    async function te() {
      if (!f.value || !m.value) {
        h.value = [];
        return;
      }
      x.value = !0;
      try {
        const e = new Date(m.value);
        e.setHours(23, 59, 59, 999);
        const d = await L.recalculation.getAffectedClosingDrafts(
          f.value,
          e.toISOString()
        );
        h.value = d;
      } catch {
        V.open({
          title: t("common.error"),
          message: "Failed to fetch affected closing drafts",
          type: "error"
        }), h.value = [];
      } finally {
        x.value = !1;
      }
    }
    de(
      [f, m],
      () => {
        f.value && m.value && !K.value ? te() : h.value = [];
      },
      { immediate: !1 }
    );
    async function r() {
      if (!(!N.value || !m.value)) {
        a.value = !0;
        try {
          if (await L.recalculation.scheduleRecalculation({
            openingId: f.value,
            untilDate: new Date(m.value).toISOString(),
            recalculateBySnapshot: !0
          }), h.value.length > 0) {
            const e = h.value.map((d) => d._id);
            await L.recalculation.scheduleInvalidateClosingDraftCache(e);
          }
          V.open({
            title: t("common.success"),
            message: "Stock recalculation has been scheduled successfully",
            type: "success"
          }), await j(), $.value = !1, U("submitted");
        } catch (e) {
          console.error("Error scheduling recalculation:", e), V.open({
            title: t("common.error"),
            message: "Failed to schedule stock recalculation",
            type: "error"
          });
        } finally {
          a.value = !1;
        }
      }
    }
    return (e, d) => {
      const s = w("FmButton"), u = w("FmSelect"), I = w("FmDatePicker"), B = w("FmSnackbar"), oe = w("FmAlert"), c = w("FmDialog");
      return n(), p("div", null, [
        e.showButton ? (n(), M(s, {
          key: 0,
          "prepend-icon": "info",
          variant: "tertiary",
          onClick: ue(Q, ["stop"])
        })) : b("", !0),
        _(c, {
          modelValue: $.value,
          "onUpdate:modelValue": d[4] || (d[4] = (y) => $.value = y),
          "close-button": "",
          dismissAway: "",
          "max-width": "600px"
        }, {
          "dialog-header": T(() => [
            o("div", tt, l(i(t)("inventory.stock.recalculation.title")), 1)
          ]),
          "dialog-footer": T(() => [
            J.value ? (n(), p("div", Rt, [
              _(s, {
                variant: "tertiary",
                onClick: d[3] || (d[3] = (y) => $.value = !1),
                label: i(t)("common.close")
              }, null, 8, ["label"])
            ])) : (n(), p("div", Ft, [
              _(s, {
                variant: "tertiary",
                onClick: d[2] || (d[2] = (y) => $.value = !1),
                disabled: a.value,
                label: i(t)("common.cancel")
              }, null, 8, ["disabled", "label"]),
              _(s, {
                variant: "primary",
                onClick: r,
                disabled: !N.value || a.value,
                loading: a.value,
                label: i(t)("inventory.stock.recalculation.schedule")
              }, null, 8, ["disabled", "loading", "label"])
            ]))
          ]),
          default: T(() => [
            o("div", ot, [
              o("div", at, l(i(t)("inventory.stock.recalculation.description")), 1),
              J.value ? b("", !0) : (n(), p(z, { key: 0 }, [
                o("div", lt, [
                  o("p", nt, [
                    Z(l(i(t)("inventory.stock.recalculation.openingDate")) + " ", 1),
                    d[5] || (d[5] = o("span", { class: "text-fm-color-system-error-300" }, "*", -1))
                  ]),
                  d[6] || (d[6] = o("div", { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary mb-4" }, " Select from the last 30 closing or snapshot records as the opening date for recalculation. ", -1)),
                  _(u, {
                    modelValue: f.value,
                    "onUpdate:modelValue": d[0] || (d[0] = (y) => f.value = y),
                    items: W.value,
                    placeholder: i(t)("inventory.stock.recalculation.selectOpening"),
                    loading: a.value,
                    disabled: a.value
                  }, null, 8, ["modelValue", "items", "placeholder", "loading", "disabled"])
                ]),
                o("div", st, [
                  o("p", it, [
                    Z(l(i(t)("inventory.stock.recalculation.untilDate")) + " ", 1),
                    d[7] || (d[7] = o("span", { class: "text-fm-color-system-error-300" }, "*", -1))
                  ]),
                  d[8] || (d[8] = o("div", { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary mb-4" }, " Select the end date for recalculation. Must be after the selected opening date. ", -1)),
                  _(I, {
                    modelValue: m.value,
                    "onUpdate:modelValue": d[1] || (d[1] = (y) => m.value = y),
                    placeholder: i(t)("inventory.stock.recalculation.selectDate"),
                    min: G.value,
                    disabled: !f.value || a.value
                  }, null, 8, ["modelValue", "placeholder", "min", "disabled"]),
                  K.value ? (n(), p("div", ct, l(K.value), 1)) : b("", !0),
                  E.value ? (n(), M(B, {
                    key: 1,
                    title: "Warning",
                    variant: "warning",
                    description: "You have selected today or a future date. The stock balance will be refreshed accordingly."
                  })) : b("", !0)
                ]),
                f.value && m.value && !K.value ? (n(), M(oe, {
                  key: 0,
                  type: "info"
                }, {
                  default: T(() => [
                    o("div", rt, l(i(t)("inventory.stock.recalculation.info")), 1)
                  ]),
                  _: 1
                })) : b("", !0),
                h.value.length > 0 ? (n(), p("div", dt, [
                  x.value ? (n(), p("div", ut, " Loading affected closing drafts... ")) : (n(), p("div", mt, [
                    o("div", ft, " Affected closing draft(s): " + l(h.value.length), 1),
                    o("div", yt, [
                      (n(!0), p(z, null, le(h.value, (y) => (n(), p("div", {
                        key: y._id,
                        class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary"
                      }, [
                        d[9] || (d[9] = Z(" • ")),
                        y.closingId && Y.value.get(y.closingId) ? (n(), p("span", pt, l(Y.value.get(y.closingId)), 1)) : (n(), p("span", vt, l(y._id), 1)),
                        y.effectiveAt ? (n(), p("span", gt, " (" + l(new Date(y.effectiveAt).toLocaleString()) + ") ", 1)) : b("", !0)
                      ]))), 128))
                    ])
                  ]))
                ])) : b("", !0)
              ], 64)),
              k.value.length > 0 ? (n(), p("div", ht, [
                o("p", _t, l(i(t)("inventory.stock.recalculation.recentRequests")), 1),
                o("div", bt, [
                  (n(!0), p(z, null, le(k.value, (y) => {
                    var R;
                    return n(), p("div", {
                      key: y._id,
                      class: "p-12 border border-fm-color-border-primary rounded-8 flex flex-col gap-4"
                    }, [
                      o("div", kt, [
                        o("div", xt, l(i(t)("inventory.stock.recalculation.requestedAt")) + ": " + l(new Date(y.createdAt).toLocaleString()), 1),
                        o("div", Dt, [
                          (R = y.meta) != null && R.openingType ? (n(), p("div", wt, l(y.meta.openingType === "stockSnapshot" ? "Snapshot" : "Closing"), 1)) : b("", !0),
                          o("div", {
                            class: me(["fm-typo-en-body-xs-600 px-8 py-4 rounded-4", {
                              "bg-fm-color-system-error-100 text-fm-color-system-error-500": y.failedReason,
                              "bg-fm-color-system-success-100 text-fm-color-system-success-500": y.completedAt,
                              "bg-fm-color-system-info-100 text-fm-color-system-info-500": !y.failedReason && !y.completedAt
                            }])
                          }, l(y.failedReason ? i(t)("inventory.stock.recalculation.status.failed") : y.completedAt ? i(t)("inventory.stock.recalculation.status.completed") : i(t)("inventory.stock.recalculation.status.inProgress")), 3)
                        ])
                      ]),
                      o("div", St, l(i(t)("inventory.stock.recalculation.from")) + ": " + l(new Date(y.recalculateStartDate).toLocaleDateString()), 1),
                      o("div", Ct, l(i(t)("inventory.stock.recalculation.to")) + ": " + l(new Date(y.recalculateEndDate).toLocaleDateString()), 1),
                      y.createdBy ? (n(), p("div", Vt, l(i(t)("inventory.stock.recalculation.requestedBy")) + ": " + l(y.createdBy.name || y.createdBy.id), 1)) : b("", !0),
                      y.completedAt ? (n(), p("div", $t, l(i(t)("inventory.stock.recalculation.completedAt")) + ": " + l(new Date(y.completedAt).toLocaleString()), 1)) : b("", !0),
                      y.failedReason ? (n(), p("div", At, l(y.failedReason), 1)) : b("", !0)
                    ]);
                  }), 128))
                ])
              ])) : b("", !0)
            ])
          ]),
          _: 1
        }, 8, ["modelValue"])
      ]);
    };
  }
}), Tt = { class: "fm-typo-en-heading-lg-600" }, Bt = { class: "flex flex-col gap-16" }, Lt = { class: "flex flex-col gap-4" }, Ot = { class: "fm-typo-en-label-md-400 text-fm-color-typo-secondary" }, Et = { class: "fm-typo-en-body-md-400" }, Pt = { class: "flex flex-col gap-4" }, Ut = { class: "fm-typo-en-label-md-400 text-fm-color-typo-secondary" }, Nt = { class: "fm-typo-en-body-md-400" }, Mt = { class: "flex flex-col gap-4" }, Kt = { class: "fm-typo-en-label-md-400 text-fm-color-typo-secondary" }, Ht = { class: "flex gap-8 ml-auto" }, jt = /* @__PURE__ */ ne({
  __name: "ClosingDetailDialog",
  props: {
    modelValue: { type: Boolean },
    type: {},
    data: {}
  },
  emits: ["update:modelValue"],
  setup(ae, { emit: S }) {
    const { t: C } = se(), U = he(), t = ae, L = S, O = D({
      get: () => t.modelValue,
      set: (v) => L("update:modelValue", v)
    }), V = D(() => {
      var v;
      return ((v = t.data) == null ? void 0 : v.skus) ?? [];
    }), $ = D(() => {
      var A;
      const v = (A = t.data) == null ? void 0 : A._id;
      if (!v) return "-";
      const a = P(v);
      return new Date(a).toLocaleString();
    }), f = D(() => t.type === "closing" ? C("inventory.closing.history.closingDetail", "Closing Detail") : C("inventory.closing.history.snapshotDetail", "Snapshot Detail")), m = D(() => V.value.map((v) => {
      const a = U.skuById[v.id] ?? null, k = !a;
      return {
        id: v.id,
        sku: a,
        skuName: (a == null ? void 0 : a.name) ?? v.id,
        skuCode: (a == null ? void 0 : a.code) ?? "-",
        balance: v.balance ?? { amount: 0, precision: 0 },
        isMissing: k,
        costs: v.costs,
        weightedAverage: v.weightedAverage
      };
    })), F = [
      {
        accessorKey: "skuName",
        header: () => C("inventory.ingredient.name", "Ingredient Name"),
        cell: (v) => {
          const a = v.row.original;
          return a.isMissing ? X("div", { class: "flex items-center gap-8" }, [
            X("span", {}, a.id),
            X(
              "span",
              {
                class: "px-8 py-2 rounded-4 bg-fm-color-danger-weak text-fm-color-danger-default fm-typo-en-label-sm-400"
              },
              "Missing"
            )
          ]) : v.getValue();
        }
      },
      {
        accessorKey: "skuCode",
        header: () => C("inventory.ingredient.code", "Code")
      },
      {
        id: "balance",
        header: () => C("inventory.closing.history.balance", "Balance"),
        cell: (v) => {
          var A;
          const a = v.row.original;
          if (a.isMissing || !((A = a.sku) != null && A.unit))
            return `${a.balance.amount / Math.pow(10, a.balance.precision)}`;
          const k = {
            unit: a.sku.unit,
            sku: a.sku,
            amount: a.balance,
            defaultTrackingMeasurement: a.sku.trackingMeasurement ?? void 0
          };
          return X(De, k);
        },
        size: 180
      },
      {
        accessorKey: "weightedAverage",
        header: () => C("inventory.closing.history.weightedAvgCost", "Weighted Avg Cost"),
        cell: (v) => {
          const a = v.getValue();
          if (!a) return "-";
          const k = a.amount ?? 0, A = a.precision ?? 0, h = a.currency ?? "", x = k / Math.pow(10, A);
          return `${h} ${x.toFixed(2)}`;
        }
      }
    ];
    return (v, a) => {
      const k = w("FmTable"), A = w("FmButton"), h = w("FmDialog");
      return n(), M(h, {
        modelValue: O.value,
        "onUpdate:modelValue": a[1] || (a[1] = (x) => O.value = x),
        "close-button": "",
        dismissAway: "",
        "max-width": "900px"
      }, {
        "dialog-header": T(() => [
          o("div", Tt, l(f.value), 1)
        ]),
        default: T(() => {
          var x;
          return [
            o("div", Bt, [
              o("div", Lt, [
                o("div", Ot, l(t.type === "closing" ? i(C)("inventory.closing.history.closingId") : i(C)("inventory.closing.history.snapshotId", "Snapshot ID")), 1),
                o("div", Et, l(((x = t.data) == null ? void 0 : x._id) ?? "-"), 1)
              ]),
              o("div", Pt, [
                o("div", Ut, l(i(C)("inventory.closing.history.date")), 1),
                o("div", Nt, l($.value), 1)
              ]),
              o("div", Mt, [
                o("div", Kt, l(i(C)("inventory.closing.history.ingredientBalances", "Ingredient Balances")) + " (" + l(V.value.length) + ") ", 1),
                _(k, {
                  "row-data": m.value,
                  "column-defs": F,
                  pagination: { pageSize: 10 }
                }, null, 8, ["row-data"])
              ])
            ])
          ];
        }),
        "dialog-footer": T(() => [
          o("div", Ht, [
            _(A, {
              variant: "tertiary",
              onClick: a[0] || (a[0] = (x) => O.value = !1),
              label: "Close"
            })
          ])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), zt = { class: "flex flex-col gap-16 p-16" }, Wt = { class: "flex flex-col gap-16" }, Yt = { class: "flex gap-8 ml-auto" }, lo = /* @__PURE__ */ ne({
  __name: "ClosingHistoryView",
  setup(ae) {
    var e, d;
    const { t: S } = se(), C = ie(), U = _e(), t = ge(), L = ke(), O = ce(), V = g("closings"), $ = [
      { label: "Closings", value: "closings" },
      { label: "Snapshots", value: "snapshots" }
    ], f = g([]), m = g(!1), F = g([]), v = g(!1), a = g(!1), k = g("closing"), A = g(null), h = new Date(Date.now() - 864e5), x = g(h.toISOString().split("T")[0]), W = D(() => {
      const s = [];
      return V.value === "closings" ? s.push(
        {
          label: S("inventory.stock.recalculation.title"),
          value: "recalculation",
          prependIcon: "history",
          isAdminOnly: !0
        },
        {
          label: S("inventory.closing.history.initiate_opening"),
          value: "initiateOpening",
          prependIcon: "add_box",
          isAdminOnly: !0
        },
        {
          label: "Refresh",
          value: "refreshOpening",
          prependIcon: "refresh"
        }
      ) : s.push(
        {
          label: `${S("inventory.stock.recalculation.title")} (BETA)`,
          value: "recalculation",
          prependIcon: "history",
          isAdminOnly: !0
        },
        {
          label: `${S("inventory.closing.history.initiate_snapshot")} (BETA)`,
          value: "initiateStockSnapshot",
          prependIcon: "camera",
          isAdminOnly: !0
        },
        {
          label: "Refresh",
          value: "refreshStockSnapshot",
          prependIcon: "refresh"
        }
      ), s;
    }), Y = g(), G = g();
    function K(s) {
      var u, I;
      switch (s) {
        case "recalculation":
          return V.value === "closings" ? (u = Y.value) == null ? void 0 : u.open() : (I = G.value) == null ? void 0 : I.open();
        case "initiateOpening": {
          L.open({
            title: "Initiate Opening Balance",
            message: "Initiate opening balance if no opening balance exists for the current location.",
            primaryActions: { text: "Confirm", close: !0 }
          }).onPrimary(async () => {
            try {
              await C.initiateClosing(), O.open({
                message: "Opening balance initiated successfully.",
                type: "success"
              }), await H();
            } catch (B) {
              O.open({
                message: B.message || "Failed to initiate opening balance. Please try again.",
                type: "error"
              });
            }
          });
          break;
        }
        case "initiateStockSnapshot": {
          const B = new Date(Date.now() - 864e5);
          x.value = B.toISOString().split("T")[0], E.value = !0;
          break;
        }
        case "refreshOpening": {
          H();
          break;
        }
        case "refreshStockSnapshot": {
          j();
          break;
        }
      }
    }
    const E = g(!1), N = g(!1), J = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
    async function Q() {
      N.value = !0;
      try {
        const s = new Date(x.value).toISOString();
        await C.initiateStockSnapshot(s), O.open({
          message: "Stock snapshot created successfully.",
          type: "success"
        }), E.value = !1, await j();
      } catch (s) {
        O.open({
          message: s.message || "Failed to create stock snapshot. Please try again.",
          type: "error"
        });
      } finally {
        N.value = !1;
      }
    }
    const q = [
      ...(e = t.sessionUser.value) != null && e.role.isAdmin ? [
        {
          accessorKey: "_id",
          header: () => X(re, {}, () => `${S("inventory.closing.history.closingId")}`),
          cell: (s) => s.getValue()
        }
      ] : [],
      {
        accessorKey: "_id",
        id: "date",
        header: () => S("inventory.closing.history.date"),
        cell: (s) => {
          const u = s.getValue(), I = P(u);
          return new Date(I).toLocaleDateString();
        }
      },
      {
        accessorKey: "_id",
        id: "time",
        header: () => S("inventory.closing.history.time"),
        cell: (s) => {
          const u = s.getValue(), I = P(u);
          return new Date(I).toLocaleTimeString();
        }
      },
      {
        accessorKey: "ref",
        header: () => S("inventory.closing.history.createdFrom"),
        cell: (s) => s.getValue() || "-"
      }
    ], ee = [
      ...(d = t.sessionUser.value) != null && d.role.isAdmin ? [
        {
          accessorKey: "_id",
          header: () => X(
            re,
            {},
            () => `${S("inventory.closing.history.snapshotId", "Snapshot ID")}`
          ),
          cell: (s) => s.getValue()
        }
      ] : [],
      {
        accessorKey: "_id",
        id: "date",
        header: () => S("inventory.closing.history.date"),
        cell: (s) => {
          const u = s.getValue(), I = P(u);
          return new Date(I).toLocaleDateString();
        }
      },
      {
        accessorKey: "_id",
        id: "time",
        header: () => S("inventory.closing.history.time"),
        cell: (s) => {
          const u = s.getValue(), I = P(u);
          return new Date(I).toLocaleTimeString();
        }
      },
      {
        accessorKey: "remark",
        header: () => S("inventory.closing.history.createdFrom"),
        cell: (s) => s.getValue() || "-"
      }
    ];
    async function H() {
      if (U.currentLocationDBName) {
        m.value = !0;
        try {
          const s = await C.getLastNClosings(30);
          f.value = s;
        } catch (s) {
          console.error("Error fetching closings:", s), f.value = [];
        } finally {
          m.value = !1;
        }
      }
    }
    async function j() {
      if (U.currentLocationDBName) {
        v.value = !0;
        try {
          const s = await C.getLastNStockSnapshots(30);
          F.value = s;
        } catch (s) {
          console.error("Error fetching stock snapshots:", s), F.value = [];
        } finally {
          v.value = !1;
        }
      }
    }
    function te(s) {
      k.value = "closing", A.value = s, a.value = !0;
    }
    function r(s) {
      k.value = "snapshot", A.value = s, a.value = !0;
    }
    return U.watchLocation(async () => {
      U.currentLocationDBName && (await H(), await j());
    }), (s, u) => {
      const I = w("FmTabs"), B = w("FmTable"), oe = w("FmDatePicker"), c = w("FmButton"), y = w("FmDialog");
      return n(), M(ve, {
        actions: W.value,
        title: i(S)("inventory.closing.history.title"),
        "onClick:action": K
      }, {
        default: T(() => [
          o("div", zt, [
            _(be, {
              "change-location": "",
              "hide-filter-options": !0
            }),
            _(I, {
              "model-value": V.value,
              "onUpdate:modelValue": u[0] || (u[0] = (R) => V.value = R),
              items: $
            }, null, 8, ["model-value"]),
            V.value === "closings" ? (n(), p(z, { key: 0 }, [
              u[9] || (u[9] = o("div", { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, " Displaying the last 30 closing records. Click on a row to view details. ", -1)),
              _(B, {
                loading: m.value,
                "row-data": f.value,
                "column-defs": q,
                onRowClick: u[1] || (u[1] = (R) => te(R.original))
              }, null, 8, ["loading", "row-data"])
            ], 64)) : b("", !0),
            V.value === "snapshots" ? (n(), p(z, { key: 1 }, [
              u[10] || (u[10] = o("div", { class: "fm-typo-en-body-sm-400 text-fm-color-typo-secondary" }, " Displaying the last 30 stock snapshot records. Snapshots are generated based on adjustments from the last 60 days. Click on a row to view details. ", -1)),
              _(B, {
                loading: v.value,
                "row-data": F.value,
                "column-defs": ee,
                onRowClick: u[2] || (u[2] = (R) => r(R.original))
              }, null, 8, ["loading", "row-data"])
            ], 64)) : b("", !0)
          ]),
          (n(), M(pe, { to: "body" }, [
            _(et, {
              "show-button": !1,
              ref_key: "recalculationDialogRef",
              ref: Y,
              onSubmitted: u[3] || (u[3] = (R) => H())
            }, null, 512),
            _(It, {
              "show-button": !1,
              ref_key: "snapshotRecalculationDialogRef",
              ref: G,
              onSubmitted: u[4] || (u[4] = (R) => j())
            }, null, 512),
            _(jt, {
              modelValue: a.value,
              "onUpdate:modelValue": u[5] || (u[5] = (R) => a.value = R),
              type: k.value,
              data: A.value
            }, null, 8, ["modelValue", "type", "data"]),
            _(y, {
              modelValue: E.value,
              "onUpdate:modelValue": u[8] || (u[8] = (R) => E.value = R),
              "close-button": "",
              dismissAway: "",
              "max-width": "400px"
            }, {
              "dialog-header": T(() => u[11] || (u[11] = [
                o("div", { class: "fm-typo-en-heading-lg-600" }, "Initiate Stock Snapshot", -1)
              ])),
              default: T(() => [
                o("div", Wt, [
                  u[12] || (u[12] = o("div", { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, " Create a stock snapshot for the selected date. The snapshot will capture stock balances based on adjustments from the last 60 days before the selected date. ", -1)),
                  _(oe, {
                    modelValue: x.value,
                    "onUpdate:modelValue": u[6] || (u[6] = (R) => x.value = R),
                    label: "Snapshot Date",
                    max: i(J)
                  }, null, 8, ["modelValue", "max"])
                ])
              ]),
              "dialog-footer": T(() => [
                o("div", Yt, [
                  _(c, {
                    variant: "tertiary",
                    onClick: u[7] || (u[7] = (R) => E.value = !1),
                    label: "Cancel",
                    disabled: N.value
                  }, null, 8, ["disabled"]),
                  _(c, {
                    variant: "primary",
                    onClick: Q,
                    label: "Confirm",
                    loading: N.value
                  }, null, 8, ["loading"])
                ])
              ]),
              _: 1
            }, 8, ["modelValue"])
          ]))
        ]),
        _: 1
      }, 8, ["actions", "title"]);
    };
  }
});
export {
  lo as default
};
