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