import { defineComponent as me, openBlock as j, createBlock as ee, withCtx as T, createElementVNode as e, toDisplayString as c, unref as s, ref as G, h as ge, computed as E, watch as Fe, resolveComponent as M, isRef as Ue, createVNode as f, createElementBlock as W, Fragment as ue, renderList as de, createCommentVNode as oe, normalizeClass as Ie, reactive as mt, mergeModels as Qe, useModel as St, onMounted as Ke, createTextVNode as ve, normalizeStyle as ft, watchEffect as wt, renderSlot as Ze, Teleport as At, normalizeProps as et, mergeProps as Le } from "vue";
import { u as Ft, _ as $t } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { u as je, c as Ee, a as Re, F as tt, t as jt, D as ae, s as Vt, m as Ct, B as Dt, w as Z, f as Ve, h as ot, d as nt, J as xe, K as Ce } from "./app-Bpb4394e.js";
import { u as Ne } from "./stock-Dvcz34IY.js";
import { c as Bt } from "./component-kqxARxvM.js";
import { _ as vt, o as Mt } from "./UnitDisplayControl.vue_vue_type_script_setup_true_lang-IYlWKszA.js";
import { _ as We, S as ze, g as pt, a as It } from "./SubsidiaryTreeDialog.vue_vue_type_script_setup_true_lang-C-OhTH0B.js";
import { _ as Tt } from "./PreviewBadge.vue_vue_type_script_setup_true_lang-CRZiQHjx.js";
import { useI18n as fe, useCoreStore as qe } from "@feedmepos/mf-common";
import { u as yt, i as Te, _ as st } from "./PremiumBadge.vue_vue_type_script_setup_true_lang-D5Oc4Mz8.js";
import { useSnackbar as we, useDialog as Oe, useProxiedModel as Ye, useBreakpoints as Ht } from "@feedmepos/ui-library";
import { defineStore as Pt } from "pinia";
import { F as Xe } from "./FmAdminBadge-DjnBAgyv.js";
import { g as $e, a as he, e as Ut, t as He, c as Se, f as Et, h as at, i as _t, j as Je, d as Be, k as Rt } from "./number-BVg7EKPV.js";
import { u as Ae } from "./stock-DWkfMCtv.js";
import { c as Pe, A as Nt, M as Ot, R as Yt } from "./rules-CoimOM7X.js";
import { u as Lt } from "./use-inventory-binding-dialog-zJqVnpvd.js";
import { a as kt } from "./FmMultiselectDialog-D-38fV59.js";
import { d as ke } from "./dayjs.min-D5mIeZ1x.js";
import { _ as zt } from "./NumberPrecisionInput.vue_vue_type_script_setup_true_lang-C50b1vbd.js";
import { g as Gt } from "./decimal-C219qGO5.js";
import { a as Wt, c as Kt, f as ht, t as lt, d as rt, p as qt, n as Xt, b as Jt } from "./date2-DpnYOzUg.js";
import { i as Qt, _ as Zt } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { _ as eo } from "./empty-placeholder-B0QU467o.js";
import { F as _e } from "./inventory-core-dart.default-DanfWZQm.js";
import { u as to } from "./feature-Cz6F0_cm.js";
import { u as bt } from "./useHrmPermission-DEaN-y77.js";
import { _ as oo, F as it } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { u as no } from "./netsuite-BGUUAOqe.js";
import { P as so, J as ao } from "./app-DiX-EfV6.js";
var Me = /* @__PURE__ */ ((V) => (V.History = "History", V.Convert = "Convert", V.Adjust = "Adjust", V))(Me || {});
const lo = [
  {
    translationKey: "inventory.stock.action.history",
    color: "text-neutral-700",
    value: "History"
    /* History */
  }
], ro = [
  {
    translationKey: "inventory.stock.action.history",
    color: "text-neutral-700",
    value: "History"
    /* History */
  },
  {
    translationKey: "inventory.stock.action.convert",
    color: "text-neutral-700",
    value: "Convert"
    /* Convert */
  },
  {
    translationKey: "inventory.stock.action.adjust",
    color: "text-neutral-700",
    value: "Adjust"
    /* Adjust */
  }
], io = { class: "whitespace-nowrap" }, uo = /* @__PURE__ */ me({
  __name: "StockHeaderPreview",
  setup(V) {
    const { t: m } = fe();
    return (y, _) => (j(), ee(Tt, null, {
      default: T(() => [
        e("div", io, c(s(m)("inventory.stock.prediction.daysRemaining")), 1)
      ]),
      _: 1
    }));
  }
}), gt = Pt("stockActions", () => {
  const V = G(!1), m = je(), y = Ne(), _ = yt(), S = we(), C = Oe(), { t: v } = fe();
  async function i() {
    if (m._currentLocation) {
      V.value = !0;
      try {
        await y.readStockBalance(), await y.readProductBalance(), await _.readStockEstimateBalance();
      } catch {
        S.open({
          title: v("inventory.stock.error.title"),
          message: v("inventory.stock.error.message"),
          type: "error"
        });
      } finally {
        V.value = !1;
      }
    }
  }
  const g = G();
  async function z(b) {
    var w, H, R;
    if (!!!((H = (w = b.convert) == null ? void 0 : w.inventoryBindings) != null && H.length)) {
      C.open({
        title: v("inventory.stock.error.convert.title"),
        message: v("inventory.stock.error.convert.message")
      });
      return;
    }
    const o = {
      maxCount: ((R = y.productBalance.find(({ id: O }) => O === b._id)) == null ? void 0 : R.count) || 0,
      sku: b,
      show: !0,
      "onUpdate:show"(O) {
        g.value.show = O;
      },
      onSubmitted() {
        i();
      }
    };
    g.value = o;
  }
  const D = G();
  async function u(b) {
    const n = {
      stock: b,
      show: !0,
      "onUpdate:show"(t) {
        D.value.show = t;
      },
      onSubmitted() {
        i();
      }
    };
    D.value = n;
  }
  const d = G();
  async function I(b) {
    const n = {
      sku: b,
      show: !0,
      "onUpdate:show"(t) {
        d.value.show = t;
      }
    };
    d.value = n;
  }
  function k(b, n) {
    const t = Ee(n);
    switch (b) {
      case Me.History:
        I(t);
        return;
      case Me.Convert:
        z(t);
        return;
      case Me.Adjust:
        u(t);
        return;
    }
  }
  return {
    fetchStockBalance: i,
    onActionMenu: k,
    stockHistoryProps: d,
    showSkuHistory: I,
    convertSkuDialogProps: g,
    adjustSkuDialogProps: D
  };
});
function co() {
  var C;
  const V = je(), m = gt(), y = qe(), { t: _ } = fe();
  return {
    columnDefs: [
      {
        accessorKey: "code",
        header: () => _("inventory.stock.code"),
        enableSorting: !0,
        size: 300
      },
      {
        accessorKey: "name",
        header: () => _("inventory.stock.product"),
        enableSorting: !0,
        size: "auto"
      },
      {
        id: "UOM",
        header: () => _("inventory.stock.balance"),
        cell(v) {
          const i = v.row.original, g = {
            unit: i.unit,
            sku: i,
            amount: i.balance,
            defaultTrackingMeasurement: i.trackingMeasurement ?? void 0
          };
          return ge(vt, g);
        },
        size: 180
      },
      ...(C = y.sessionUser.value) != null && C.role.isAdmin ? [
        {
          accessorKey: "isInactive",
          header: () => ge(Xe, {}, () => `${_("inventory.ingredient.status.title")}`),
          cell(v) {
            const i = v.row.original.isInactive;
            return ge(
              "span",
              {
                class: [
                  "inline-block px-3 py-1 rounded-full text-xs font-semibold",
                  i ? "bg-red-100 text-red-700" : "bg-green-100 text-green-700"
                ].join(" ")
              },
              _(i ? "inventory.ingredient.status.inactive" : "inventory.ingredient.status.active")
            );
          },
          enableSorting: !0
        }
      ] : [],
      {
        accessorKey: "day",
        id: "expireDate",
        header: () => ge(uo),
        enableSorting: !0,
        sortUndefined: "last",
        cell(v) {
          var I, k;
          const i = v.row.original.day, g = v.row.original.operator, z = (I = v.row.original.thresholds) == null ? void 0 : I.low, D = (k = v.row.original.thresholds) == null ? void 0 : k.mid;
          if (typeof i != "number" || typeof z != "number" || typeof D != "number")
            return ge(We, {
              days: i,
              operator: g
            });
          const u = i <= z ? ze.low : i <= D ? ze.mid : ze.high;
          return ge(We, {
            days: i,
            level: u
          });
        },
        size: 200
      },
      {
        id: "action",
        cell(v) {
          var i;
          return Bt(
            ((i = V._currentLocation) == null ? void 0 : i.type) === "restaurant" ? lo : ro,
            (g) => m.onActionMenu(g, v.row.original)
          );
        },
        enableSorting: !1,
        size: 40,
        meta: {
          cellClass: "",
          headerClass: ""
        }
      }
    ]
  };
}
const mo = {
  context: null,
  error: null,
  isRequired(V = "This field is required") {
    return `${this.context ?? ""}`.length === 0 && (this.error = V), this;
  },
  isString(V = "Must be a valid string") {
    return this.error ? this : (typeof this.context != "string" && (this.error ?? (this.error = V)), this);
  },
  toInt() {
    return this.error ? this : (this.context = +this.context, this);
  },
  isInteger(V = "Must be an integer") {
    return this.error ? this : (this.toInt(), isNaN(this.context) && (this.error = V), this);
  },
  min(V, m) {
    if (this.error) return this;
    try {
      typeof this.context == "number" ? +this.context < V && (this.error = m ?? `Must be at least ${V}`) : Object.prototype.hasOwnProperty.call(this.context, "length") ? +this.context.length < V && (this.error = m ?? `Must be at least ${V}`) : this.error = "Length cannot be determined";
    } catch {
      this.error = "Length cannot be determined";
    }
    return this;
  },
  max(V, m) {
    if (this.error) return this;
    try {
      typeof this.context == "number" ? +this.context > V && (this.error = m ?? `Must be at most ${V}`) : "length" in this.context ? +this.context.length > V && (this.error = m ?? `Must be at most ${V}`) : this.error = "Length cannot be determined";
    } catch {
      this.error = "Length cannot be determined";
    }
    return this;
  }
};
function ut(V) {
  return { ...mo, context: V };
}
const fo = { class: "flex items-center" }, vo = { class: "fm-typo-en-title-md-800" }, po = { class: "flex flex-col gap-24 w-full" }, yo = { class: "flex flex-col gap-8" }, _o = { class: "fm-typo-en-body-lg-600" }, ko = { class: "fm-typo-en-body-lg-400 text-fm-color-typo-secondary flex-grow" }, ho = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-error" }, bo = { class: "flex flex-col p-16 gap-8" }, go = { class: "flex flex-col gap-4" }, xo = { class: "fm-typo-en-body-md-600 text-fm-color-typo-secondary bg-fm-color-neutral-gray-100 border-b py-12 px-16" }, So = { class: "grid grid-cols-[auto_100px_100px_48px] xs:grid-cols-[auto_80px_120px_48px] gap-8 px-8 items-center" }, wo = { class: "xs:col-span-3" }, Ao = { class: "flex gap-8" }, Fo = /* @__PURE__ */ me({
  __name: "ConvertSkuDialog",
  props: {
    sku: {},
    maxCount: {},
    show: { type: Boolean }
  },
  emits: ["update:show", "submitted"],
  setup(V, { expose: m, emit: y }) {
    const _ = V, S = y, C = Lt(), v = Re(), i = Ae(), g = we(), { t: z } = fe(), D = G(0), u = G(null), d = E(() => v.skus), I = E(
      () => {
        var h, x;
        return (((x = (h = _.sku) == null ? void 0 : h.convert) == null ? void 0 : x.inventoryBindings) ?? []).filter(
          (B) => B.type === tt.enum.SKU
        );
      }
    ), k = E({
      get() {
        return !!u.value;
      },
      set(h) {
        h ? u.value = Ee(I.value) : (u.value = null, D.value = Math.min(D.value, _.maxCount ?? 0));
      }
    }), b = G(!1);
    Fe([() => _.show], ([h]) => {
      h && (D.value = 0);
    });
    function n() {
      U(_.sku, He(D.value), u.value);
    }
    function t(h) {
      if (u.value)
        return !0;
      const x = ut(h).isInteger().max(_.maxCount ?? 0).error ?? "";
      return x || !0;
    }
    function o(h) {
      var P;
      const x = (P = _.sku.convert) != null && P.measurement ? _.sku.unit.measurements.find((l) => {
        var r;
        return l.id === ((r = _.sku.convert) == null ? void 0 : r.measurement);
      }) ?? null : null, B = $e(_.sku.unit, x), A = Et(+h);
      return ut(A).isInteger().max(B).error ? "Precision cannot be more than " + B : !0;
    }
    const w = E(
      () => {
        var h, x;
        return (h = _.sku.convert) != null && h.measurement ? (x = _.sku.unit.measurements.find((B) => {
          var A;
          return B.id === ((A = _.sku.convert) == null ? void 0 : A.measurement);
        })) == null ? void 0 : x.abbrev : _.sku.unit.abbrev;
      }
    ), H = E(() => {
      var A, q;
      const x = jt({
        bindings: ((A = _.sku.convert) == null ? void 0 : A.inventoryBindings) ?? [],
        skus: v.skus,
        skuGroups: v.skuGroups,
        recipes: v.recipes
      }).inventoryBindings.filter((P) => "success" in P && P.success).map((P) => P).map((P) => P.binding);
      return (q = u.value ?? x) == null ? void 0 : q.map((P) => {
        var te, le, X, se, re;
        const l = v.skus.find((ie) => ie._id === P.id), r = ((te = P.measurement) == null ? void 0 : te.abbrev) ?? ((le = l == null ? void 0 : l.unit) == null ? void 0 : le.abbrev), F = (X = _.sku.convert) != null && X.measurement ? _.sku.unit.measurements.find((ie) => {
          var pe;
          return ie.id === ((pe = _.sku.convert) == null ? void 0 : pe.measurement);
        }) ?? null : null, $ = $e(_.sku.unit, F), a = o(`${D.value}`) === !0 ? he(
          Ut(
            P.amount,
            He(+D.value, $)
          ),
          !1
        ) : "0", p = (re = (se = u.value) == null ? void 0 : se.find((ie) => ie.id === (l == null ? void 0 : l._id))) == null ? void 0 : re.amount, L = p ? he(p, !1) : null;
        return {
          sku: l,
          convertAmount: L ?? a,
          abbrev: r
        };
      });
    }), R = G();
    m({
      validateInputs: () => {
        var h, x;
        (x = (h = R.value) == null ? void 0 : h.validateInputs) == null || x.call(h);
      },
      resetInputsValidation: () => {
        var h, x;
        (x = (h = R.value) == null ? void 0 : h.resetInputsValidation) == null || x.call(h);
      },
      resetInputs: () => {
        var h, x;
        (x = (h = R.value) == null ? void 0 : h.resetInputs) == null || x.call(h);
      }
    });
    const O = Ye(_, "show");
    async function U(h, x, B) {
      b.value = !0;
      try {
        await i.convertSku({
          conversions: [
            {
              doc: h,
              amount: x,
              overrides: B == null ? void 0 : B.map((A) => ({
                ...A,
                amount: {
                  ...A.amount,
                  amount: -1 * Math.abs(A.amount.amount)
                  // ensure truly negative
                }
              }))
            }
          ]
        }), S("update:show", !1), S("submitted");
      } catch (A) {
        g.open({
          title: "Something went wrong",
          message: `Cannot convert ${h.name}. Please try again.`,
          type: "error"
        }), console.error("error at converting stock amount", h, x, A);
      } finally {
        b.value = !1;
      }
    }
    function J(h, x, B) {
      const A = +x;
      let q = B;
      x.length > 0 && isFinite(A) ? q = B.map((P) => (P.id !== h || (P.amount = Se(A)), P)) : q = B.map((P) => (P.id !== h || (P.amount = { amount: 0, precision: 0 }), P)), u.value = q;
    }
    function N(h) {
      const x = d.value.find((B) => B._id === h);
      return x ? pt(x.unit, !0) : [];
    }
    function K(h, x) {
      const B = N(h), A = B.find((q) => q.value === x) ?? B.find((q) => q.value === null);
      return A ? {
        ...A,
        label: A.abbrev
      } : null;
    }
    function Y(h, x, B) {
      let A;
      if (x === null)
        A = B.map((q) => (q.id !== h || (q.measurement = null), q)) ?? [];
      else {
        const q = d.value.find((P) => P._id === h);
        A = B.map((P) => {
          var l, r;
          return P.id !== h || (P.measurement = (r = (l = q == null ? void 0 : q.unit) == null ? void 0 : l.measurements) == null ? void 0 : r.find((F) => F.id === x)), P;
        }) ?? [];
      }
      u.value = A;
    }
    function Q(h, x) {
      const B = x.filter((A) => A.id !== h);
      u.value = B;
    }
    function ne() {
      const h = (u.value ?? []).map((x) => ({
        ...x,
        type: tt.enum.SKU
      }));
      C.promptIngredientsBinding(
        h,
        (x) => u.value = x,
        _.sku._id
      );
    }
    return Fe(
      () => _.show,
      (h) => {
        h || (u.value = null, D.value = 0);
      }
    ), (h, x) => {
      const B = M("FmTextField"), A = M("FmForm"), q = M("FmCard"), P = M("FmSwitch"), l = M("FmFormGroup"), r = M("FmSelect"), F = M("FmButton"), $ = M("FmSideSheet");
      return j(), ee($, {
        "dismiss-away": "",
        modelValue: s(O),
        "onUpdate:modelValue": x[3] || (x[3] = (a) => Ue(O) ? O.value = a : null),
        "max-width": 500
      }, {
        "side-sheet-header": T(() => [
          e("div", fo, [
            e("div", vo, c(s(z)("inventory.stock.convert.title", { name: h.sku.name })), 1)
          ])
        ]),
        default: T(() => [
          e("div", po, [
            f(A, {
              ref_key: "formRef",
              ref: R,
              onValidationSuccess: n
            }, {
              default: T(() => [
                f(B, {
                  disabled: b.value,
                  "model-value": D.value,
                  "onUpdate:modelValue": x[0] || (x[0] = (a) => D.value = a),
                  label: s(z)("inventory.stock.convert.amount"),
                  rules: [t, o, s(Pe)(0)],
                  "append-text": w.value,
                  "helper-text": u.value ? void 0 : `Max ${h.maxCount} ${w.value}`
                }, null, 8, ["disabled", "model-value", "label", "rules", "append-text", "helper-text"])
              ]),
              _: 1
            }, 512),
            f(q, {
              variant: "outlined",
              class: "p-16"
            }, {
              default: T(() => [
                e("div", yo, [
                  e("div", _o, c(s(z)("inventory.stock.convert.deductionSummary")), 1),
                  (j(!0), W(ue, null, de(H.value, (a) => {
                    var p, L;
                    return j(), W("div", {
                      key: (p = a.sku) == null ? void 0 : p._id,
                      class: "flex items-center"
                    }, [
                      e("div", ko, c((L = a.sku) == null ? void 0 : L.name), 1),
                      e("div", ho, " -" + c(a.convertAmount) + " " + c(a.abbrev), 1)
                    ]);
                  }), 128))
                ])
              ]),
              _: 1
            }),
            f(q, { variant: "outlined" }, {
              default: T(() => [
                e("div", bo, [
                  f(P, {
                    value: "",
                    modelValue: k.value,
                    "onUpdate:modelValue": x[1] || (x[1] = (a) => k.value = a),
                    label: s(z)("inventory.stock.convert.overrideDeduction"),
                    "label-placement": "right"
                  }, null, 8, ["modelValue", "label"]),
                  k.value ? (j(), W(ue, { key: 0 }, [
                    f(l, {
                      modelValue: u.value,
                      rules: [s(Nt)(1, "Must have at least one ingredient binding")]
                    }, null, 8, ["modelValue", "rules"]),
                    e("div", go, [
                      e("div", xo, c(s(z)("inventory.stock.convert.ingredients")), 1),
                      (j(!0), W(ue, null, de(u.value, (a) => (j(), ee(l, {
                        key: a.id,
                        disabled: b.value,
                        modelValue: +s(he)(a.amount ?? { amount: 1, precision: 0 }),
                        rules: [
                          s(Ot)(
                            d.value.find((p) => p._id === a.id).unit,
                            a.measurement
                          ),
                          s(Pe)(0)
                        ]
                      }, {
                        default: T(({ invalid: p }) => {
                          var L, te, le;
                          return [
                            e("div", So, [
                              e("div", wo, c((L = d.value.find((X) => X._id === a.id)) == null ? void 0 : L.name), 1),
                              f(B, {
                                class: "xs:col-span-2",
                                disabled: b.value,
                                modelValue: +s(he)(
                                  a.amount ?? { amount: 1, precision: 0 }
                                ),
                                "onUpdate:modelValue": (X) => J(a.id, X, u.value ?? []),
                                invalid: p
                              }, null, 8, ["disabled", "modelValue", "onUpdate:modelValue", "invalid"]),
                              f(r, {
                                disabled: b.value,
                                class: "translate-y-[2px]",
                                items: N(a.id),
                                "model-value": (le = K(a.id, (te = a.measurement) == null ? void 0 : te.id)) == null ? void 0 : le.value,
                                "onUpdate:modelValue": (X) => Y(a.id, X, u.value ?? []),
                                invalid: p
                              }, {
                                "helper-text": T(() => x[4] || (x[4] = [])),
                                _: 2
                              }, 1032, ["disabled", "items", "model-value", "onUpdate:modelValue", "invalid"]),
                              f(F, {
                                disabled: b.value,
                                type: "button",
                                variant: "tertiary",
                                icon: "delete",
                                onClick: (X) => Q(a.id, u.value ?? [])
                              }, null, 8, ["disabled", "onClick"])
                            ])
                          ];
                        }),
                        _: 2
                      }, 1032, ["disabled", "modelValue", "rules"]))), 128))
                    ]),
                    e("div", null, [
                      f(F, {
                        icon: "link",
                        label: s(z)("inventory.stock.convert.linkIngredient"),
                        variant: "plain",
                        onClick: ne
                      }, null, 8, ["label"])
                    ])
                  ], 64)) : oe("", !0)
                ])
              ]),
              _: 1
            })
          ])
        ]),
        "side-sheet-footer": T(() => [
          e("div", Ao, [
            f(F, {
              loading: b.value,
              label: s(z)("inventory.stock.convert.convertButton"),
              onClick: x[2] || (x[2] = (a) => {
                var p, L;
                return (L = (p = R.value) == null ? void 0 : p.validateInputs) == null ? void 0 : L.call(p);
              })
            }, null, 8, ["loading", "label"])
          ])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
});
function De(V, m) {
  const y = He(V, m);
  return { ...y, amount: -y.amount };
}
function ct(V, m) {
  return He(Math.abs(V), m);
}
const Ge = {
  [ae.enum.DAMAGE]: {
    label: "Damage",
    toAdjustmentAmount: De
  },
  [ae.enum.WASTAGE]: {
    label: "Wastage",
    toAdjustmentAmount: De
  },
  [ae.enum.THEFT]: {
    label: "Theft",
    toAdjustmentAmount: De
  },
  [ae.enum.LOSE]: {
    label: "Lose",
    toAdjustmentAmount: De
  },
  [ae.enum.EXTRA]: {
    label: "Extra",
    toAdjustmentAmount: ct
  },
  [ae.enum.PURCHASE]: {
    label: "Purchase",
    toAdjustmentAmount: ct
  }
}, $o = { class: "col-span-2 flex" }, jo = { class: "flex-1" }, Vo = { class: "fm-typo-en-body-lg-600" }, Co = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Do = { class: "col-span-2 flex flex-col gap-4" }, Bo = { class: "flex gap-4 text-fm-color-typo-primary fm-typo-en-body-lg-600" }, Mo = {
  key: 0,
  class: "fm-typo-en-body-md-400 text-fm-color-typo-warning"
}, xt = /* @__PURE__ */ me({
  __name: "AdjustedItemForm",
  props: {
    modelValue: {},
    disabled: { type: Boolean },
    isBackdate: { type: Boolean }
  },
  emits: ["update:modelValue", "click:delete"],
  setup(V, { emit: m }) {
    const y = V, _ = m, { t: S } = fe(), C = Ne(), v = E(
      () => Object.keys(Ge).map((t) => ({
        label: Vt(t),
        value: t
      }))
    ), i = E(() => pt(y.modelValue.doc.unit, !0)), g = E({
      get() {
        return y.modelValue.type ?? ae.enum.PURCHASE;
      },
      set(t) {
        const o = {
          ...y.modelValue
        };
        o.type = t;
        const w = at(y.modelValue.amount);
        o.amount = Ge[o.type].toAdjustmentAmount(
          +he(w),
          w.precision
        ), _("update:modelValue", o);
      }
    }), z = E({
      get() {
        const t = at(y.modelValue.amount);
        return +he(t);
      },
      set(t) {
        const o = {
          ...y.modelValue
        }, w = Se(t);
        o.amount = Ge[g.value].toAdjustmentAmount(
          t,
          w.precision
        ), _("update:modelValue", o);
      }
    }), D = E({
      get() {
        var t;
        return ((t = y.modelValue.measurement) == null ? void 0 : t.id) ?? null;
      },
      set(t) {
        var w, H;
        const o = {
          ...y.modelValue
        };
        o.measurement = ((H = (w = y.modelValue.doc.unit) == null ? void 0 : w.measurements) == null ? void 0 : H.find((R) => R.id === t)) ?? null, _("update:modelValue", o);
      }
    }), u = E({
      get() {
        return y.modelValue.remark ?? "";
      },
      set(t) {
        const o = {
          ...y.modelValue
        };
        o.remark = t, _("update:modelValue", o);
      }
    }), d = E(() => {
      var o;
      const t = (o = C.stockBalance.skus) == null ? void 0 : o.find((w) => w.id === y.modelValue.doc._id);
      return (t == null ? void 0 : t.balance) ?? { amount: 0, precision: 0 };
    }), I = E(() => {
      const t = y.modelValue.amount, o = y.modelValue.measurement;
      return o ? _t(t, o.conversion) : t;
    }), k = E(
      () => y.isBackdate ? d.value : Je(d.value, I.value)
    ), b = E(
      () => Gt(k.value, y.modelValue.doc.unit)
    ), n = E(
      () => !y.isBackdate && I.value.amount < 0
    );
    return (t, o) => {
      const w = M("FmButton"), H = M("FmSelect"), R = M("FmTextarea"), O = M("FmCard");
      return j(), ee(O, {
        variant: "outlined",
        class: "grid grid-cols-2 gap-8 p-16"
      }, {
        default: T(() => [
          e("div", $o, [
            e("div", jo, [
              e("div", Vo, c(t.modelValue.doc.name), 1),
              e("div", Co, c(t.modelValue.doc.code), 1)
            ]),
            f(w, {
              variant: "tertiary",
              "prepend-icon": "delete",
              onClick: o[0] || (o[0] = (U) => _("click:delete"))
            })
          ]),
          f(H, {
            disabled: t.disabled,
            class: "col-span-2",
            label: "Type",
            items: v.value,
            modelValue: g.value,
            "onUpdate:modelValue": o[1] || (o[1] = (U) => g.value = U),
            rules: [s(Yt)()],
            "label-mark": "required"
          }, null, 8, ["disabled", "items", "modelValue", "rules"]),
          f(zt, {
            disabled: t.disabled,
            label: "Amount",
            step: +s(he)({
              amount: 1,
              precision: s($e)(t.modelValue.doc.unit, t.modelValue.measurement)
            }),
            modelValue: z.value,
            "onUpdate:modelValue": o[2] || (o[2] = (U) => z.value = U),
            rules: [s(Pe)(0)]
          }, null, 8, ["disabled", "step", "modelValue", "rules"]),
          f(H, {
            disabled: t.disabled,
            label: "Unit",
            items: i.value,
            modelValue: D.value,
            "onUpdate:modelValue": o[3] || (o[3] = (U) => D.value = U)
          }, null, 8, ["disabled", "items", "modelValue"]),
          f(R, {
            class: "col-span-2",
            disabled: t.disabled,
            label: "Remark",
            modelValue: u.value,
            "onUpdate:modelValue": o[4] || (o[4] = (U) => u.value = U),
            "label-mark": "optional"
          }, null, 8, ["disabled", "modelValue"]),
          e("div", Do, [
            e("div", Bo, c(s(S)("inventory.stock.stock_adjustment.stockAfter")), 1),
            e("div", {
              class: Ie(["fm-typo-en-body-lg-600", n.value ? "text-red-700" : "text-green-700"])
            }, c(b.value), 3),
            t.isBackdate ? (j(), W("div", Mo, c(s(S)("inventory.stock.stock_adjustment.backdatePreviewWarning")), 1)) : oe("", !0)
          ])
        ]),
        _: 1
      });
    };
  }
}), Io = { class: "flex items-center" }, To = { class: "fm-typo-en-title-md-800" }, Ho = { class: "flex items-center" }, Po = { class: "fm-typo-en-title-sm-800 flex-1" }, Uo = { class: "flex gap-8" }, Eo = /* @__PURE__ */ me({
  __name: "AdjustSkuDialog",
  props: {
    stock: {},
    show: { type: Boolean }
  },
  emits: ["update:show", "submitted"],
  setup(V, { expose: m, emit: y }) {
    const _ = V, S = y, C = Re(), v = Oe(), i = Ae(), g = we(), z = G(!1), { t: D } = fe();
    function u() {
      b(Ee(k));
    }
    const d = G();
    m({
      validateInputs: () => {
        var o, w;
        (w = (o = d.value) == null ? void 0 : o.validateInputs) == null || w.call(o);
      },
      resetInputsValidation: () => {
        var o, w;
        (w = (o = d.value) == null ? void 0 : o.resetInputsValidation) == null || w.call(o);
      },
      resetInputs: () => {
        var o, w;
        (w = (o = d.value) == null ? void 0 : o.resetInputs) == null || w.call(o);
      }
    });
    const I = Ye(_, "show"), k = mt({
      remark: "",
      adjustments: [
        {
          id: `sku_${(/* @__PURE__ */ new Date()).toISOString()}_${Math.random().toString(16).slice(2, 8)}`,
          type: ae.enum.PURCHASE,
          doc: _.stock,
          measurement: null,
          remark: "",
          amount: Se(1)
        }
      ]
    });
    Fe([() => _.show], ([o]) => {
      o && (k.remark = "", k.adjustments = [
        {
          id: `sku_${(/* @__PURE__ */ new Date()).toISOString()}_${Math.random().toString(16).slice(2, 8)}`,
          type: ae.enum.PURCHASE,
          doc: _.stock,
          measurement: null,
          remark: "",
          amount: Se(1)
        }
      ]);
    });
    async function b(o) {
      z.value = !0;
      try {
        await i.adjustSku({
          remark: o.remark,
          adjustments: o.adjustments.map(({ doc: w, remark: H, type: R, amount: O, measurement: U }) => ({
            id: w._id,
            amount: O,
            measurement: U,
            remark: H,
            doc: w,
            type: R
          }))
        }), S("update:show", !1), S("submitted");
      } catch (w) {
        g.open({
          title: D("inventory.stock.adjust.error.title"),
          message: D("inventory.stock.adjust.error.message"),
          type: "error"
        }), console.log("error on adjust ingredients", o, w);
      } finally {
        z.value = !1;
      }
    }
    function n() {
      const o = C.skus.map((H) => ({
        label: H.name,
        sublabel: H.code,
        value: H._id
      })), w = o.filter((H) => k.adjustments.find((R) => R.doc._id === H.value)).map((H) => H.value);
      v.open({
        title: "Select ingredients",
        contentComponent: kt,
        contentComponentProps: {
          items: o,
          modelValue: w
        },
        overlay: !0,
        closeButton: !0,
        dismissAway: !0,
        primaryActions: {
          text: "Confirm",
          close: !0
        },
        secondaryActions: {
          text: "Close",
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((H) => {
        k.adjustments = H.map(
          (R) => k.adjustments.find((O) => O.doc._id === R) ?? {
            id: `sku_${(/* @__PURE__ */ new Date()).toISOString()}_${Math.random().toString(16).slice(2, 8)}`,
            type: ae.enum.PURCHASE,
            doc: C.skus.find((O) => O._id === R),
            measurement: null,
            remark: "",
            amount: Se(1)
          }
        );
      });
    }
    function t(o) {
      k.adjustments.splice(o, 1);
    }
    return (o, w) => {
      const H = M("FmTextarea"), R = M("FmButton"), O = M("FmForm"), U = M("FmSideSheet");
      return j(), ee(U, {
        modelValue: s(I),
        "onUpdate:modelValue": w[2] || (w[2] = (J) => Ue(I) ? I.value = J : null),
        "dismiss-away": "",
        "max-width": 500
      }, {
        "side-sheet-header": T(() => [
          e("div", Io, [
            e("div", To, c(s(D)("inventory.stock.adjust.title")), 1)
          ])
        ]),
        default: T(() => [
          f(O, {
            class: "w-full flex flex-col gap-12",
            ref_key: "formRef",
            ref: d,
            onValidationSuccess: u
          }, {
            default: T(() => [
              f(H, {
                label: s(D)("inventory.stock.adjust.remark"),
                modelValue: k.remark,
                "onUpdate:modelValue": w[0] || (w[0] = (J) => k.remark = J)
              }, null, 8, ["label", "modelValue"]),
              e("div", Ho, [
                e("div", Po, c(s(D)("inventory.stock.adjust.adjustedItems")), 1),
                f(R, {
                  "prepend-icon": "add",
                  variant: "tertiary",
                  size: "md",
                  onClick: n
                })
              ]),
              (j(!0), W(ue, null, de(k.adjustments, (J, N) => (j(), ee(xt, {
                key: J.id,
                modelValue: k.adjustments[N],
                "onUpdate:modelValue": (K) => k.adjustments[N] = K,
                "onClick:delete": (K) => t(N)
              }, null, 8, ["modelValue", "onUpdate:modelValue", "onClick:delete"]))), 128))
            ]),
            _: 1
          }, 512)
        ]),
        "side-sheet-footer": T(() => [
          e("div", Uo, [
            f(R, {
              label: s(D)("inventory.stock.adjust.adjustButton"),
              loading: z.value,
              onClick: w[1] || (w[1] = (J) => {
                var N, K;
                return (K = (N = d.value) == null ? void 0 : N.validateInputs) == null ? void 0 : K.call(N);
              })
            }, null, 8, ["label", "loading"])
          ])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), Ro = { class: "flex items-center w-full gap-8" }, No = { class: "fm-typo-en-title-md-800 flex-1" }, Oo = {
  key: 0,
  class: "flex flex-col gap-4"
}, Yo = { class: "fm-typo-en-body-md-600" }, Lo = { class: "flex gap-8 items-start" }, zo = { class: "flex-1 min-w-0" }, Go = { class: "flex-1 min-w-0" }, Wo = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Ko = { class: "flex items-center" }, qo = { class: "fm-typo-en-title-sm-800 flex-1" }, Xo = { class: "flex gap-8" }, dt = 14, Jo = /* @__PURE__ */ me({
  __name: "StockAdjustmentSideSheet",
  props: {
    show: { type: Boolean }
  },
  emits: ["update:show", "submitted"],
  setup(V, { emit: m }) {
    const y = V, _ = m, { t: S } = fe(), C = Re(), v = Ae(), i = Oe(), g = we(), z = Ye(y, "show"), D = G(!1), u = mt({
      remark: "",
      effectiveAt: /* @__PURE__ */ new Date(),
      adjustments: []
    }), d = G(!1), I = G(ke().format("YYYY-MM-DD")), k = G(ke().format("HH:mm")), b = G();
    Fe([I, k], () => {
      if (I.value && k.value) {
        const K = ke(`${I.value} ${k.value}`, "YYYY-MM-DD HH:mm");
        K.isValid() && (u.effectiveAt = K.toDate());
      }
    });
    const n = E(() => `${I.value} ${k.value}`);
    function t() {
      if (!d.value) return !0;
      const K = ke(`${I.value} ${k.value}`, "YYYY-MM-DD HH:mm");
      if (!K.isValid()) return S("inventory.stock.stock_adjustment.invalidDateTime");
      const Y = ke();
      if (K.isAfter(Y))
        return S("inventory.stock.stock_adjustment.futureDateNotAllowed");
      const Q = Y.subtract(dt, "day");
      return K.isBefore(Q) ? S("inventory.stock.stock_adjustment.backdateLimitError", { days: dt }) : !0;
    }
    const o = E(() => [() => t()]), w = E(() => u.adjustments.length === 0 || t() !== !0);
    function H() {
      u.remark = "", u.effectiveAt = /* @__PURE__ */ new Date(), u.adjustments = [], d.value = !1, I.value = ke(u.effectiveAt).format("YYYY-MM-DD"), k.value = ke(u.effectiveAt).format("HH:mm");
    }
    function R() {
      H();
    }
    const O = E(() => {
      const K = {};
      return C.skus.forEach((Y) => {
        K[Y._id] = Y;
      }), K;
    });
    function U() {
      const K = C.skus.map((Q) => ({
        label: Q.name,
        sublabel: Q.code,
        value: Q._id
      })), Y = u.adjustments.map((Q) => Q.doc._id);
      i.open({
        title: S("inventory.stock.adjust.selectIngredients"),
        contentComponent: kt,
        contentComponentProps: {
          items: K,
          modelValue: Y,
          virtualScroll: !0
        },
        overlay: !0,
        closeButton: !0,
        dismissAway: !0,
        primaryActions: {
          text: S("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: S("common.close"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((Q) => {
        u.adjustments = Q.map(
          (ne) => u.adjustments.find((h) => h.doc._id === ne) ?? {
            id: "",
            type: ae.enum.PURCHASE,
            doc: O.value[ne],
            measurement: null,
            remark: "",
            amount: Se(1)
          }
        );
      });
    }
    function J(K) {
      u.adjustments.splice(K, 1);
    }
    async function N() {
      if (u.adjustments.length === 0) {
        g.open({
          title: S("inventory.stock.error.title"),
          message: S("inventory.stock.stock_adjustment.noAdjustments"),
          type: "warning"
        });
        return;
      }
      D.value = !0;
      try {
        const K = u.adjustments.map(
          ({ doc: Q, remark: ne, type: h, amount: x, measurement: B }) => ({
            id: Q._id,
            amount: x,
            measurement: B,
            remark: ne,
            doc: Q,
            type: h
          })
        ), Y = {
          remark: u.remark,
          adjustments: K,
          ...d.value ? { effectiveAt: u.effectiveAt.toISOString() } : {}
        };
        await v.adjustSku(Ee(Y)), _("submitted"), _("update:show", !1);
      } catch (K) {
        g.open({
          title: S("inventory.stock.adjust.error.title"),
          message: S("inventory.stock.adjust.error.message"),
          type: "error"
        }), console.error("error on stock adjustment", K);
      } finally {
        D.value = !1;
      }
    }
    return (K, Y) => {
      const Q = M("FmTextarea"), ne = M("FmSwitch"), h = M("FmDatePicker"), x = M("FmTimePicker"), B = M("FmFormGroup"), A = M("FmButton"), q = M("FmForm"), P = M("FmSideSheet");
      return j(), ee(P, {
        modelValue: s(z),
        "onUpdate:modelValue": Y[6] || (Y[6] = (l) => Ue(z) ? z.value = l : null),
        "dismiss-away": "",
        "max-width": 560,
        onAfterEnter: R
      }, {
        "side-sheet-header": T(() => [
          e("div", Ro, [
            e("div", No, c(s(S)("inventory.stock.stock_adjustment.title")), 1)
          ])
        ]),
        default: T(() => [
          f(q, {
            class: "flex flex-col gap-16",
            ref_key: "formRef",
            ref: b,
            onValidationSuccess: N
          }, {
            default: T(() => [
              f(Q, {
                label: s(S)("inventory.stock.adjust.remark"),
                modelValue: u.remark,
                "onUpdate:modelValue": Y[0] || (Y[0] = (l) => u.remark = l),
                "label-mark": "optional"
              }, null, 8, ["label", "modelValue"]),
              f(ne, {
                value: "",
                "model-value": d.value,
                "onUpdate:modelValue": Y[1] || (Y[1] = (l) => d.value = l),
                label: s(S)("inventory.stock.stock_adjustment.backdateLabel"),
                sublabel: s(S)("inventory.stock.stock_adjustment.backdateSublabel"),
                labelPlacement: "right"
              }, null, 8, ["model-value", "label", "sublabel"]),
              d.value ? (j(), W("div", Oo, [
                e("label", Yo, c(s(S)("inventory.stock.stock_adjustment.effectiveAt")), 1),
                e("div", Lo, [
                  e("div", zo, [
                    f(h, {
                      class: "w-full",
                      modelValue: I.value,
                      "onUpdate:modelValue": Y[2] || (Y[2] = (l) => I.value = l),
                      clearable: !1
                    }, null, 8, ["modelValue"])
                  ]),
                  e("div", Go, [
                    f(x, {
                      class: "w-full",
                      modelValue: k.value,
                      "onUpdate:modelValue": Y[3] || (Y[3] = (l) => k.value = l),
                      format: "HH:mm"
                    }, null, 8, ["modelValue"])
                  ])
                ]),
                f(B, {
                  "model-value": n.value,
                  rules: o.value
                }, null, 8, ["model-value", "rules"]),
                e("div", Wo, c(s(S)("inventory.stock.stock_adjustment.immediateHint")), 1)
              ])) : oe("", !0),
              e("div", Ko, [
                e("div", qo, c(s(S)("inventory.stock.adjust.adjustedItems")), 1),
                f(A, {
                  "prepend-icon": "add",
                  variant: "tertiary",
                  size: "md",
                  onClick: U
                })
              ]),
              (j(!0), W(ue, null, de(u.adjustments, (l, r) => (j(), ee(xt, {
                key: l.doc._id,
                modelValue: u.adjustments[r],
                "onUpdate:modelValue": (F) => u.adjustments[r] = F,
                "is-backdate": d.value,
                "onClick:delete": (F) => J(r)
              }, null, 8, ["modelValue", "onUpdate:modelValue", "is-backdate", "onClick:delete"]))), 128))
            ]),
            _: 1
          }, 512)
        ]),
        "side-sheet-footer": T(() => [
          e("div", Xo, [
            f(A, {
              label: s(S)("common.confirm"),
              loading: D.value,
              disabled: w.value,
              onClick: Y[4] || (Y[4] = (l) => {
                var r, F;
                return (F = (r = b.value) == null ? void 0 : r.validateInputs) == null ? void 0 : F.call(r);
              })
            }, null, 8, ["label", "loading", "disabled"]),
            f(A, {
              label: s(S)("common.close"),
              variant: "tertiary",
              onClick: Y[5] || (Y[5] = (l) => _("update:show", !1))
            }, null, 8, ["label"])
          ])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), Qo = Ct((V, m) => ({
  // TODO: remove once latest inventory backend has been push
  async findBillsByBusinessId(y, _, S) {
    const C = `${V.businessesBackendUrl}/${y}/reports/find-many`, v = {
      //   type: TYPE.bill,
      type: "bill",
      restaurantIds: _,
      ids: S
    };
    return await m.post(C, v);
  },
  async findBillsById(y) {
    const S = je().currentLocationDBName, C = `${V.inventoryBackendUrl}/${S}/bill/search`, v = {
      ids: y
    };
    return await m.post(C, v);
  }
})), Zo = {
  key: 0,
  class: "flex justify-center items-center h-32"
}, en = { class: "mb-3" }, tn = { class: "flex flex-col gap-8" }, on = { class: "flex flex-col text-fm-color-typo-primary mb-3 text-center" }, nn = { class: "text-fm-color-neutral-gray-400 fm-typo-en-body-sm-600" }, sn = { class: "flex flex-col gap-4 text-fm-color-typo-primary mb-3" }, an = { class: "flex flex-col gap-4 text-fm-color-typo-primary mb-3" }, ln = { class: "flex flex-col gap-4 text-fm-color-typo-primary mb-3" }, rn = { class: "flex flex-col w-full px-2" }, un = { class: "flex gap-2" }, cn = /* @__PURE__ */ me({
  __name: "AmendAdjustmentForm",
  props: /* @__PURE__ */ Qe({
    adjustmentId: {}
  }, {
    modelValue: {},
    modelModifiers: {}
  }),
  emits: /* @__PURE__ */ Qe(["refreshHistory"], ["update:modelValue"]),
  setup(V, { emit: m }) {
    const y = V, _ = m, S = Ae(), C = St(V, "modelValue"), v = G(!1), i = G(!1), g = G(!1), z = G({
      _id: `inventoryAdjustment_${(/* @__PURE__ */ new Date()).toISOString()}_XXXXX`,
      skus: []
    }), D = G();
    Ke(async () => {
      v.value = !0;
      const n = await S.readSingleAdjustment(y.adjustmentId);
      if (!n) throw new Error("Adjustment not found");
      z.value = n, v.value = !1;
    });
    async function u() {
      var t, o;
      if ((o = (t = D == null ? void 0 : D.value) == null ? void 0 : t.validateInputs) == null || o.call(t), !i.value) return;
      const n = {};
      Object.keys(C.value || {}).forEach((w) => {
        var H;
        Object.keys(((H = C.value) == null ? void 0 : H[w]) || {}).forEach((R) => {
          var U, J;
          const O = (J = (U = C.value) == null ? void 0 : U[w]) == null ? void 0 : J[Number(R)];
          O && I(O.amount) > 0 && (n[w] || (n[w] = []), n[w].push(O));
        });
      }), await S.revertWastageAdjustment({
        targetWastageAdjustmentId: y.adjustmentId,
        amountsGoingToAdjust: n
      }), _("refreshHistory"), g.value = !1, C.value = {};
    }
    function d(n) {
      const { skuId: t, idx: o, unit: w, measurement: H } = n;
      return E({
        get: () => {
          var U, J, N;
          const R = (N = (J = (U = C.value) == null ? void 0 : U[t]) == null ? void 0 : J[o]) == null ? void 0 : N.amount;
          return R ? Number(_e.toFormatString({ value: R })) : 0;
        },
        set: (R) => {
          C.value || (C.value = {});
          const O = { ...C.value };
          O[t] || (O[t] = {}), O[t][o] = {
            amount: _e.convertPrecision({
              value: _e.fromNumber(R),
              precision: $e(w)
            }),
            type: ae.Enum.WASTAGE,
            measurement: H
          }, C.value = O;
        }
      });
    }
    function I(n, t = !0) {
      const o = Number(_e.toFormatString({ value: n }));
      return t ? Math.abs(o) : o;
    }
    function k(n, t) {
      return t.measurement ? t.measurement.abbrev : n.sku.unit.abbrev;
    }
    function b(n, t) {
      if (t.amount === 0) return "N/A";
      const o = _e.add([n, t]);
      return o ? _e.toFormatString({ value: o }) : "N/A";
    }
    return (n, t) => {
      const o = M("FmIcon"), w = M("FmStepperField"), H = M("FmCard"), R = M("FmForm"), O = M("FmSpacer"), U = M("FmButton"), J = M("FmDialog");
      return j(), ee(J, {
        modelValue: g.value,
        "onUpdate:modelValue": t[4] || (t[4] = (N) => g.value = N),
        overlay: !0
      }, {
        "dialog-button": T(() => [
          f(Xe, null, {
            default: T(() => [
              e("button", {
                onClick: t[0] || (t[0] = (N) => g.value = !0),
                class: "rounded-md hover:bg-gray-100 transition-colors"
              }, [
                f(o, {
                  name: "edit",
                  size: "sm"
                })
              ])
            ]),
            _: 1
          })
        ]),
        "dialog-header": T(() => t[5] || (t[5] = [
          e("div", null, "Amend Adjustment", -1)
        ])),
        "dialog-footer": T(() => [
          e("div", rn, [
            t[13] || (t[13] = e("span", { class: "text-fm-color-system-warning-400 fm-typo-en-body-sm-400" }, "1. New adjustment EXTRA will be created for each reversal", -1)),
            e("div", un, [
              f(O),
              f(U, {
                class: "sm:w-full xs:w-full",
                label: "Close",
                size: "md",
                variant: "tertiary",
                onClick: t[3] || (t[3] = (N) => g.value = !1)
              }),
              f(U, {
                class: "sm:w-full xs:w-full",
                label: "Submit",
                size: "md",
                variant: "primary",
                onClick: u
              })
            ])
          ])
        ]),
        default: T(() => [
          v.value ? (j(), W("div", Zo)) : (j(), ee(R, {
            key: 1,
            ref_key: "formRef",
            ref: D,
            onValidationFailed: t[1] || (t[1] = () => {
              i.value = !1;
            }),
            onValidationSuccess: t[2] || (t[2] = () => {
              i.value = !0;
            }),
            blameFormChildOnValidationFailed: ""
          }, {
            default: T(() => [
              e("p", en, [
                t[6] || (t[6] = e("b", null, "Date:", -1)),
                t[7] || (t[7] = e("br", null, null, -1)),
                ve(" " + c(s(Wt)(s(Dt)(z.value._id))), 1)
              ]),
              e("div", tn, [
                (j(!0), W(ue, null, de(z.value.skus, (N, K) => (j(), W(ue, { key: K }, [
                  (j(!0), W(ue, null, de(N.amounts, (Y, Q) => (j(), ee(H, {
                    key: Q,
                    variant: "outlined",
                    class: "p-2"
                  }, {
                    default: T(() => [
                      e("div", on, [
                        e("span", nn, c(N.sku.code), 1),
                        e("span", null, c(N.sku.name), 1)
                      ]),
                      t[12] || (t[12] = e("hr", { class: "m-2" }, null, -1)),
                      e("div", sn, [
                        t[8] || (t[8] = e("span", { class: "fm-typo-en-body-lg-600" }, "Adjustment type:", -1)),
                        e("span", null, c(Y.type), 1)
                      ]),
                      e("div", an, [
                        t[9] || (t[9] = e("span", { class: "fm-typo-en-body-lg-600" }, "Current amount:", -1)),
                        e("span", null, c(s(_e).toFormatString({ value: Y.amount })) + " " + c(k(N, Y)), 1)
                      ]),
                      f(w, {
                        "max-fraction-digits": s($e)(N.sku.unit),
                        "model-value": d({
                          skuId: N.sku._id,
                          idx: Q,
                          unit: N.sku.unit
                        }).value,
                        "onUpdate:modelValue": (ne) => d({
                          skuId: N.sku._id,
                          idx: Q,
                          unit: N.sku.unit
                        }).value = ne,
                        class: "mb-3",
                        label: "Adjust Amount (Leave 0 to skip)",
                        "helper-text": `Max: ${I(Y.amount)}`,
                        "append-text": k(N, Y),
                        rules: [
                          (ne) => ne <= I(Y.amount) || `Cannot be more than ${I(Y.amount)}`,
                          s(Pe)(-1)
                        ]
                      }, null, 8, ["max-fraction-digits", "model-value", "onUpdate:modelValue", "helper-text", "append-text", "rules"]),
                      e("div", ln, [
                        t[10] || (t[10] = e("span", { class: "fm-typo-en-body-lg-600" }, "Amount after amend:", -1)),
                        t[11] || (t[11] = e("span", { class: "text-fm-color-system-warning-400 fm-typo-en-body-sm-400" }, "* It's an estimate for your reference, as it didn't include all the reversals related to this adjustment", -1)),
                        ve(" " + c(b(
                          Y.amount,
                          s(_e).fromNumber(
                            d({
                              skuId: N.sku._id,
                              idx: Q,
                              unit: N.sku.unit
                            }).value
                          )
                        )) + " " + c(k(N, Y)), 1)
                      ])
                    ]),
                    _: 2
                  }, 1024))), 128))
                ], 64))), 128))
              ])
            ]),
            _: 1
          }, 512))
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), dn = { class: "p-16" }, mn = { class: "fm-typo-en-body-md-600 flex-grow" }, fn = { class: "flex-grow text-fm-color-typo-secondary" }, vn = {
  key: 0,
  class: "my-5"
}, pn = { class: "text-neutral-400" }, yn = { class: "flex-grow" }, _n = { class: "flex gap-1" }, kn = { class: "flex flex-col gap-1" }, hn = {
  key: 1,
  class: "t-system text-fsecondary"
}, bn = {
  key: 2,
  class: "text-xs text-gray-400"
}, gn = { key: 3 }, xn = { key: 4 }, Sn = {
  key: 5,
  class: "inline-flex items-center rounded-md bg-yellow-400/10 px-2 text-xs font-medium text-yellow-500 inset-ring inset-ring-yellow-400/20"
}, wn = {
  key: 1,
  class: "shrink-0 text-fm-color-typo-secondary"
}, An = /* @__PURE__ */ me({
  __name: "StockRecordCard",
  props: {
    record: {},
    sku: {},
    bills: { default: () => [] },
    unitCostHistory: { default: () => [] },
    costMechanism: { default: "adjustment" }
  },
  setup(V) {
    const m = V;
    function y(D, u) {
      if (m.costMechanism === "adjustment")
        return null;
      const d = m.unitCostHistory.filter(
        (b) => b.mechanism === m.costMechanism && b.skuId === m.sku._id
      );
      if (d.length === 0) return null;
      const I = d.find((b) => {
        const n = b.meta;
        return (n == null ? void 0 : n.adjustmentId) === D;
      });
      if (I) return I.cost;
      const k = [...d].filter((b) => new Date(b.snapshotAt) <= new Date(u)).sort((b, n) => new Date(n.snapshotAt).getTime() - new Date(b.snapshotAt).getTime());
      return k.length > 0 ? k[0].cost : null;
    }
    const _ = G(!1), S = G(), C = G(null), v = E(() => C.value === null ? "unset" : _.value ? `${C.value}px` : "0px");
    Ke(() => {
      var D;
      C.value = ((D = S.value) == null ? void 0 : D.scrollHeight) || 0;
    });
    const i = E(() => {
      var b;
      const D = m.record.adjustments, u = m.sku, d = {}, k = D.flatMap((n) => {
        var t;
        return ((t = n.skus) == null ? void 0 : t.filter((o) => o.sku._id === u._id)) ?? [];
      }).flatMap((n) => n.amounts);
      for (const n of k) {
        const t = n.measurement ? _t(n.measurement.conversion, n.amount) : n.amount;
        d[b = n.type] ?? (d[b] = { amount: 0, precision: 0 }), d[n.type] = Je(t, d[n.type]);
      }
      return Object.entries(d).reduce(
        (n, [t, o]) => (n[t] = /// comment, because without it formatter makes code uglier
        `${Z.toFormatString({
          value: o,
          precision: 4
        })} ${u.unit.abbrev}`, n),
        {}
      );
    }), { t: g } = fe(), z = E(() => m.record.adjustmentsByTime.map(({ date: D, adjustments: u }) => ({
      time: Kt(new Date(D)),
      adjustments: u.flatMap(
        (d) => {
          var I, k;
          return ((k = (I = d.skus) == null ? void 0 : I.map) == null ? void 0 : k.call(I, (b) => {
            var n, t;
            return {
              ...b,
              ref: d.ref,
              reason: d.reason,
              adjustmentRemark: d.remark,
              backdateFrom: d.effectiveAt != null ? Te(d._id) : null,
              toBalance: (t = (n = d.skus) == null ? void 0 : n[0]) == null ? void 0 : t.toBalance,
              adjustmentId: d._id,
              adjustmentTime: d.effectiveAt ?? Te(d._id)
            };
          })) ?? [];
        }
      ).flatMap((d) => {
        var t;
        const I = (t = m.bills.find((o) => o._id === d.ref)) == null ? void 0 : t.seqNumber, k = I ? g("inventory.stock.record.bill", [I]) : "", b = d.adjustmentTime ?? (/* @__PURE__ */ new Date()).toISOString(), n = y(d.adjustmentId, b);
        return (d.amounts || []).filter((o) => o != null).map((o) => {
          var R;
          let w = o.cost;
          if (n) {
            const O = Z.fromDinero(n), U = o.amount, J = o.measurement ? Z.multiply([U, o.measurement.conversion]) : U;
            w = {
              ...Z.multiply([
                O,
                J
              ]),
              currency: n.currency
            };
          }
          let H = "";
          return k ? H = o.remark || "" : H = [d.adjustmentRemark, o.remark].filter((U) => U).join("/"), {
            amount: `${Z.toFormatString({ value: o.amount, precision: 4 })} ${((R = o.measurement) == null ? void 0 : R.abbrev) ?? d.sku.unit.abbrev}`,
            backdateFrom: d.backdateFrom,
            name: o.type,
            billRemark: k,
            remark: H,
            reason: d.reason || "",
            cost: w,
            toBalance: Z.toFormatString({
              value: d.toBalance ?? Z.fromNumber(0),
              precision: 4
            }),
            baseUnit: d.sku.unit.abbrev,
            adjustmentId: d.adjustmentId
          };
        });
      })
    })));
    return (D, u) => {
      const d = M("FmIcon"), I = M("FmTooltip"), k = M("FmCard");
      return j(), ee(k, { variant: "outlined" }, {
        default: T(() => [
          e("div", dn, [
            e("div", {
              class: "flex items-center cursor-pointer mb-1",
              onClick: u[0] || (u[0] = (b) => _.value = !_.value)
            }, [
              e("div", mn, c(D.record.date), 1),
              f(d, {
                name: _.value ? "expand_more" : "expand_less",
                color: "#777777",
                size: "md"
              }, null, 8, ["name"])
            ]),
            (j(!0), W(ue, null, de(i.value, (b, n) => (j(), W("div", {
              key: n,
              class: "flex flex-row py-1",
              style: { "font-size": "0.8rem" }
            }, [
              e("div", fn, c(s(g)(`inventory.inventoryAdjustment.type.${n}`)), 1),
              e("div", {
                class: Ie({
                  "text-fm-color-typo-error": b.startsWith("-"),
                  "text-fm-color-typo-success": !b.startsWith("-"),
                  "ml-auto": !0
                })
              }, c(b), 3)
            ]))), 128)),
            e("div", {
              ref_key: "detailRef",
              ref: S,
              style: ft({
                fontSize: "0.8rem",
                maxHeight: v.value,
                overflow: "hidden",
                transition: "max-height 0.2s ease-out"
              })
            }, [
              z.value.length ? (j(), W("hr", vn)) : oe("", !0),
              (j(!0), W(ue, null, de(z.value, (b) => (j(), W("div", {
                key: b.time,
                class: "flex gap-1 w-full"
              }, [
                e("div", pn, c(b.time), 1),
                e("div", yn, [
                  (j(!0), W(ue, null, de(b.adjustments, (n) => (j(), W("div", {
                    key: n.name,
                    class: "flex gap-1"
                  }, [
                    e("div", _n, [
                      ve(c(s(g)(`inventory.inventoryAdjustment.type.${n.name}`)) + " ", 1),
                      n.backdateFrom ? (j(), ee(I, {
                        key: 0,
                        variant: "plain",
                        placement: "top",
                        "z-index": 50
                      }, {
                        content: T(() => [
                          e("div", kn, c(s(g)("inventory.stock.record.backdate", [
                            s(ht)(new Date(n.backdateFrom))
                          ])), 1)
                        ]),
                        default: T(() => [
                          f(d, {
                            name: "info",
                            size: "sm",
                            color: "primary"
                          })
                        ]),
                        _: 2
                      }, 1024)) : oe("", !0),
                      n.billRemark ? (j(), W("span", hn, " # " + c(n.billRemark), 1)) : oe("", !0),
                      n.billRemark && n.remark ? (j(), W("span", bn, " (" + c(n.remark) + ") ", 1)) : oe("", !0),
                      !n.billRemark && n.reason ? (j(), W("span", gn, " (" + c(n.reason) + ") ", 1)) : oe("", !0),
                      !n.billRemark && n.remark ? (j(), W("span", xn, " # " + c(n.remark), 1)) : oe("", !0),
                      n.name === s(ae).Enum.CLOSING ? (j(), W("span", Sn, " Actual Balance: " + c(n.toBalance) + " " + c(n.baseUnit), 1)) : oe("", !0)
                    ]),
                    e("div", {
                      class: Ie({
                        "text-fm-color-typo-error": n.amount.startsWith("-"),
                        "text-fm-color-typo-success": !n.amount.startsWith("-"),
                        "ml-auto": !0
                      })
                    }, c(n.amount), 3),
                    n.name === s(ae).Enum.WASTAGE ? (j(), ee(cn, {
                      key: 0,
                      adjustmentId: n.adjustmentId,
                      onRefreshHistory: u[1] || (u[1] = (t) => D.$emit("refreshHistory"))
                    }, null, 8, ["adjustmentId"])) : oe("", !0),
                    n.cost ? (j(), W("div", wn, " (" + c(s(Be)(n.cost, !1, n.cost.precision)) + ") ", 1)) : oe("", !0)
                  ]))), 128))
                ])
              ]))), 128))
            ], 4)
          ])
        ]),
        _: 1
      });
    };
  }
});
function Fn(V, m) {
  var C;
  const y = Object.keys(ae.enum).reduce(
    (v, i) => (v[i] = { amount: 0, precision: 0 }, v),
    {}
  );
  if (!m)
    return Object.entries(y).reduce(
      (v, [i]) => (v[i] = Z.fromNumber(0), v),
      {}
    );
  const S = V.flatMap((v) => {
    var i;
    return ((i = v.skus) == null ? void 0 : i.filter((g) => g.sku._id === m._id)) ?? [];
  }).flatMap((v) => v.amounts);
  for (const v of S) {
    const i = v.measurement ? Z.multiply([v.measurement.conversion, v.amount]) : v.amount;
    y[C = v.type] ?? (y[C] = { amount: 0, precision: 0 }), y[v.type] = Z.add([i, y[v.type]]);
  }
  return Object.entries(y).reduce(
    (v, [i, g]) => {
      const z = {
        ...g,
        amount: Math.abs(g.amount)
      };
      return v[i] = /// comment, because without it formatter makes code uglier
      `${Z.toFormatString({
        value: z,
        precision: 4
      })} ${m.unit.abbrev}`, v;
    },
    {}
  );
}
function $n(V, m) {
  if (!m)
    return null;
  let y = null;
  const S = V.flatMap((C) => {
    var v;
    return ((v = C.skus) == null ? void 0 : v.filter((i) => i.sku._id === m._id)) ?? [];
  }).flatMap((C) => {
    var v;
    return !C.history || ((v = C.history) == null ? void 0 : v.length) === 0 ? [] : C.history[0];
  });
  for (const C of S) {
    const v = C.amounts;
    for (const i of v) {
      if (i.type !== ae.Enum.SALES)
        continue;
      const g = i.measurement ? Z.multiply([i.measurement.conversion, i.amount]) : i.amount;
      y ?? (y = Z.fromNumber(0)), y = Z.add([y, g]);
    }
  }
  return y != null ? (y.amount = Math.abs(y.amount), `${Z.toFormatString({
    value: y,
    precision: 4
  })} ${m.unit.abbrev}`) : null;
}
const jn = { class: "flex items-center w-full fm-typo-en-title-md-800" }, Vn = { class: "flex-1 line-clamp-2" }, Cn = { class: "flex flex-col gap-32 w-full h-full" }, Dn = { class: "flex items-center relative gap-4" }, Bn = { class: "flex-1" }, Mn = {
  key: 0,
  class: "flex-1 flex flex-col items-center gap-16"
}, In = { class: "fm-typo-en-body-lg-400 translate-x-4" }, Tn = {
  key: 1,
  class: "flex flex-col gap-12"
}, Hn = { class: "pb-16" }, Pn = { class: "fm-typo-cn-body-lg-600" }, Un = {
  class: "grid gap-12 fm-typo-en-body-md-400",
  style: { "grid-template-columns": "auto auto auto", "grid-auto-rows": "1fr" }
}, En = { class: "flex flex-col gap-1" }, Rn = { class: "text-fm-color-typo-secondary" }, Nn = { class: "font-bold" }, On = { class: "flex flex-col gap-1" }, Yn = { class: "text-fm-color-typo-secondary flex" }, Ln = { class: "font-bold" }, zn = { class: "flex flex-col gap-1" }, Gn = { class: "text-fm-color-typo-secondary" }, Wn = { class: "font-bold" }, Kn = { class: "flex flex-col gap-1" }, qn = { class: "text-fm-color-typo-secondary" }, Xn = { class: "font-bold" }, Jn = { class: "flex flex-col gap-1" }, Qn = { class: "text-fm-color-typo-secondary" }, Zn = { class: "font-bold" }, es = { class: "flex flex-col gap-1" }, ts = { class: "text-fm-color-typo-secondary" }, os = { class: "font-bold" }, ns = { class: "flex flex-col gap-1" }, ss = { class: "text-fm-color-typo-secondary" }, as = { class: "font-bold" }, ls = { class: "flex flex-col gap-1" }, rs = { class: "text-fm-color-typo-secondary" }, is = { class: "font-bold" }, us = { class: "flex flex-col gap-1" }, cs = { class: "text-fm-color-typo-secondary" }, ds = { class: "font-bold" }, ms = {
  key: 0,
  class: "flex flex-col gap-8"
}, fs = { class: "flex" }, vs = { class: "flex-1 flex flex-col gap-1" }, ps = { class: "flex gap-1 items-center text-fm-color-typo-secondary" }, ys = { class: "font-bold" }, _s = { class: "flex-1 flex flex-col gap-1" }, ks = { class: "flex gap-1 items-center text-fm-color-typo-secondary" }, hs = { class: "flex flex-col gap-1" }, bs = { class: "font-bold" }, gs = {
  key: 2,
  class: "flex-1 flex flex-col items-center gap-8"
}, xs = ["src"], Ss = { class: "font-bold text-lg" }, ws = { class: "text-xs text-neutral-400 text-center" }, As = /* @__PURE__ */ me({
  __name: "StockHistory",
  props: {
    sku: {},
    show: { type: Boolean }
  },
  emits: ["update:show"],
  setup(V) {
    const m = qe(), y = Ne(), _ = Ae(), S = Qo(), C = je(), v = to(), { t: i } = fe(), g = V, z = G(!1), D = we(), u = G("adjustment"), d = G([
      { label: "Adjustment (Default)", value: "adjustment" }
    ]), I = G([]), k = G(Qt(0));
    async function b() {
      z.value = !0;
      try {
        await R(), await y.readStockBalance();
      } catch (l) {
        D.open({
          title: "Something went wrong",
          message: "Cannot fetch stock history. Please try again.",
          type: "error"
        }), console.log("failed at fetching item adjustment history", g.sku, k, l);
      } finally {
        z.value = !1;
      }
    }
    Ke(() => {
      b();
    }), Fe([() => k.value, () => g.sku], () => {
      b();
    });
    const n = G([]), t = G([]), o = G(new Array());
    function w(l, r) {
      return r === "day" ? Jt(l) : ht(l);
    }
    function H(l, r) {
      const F = l.reduce(
        ($, a) => {
          const p = a.effectiveAt ?? Te(a._id);
          if (!p)
            return $;
          const L = w(new Date(p), r);
          return $[L] ?? ($[L] = []), $[L].push(a), $;
        },
        {}
      );
      return Object.keys(F).map(($) => ({
        date: $,
        adjustments: F[$]
      }));
    }
    async function R() {
      let l = await _.readStockAdjustment(
        g.sku._id,
        lt(new Date(k.value.startDate)).toISOString(),
        rt(new Date(k.value.endDate)).toISOString()
      );
      n.value = l;
      const r = l.filter(({ ref: F }) => F == null ? void 0 : F.startsWith("bill_")).map(({ ref: F }) => F);
      await O(r), t.value = H(l, "day").map(({ date: F, adjustments: $ }) => ({
        date: F,
        adjustments: $,
        adjustmentsByTime: H($, "minute")
      }));
      try {
        const F = await _.readUnitCostHistory(
          g.sku._id,
          lt(new Date(k.value.startDate)).toISOString(),
          rt(new Date(k.value.endDate)).toISOString()
        );
        I.value = F;
        const $ = /* @__PURE__ */ new Set();
        F.forEach((p) => {
          $.add(p.mechanism);
        });
        const a = [{ label: "Default", value: "adjustment" }];
        $.has(xe.Enum.weightedAverage) && a.push({
          label: "Weighted Average (Beta)",
          value: xe.Enum.weightedAverage
        }), $.has(xe.Enum.netsuite) && a.push({ label: "NetSuite (Beta)", value: xe.Enum.netsuite }), $.has(xe.Enum["netsuite-average"]) && a.push({
          label: "NetSuite Average (Beta)",
          value: xe.Enum["netsuite-average"]
        }), d.value = a, !$.has(u.value) && u.value !== "adjustment" && (u.value = "adjustment");
      } catch (F) {
        console.error("Failed to fetch unit cost history:", F);
      }
    }
    async function O(l) {
      l.length && (o.value = await S.findBillsById(l).catch((r) => {
        var a;
        console.error("Error on using latest bill API, retrying using legacy api", r);
        const F = ((a = m.currentBusiness.value) == null ? void 0 : a._id) ?? "", $ = C.currentLocation.doc._id;
        return S.findBillsByBusinessId(F, [$], l);
      }));
    }
    const U = E(() => {
      const l = n.value, r = g.sku;
      return Fn(l, r);
    }), J = E(() => {
      const l = n.value, r = g.sku;
      return $n(l, r);
    }), N = E(() => {
      const l = [...n.value].computeFirst((F) => {
        var a, p;
        const $ = (p = (a = F.skus) == null ? void 0 : a.find) == null ? void 0 : p.call(a, (L) => L.sku._id === g.sku._id);
        return $ == null ? void 0 : $.fromBalance;
      }) ?? {
        amount: 0,
        precision: 0
      }, r = g.sku;
      return r ? `${Z.toFormatString({
        value: l,
        precision: 4
      })} ${r.unit.abbrev}` : "";
    }), K = E(() => {
      const l = [...n.value].reverse().computeFirst((F) => {
        var a, p;
        const $ = (p = (a = F.skus) == null ? void 0 : a.find) == null ? void 0 : p.call(a, (L) => L.sku._id === g.sku._id);
        return $ == null ? void 0 : $.toBalance;
      }) ?? {
        amount: 0,
        precision: 0
      }, r = g.sku;
      return r ? `${Z.toFormatString({ value: l, precision: 4 })} ${r.unit.abbrev}` : "";
    }), Y = E(() => {
      var F;
      const r = n.value.flatMap(($) => {
        var a;
        return ((a = $.skus) == null ? void 0 : a.flatMap((p) => p.amounts)) ?? [];
      }).filter(($) => $.amount.amount < 0).reduce(
        ($, a) => {
          const p = a.cost;
          if (!p) return $;
          const L = {
            ...Rt($, Math.max($.precision, p.precision)),
            currency: p.currency
          };
          return {
            ...Je(L, p),
            currency: $.currency
          };
        },
        {
          amount: 0,
          precision: 0,
          currency: Ve((F = m.currentCountry) == null ? void 0 : F.value)
        }
      );
      return Be(r, !1, r.precision);
    });
    function Q() {
      const { startDate: l, endDate: r } = qt(k.value);
      l !== null && r !== null && (k.value = {
        startDate: l,
        endDate: r
      });
    }
    const ne = E(() => i("inventory.ingredient.valuationMethod.WAVG"));
    function h(l, r) {
      if (u.value === "adjustment")
        return null;
      const F = I.value.filter(
        (p) => p.mechanism === u.value && p.skuId === g.sku._id
      );
      if (F.length === 0) return null;
      const $ = F.find((p) => {
        const L = p.meta;
        return (L == null ? void 0 : L.adjustmentId) === l;
      });
      if ($) return $.cost;
      const a = [...F].filter((p) => new Date(p.snapshotAt) <= new Date(r)).sort((p, L) => new Date(L.snapshotAt).getTime() - new Date(p.snapshotAt).getTime());
      return a.length > 0 ? a[0].cost : null;
    }
    const x = E(() => {
      var $, a, p, L, te, le;
      const l = [...n.value].reverse().find((X) => {
        var se, re;
        return (re = (se = X.skus) == null ? void 0 : se.find) == null ? void 0 : re.call(se, (ie) => ie.sku._id === g.sku._id);
      });
      if (!l) return "No data";
      const r = ($ = l.skus) == null ? void 0 : $.find((X) => X.sku._id === g.sku._id);
      if (!r) return "No data";
      const F = r.toBalance;
      if (u.value === "adjustment") {
        const X = [...r.amounts].reverse()[0], se = {
          amount: ((a = X.cost) == null ? void 0 : a.amount) ?? 0,
          precision: ((p = X.cost) == null ? void 0 : p.precision) ?? 0
        }, re = X.amount, ie = re.amount == 0 ? Z.fromNumber(0) : Z.divide([se, re]);
        return {
          ...Z.multiply([ie, F]),
          currency: ((L = X.cost) == null ? void 0 : L.currency) || Ve(((te = m.currentCountry) == null ? void 0 : te.value) ?? ot)
        };
      } else {
        const X = l.effectiveAt ?? Te(l._id), se = h(
          l._id,
          X ?? (/* @__PURE__ */ new Date()).toISOString()
        );
        if (!se) return "No data";
        const re = Z.fromDinero(se);
        return {
          ...Z.multiply([re, F]),
          currency: se.currency || Ve(((le = m.currentCountry) == null ? void 0 : le.value) ?? ot)
        };
      }
    }), B = E(() => {
      var F;
      const l = [...n.value].reverse().computeFirst(($) => {
        var p, L;
        const a = (L = (p = $.skus) == null ? void 0 : p.find) == null ? void 0 : L.call(p, (te) => te.sku._id === g.sku._id);
        return a == null ? void 0 : a.toCostBalances;
      });
      return l ? {
        ...l.reduce(($, a) => Z.add([$, Z.fromDinero(a.cost)]), {
          amount: 0,
          precision: 0
        }),
        currency: Ve((F = m.currentCountry) == null ? void 0 : F.value)
      } : "No data";
    }), A = E(() => g.sku.valuation === nt.Enum.FIFO ? B.value : x.value);
    function q() {
      const { startDate: l, endDate: r } = Xt(k.value);
      l !== null && r !== null && (k.value = {
        startDate: l,
        endDate: r
      });
    }
    const P = Ye(g, "show");
    return (l, r) => {
      const F = M("FmButton"), $ = M("FmField"), a = M("FmDateRangePicker"), p = M("FmSpacer"), L = M("FmCircularProgress"), te = M("FmIcon"), le = M("FmTooltip"), X = M("FmMenuDivider"), se = M("FmChip"), re = M("FmSelect"), ie = M("FmCardSection"), pe = M("FmCard"), be = M("FmSideSheet");
      return j(), ee(be, {
        "dismiss-away": "",
        modelValue: s(P),
        "onUpdate:modelValue": r[5] || (r[5] = (ye) => Ue(P) ? P.value = ye : null),
        "close-button": !1,
        "max-width": 560
      }, {
        "side-sheet-header": T(() => [
          e("div", jn, [
            e("div", Vn, c(s(i)("inventory.stock.history.title", [l.sku.name])), 1),
            f(F, {
              variant: "tertiary",
              "prepend-icon": "close",
              onClick: r[0] || (r[0] = (ye) => P.value = !1)
            })
          ])
        ]),
        default: T(() => {
          var ye;
          return [
            e("div", Cn, [
              e("div", Dn, [
                e("div", Bn, [
                  f(a, {
                    modelValue: k.value,
                    "onUpdate:modelValue": r[1] || (r[1] = (ce) => k.value = ce),
                    "show-predefined-range": "",
                    "start-label": "",
                    "end-label": "",
                    "z-index": 50
                  }, {
                    "trigger-button": T(({ opened: ce }) => [
                      f($, {
                        "prepend-icon": "calendar_month",
                        focused: ce
                      }, {
                        default: T(() => [
                          ve(c(k.value.startDate) + " - " + c(k.value.endDate), 1)
                        ]),
                        _: 2
                      }, 1032, ["focused"])
                    ]),
                    _: 1
                  }, 8, ["modelValue"])
                ]),
                f(F, {
                  variant: "tertiary",
                  onClick: r[2] || (r[2] = (ce) => Q()),
                  "prepend-icon": "navigate_before"
                }),
                f(F, {
                  variant: "tertiary",
                  onClick: r[3] || (r[3] = (ce) => q()),
                  "prepend-icon": "navigate_next"
                })
              ]),
              z.value ? (j(), W("div", Mn, [
                f(p),
                f(L, { size: "xl" }),
                e("div", In, c(s(i)("inventory.stock.history.loading")), 1),
                f(p),
                f(p)
              ])) : t.value && ((ye = t.value) == null ? void 0 : ye.length) > 0 ? (j(), W("div", Tn, [
                f(pe, { variant: "outlined" }, {
                  default: T(() => [
                    f(ie, { class: "flex flex-col gap-4" }, {
                      default: T(() => [
                        e("div", Hn, [
                          e("div", Pn, c(s(i)("inventory.stock.history.summary.title")), 1)
                        ]),
                        e("div", Un, [
                          e("div", En, [
                            e("div", Rn, c(s(i)("inventory.stock.history.summary.totalPurchase")), 1),
                            e("div", Nn, c(U.value.PURCHASE), 1)
                          ]),
                          e("div", On, [
                            e("div", Yn, [
                              ve(c(s(i)("inventory.stock.history.summary.totalSales")) + "  ", 1),
                              J.value != null ? (j(), ee(le, {
                                key: 0,
                                variant: "plain",
                                placement: "top",
                                content: `Before: ${J.value}`,
                                "z-index": 50
                              }, {
                                default: T(() => [
                                  f(te, {
                                    name: "warning",
                                    size: "sm"
                                  })
                                ]),
                                _: 1
                              }, 8, ["content"])) : oe("", !0)
                            ]),
                            e("div", Ln, c(U.value.SALES), 1)
                          ]),
                          e("div", zn, [
                            e("div", Gn, c(s(i)("inventory.stock.history.summary.totalLose")), 1),
                            e("div", Wn, c(U.value.LOSE), 1)
                          ]),
                          e("div", Kn, [
                            e("div", qn, c(s(i)("inventory.stock.history.summary.totalRequest")), 1),
                            e("div", Xn, c(U.value.REQUEST), 1)
                          ]),
                          e("div", Jn, [
                            e("div", Qn, c(s(i)("inventory.stock.history.summary.totalReceive")), 1),
                            e("div", Zn, c(U.value.RECEIVE), 1)
                          ]),
                          e("div", es, [
                            e("div", ts, c(s(i)("inventory.stock.history.summary.totalConvert")), 1),
                            e("div", os, c(U.value.CONVERT), 1)
                          ]),
                          e("div", ns, [
                            e("div", ss, c(s(i)("inventory.stock.history.summary.totalDamage")), 1),
                            e("div", as, c(U.value.DAMAGE), 1)
                          ]),
                          e("div", ls, [
                            e("div", rs, c(s(i)("inventory.stock.history.summary.openingBalance")), 1),
                            e("div", is, c(N.value), 1)
                          ]),
                          e("div", us, [
                            e("div", cs, c(s(i)("inventory.stock.history.summary.lastStockBalance")), 1),
                            e("div", ds, c(K.value), 1)
                          ])
                        ]),
                        s(v).enableTotalCost ? (j(), W("div", ms, [
                          f(X, { class: "w-full" }),
                          e("div", fs, [
                            e("div", vs, [
                              f(st, { "z-index": 50 }, {
                                default: T(() => [
                                  e("div", ps, [
                                    ve(c(s(i)("inventory.stock.history.estimatedValue")) + " ", 1),
                                    f(le, {
                                      variant: "plain",
                                      placement: "top",
                                      content: `[${ne.value}] ${s(i)("inventory.stock.history.estimatedValueTooltip")}`,
                                      "z-index": 50
                                    }, {
                                      default: T(() => [
                                        f(te, {
                                          name: "help",
                                          size: "sm"
                                        })
                                      ]),
                                      _: 1
                                    }, 8, ["content"])
                                  ])
                                ]),
                                _: 1
                              }),
                              e("div", ys, [
                                l.sku.valuation === s(nt).Enum.FIFO ? (j(), W(ue, { key: 0 }, [
                                  f(se, {
                                    label: "FIFO",
                                    compact: ""
                                  }),
                                  ve(" " + c(typeof A.value != "string" ? s(Be)(
                                    A.value,
                                    !1,
                                    A.value.precision
                                  ) : A.value), 1)
                                ], 64)) : (j(), W(ue, { key: 1 }, [
                                  ve(c(typeof A.value != "string" ? s(Be)(
                                    A.value,
                                    !1,
                                    A.value.precision
                                  ) : A.value), 1)
                                ], 64))
                              ]),
                              f(re, {
                                modelValue: u.value,
                                "onUpdate:modelValue": r[4] || (r[4] = (ce) => u.value = ce),
                                items: d.value,
                                compact: "",
                                size: "sm",
                                style: { width: "200px" }
                              }, null, 8, ["modelValue", "items"])
                            ]),
                            e("div", _s, [
                              f(st, { "z-index": 50 }, {
                                default: T(() => [
                                  e("div", ks, [
                                    ve(c(s(i)("inventory.stock.history.costSold")) + " ", 1),
                                    f(le, {
                                      variant: "plain",
                                      placement: "top",
                                      "z-index": 50
                                    }, {
                                      content: T(() => [
                                        e("div", hs, c(s(i)("inventory.stock.history.costSoldTooltip")), 1)
                                      ]),
                                      default: T(() => [
                                        f(te, {
                                          name: "help",
                                          size: "sm"
                                        })
                                      ]),
                                      _: 1
                                    })
                                  ])
                                ]),
                                _: 1
                              }),
                              e("div", bs, c(Y.value), 1)
                            ])
                          ])
                        ])) : oe("", !0)
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                }),
                r[6] || (r[6] = e("div", null, null, -1)),
                (j(!0), W(ue, null, de(t.value, (ce) => (j(), W(ue, {
                  key: ce.date
                }, [
                  l.sku ? (j(), ee(An, {
                    key: 0,
                    record: ce,
                    sku: l.sku,
                    bills: o.value,
                    "unit-cost-history": I.value,
                    "cost-mechanism": u.value,
                    onRefreshHistory: b
                  }, null, 8, ["record", "sku", "bills", "unit-cost-history", "cost-mechanism"])) : oe("", !0)
                ], 64))), 128))
              ])) : (j(), W("div", gs, [
                f(p),
                e("div", null, [
                  e("img", {
                    src: s(eo),
                    alt: "List is empty"
                  }, null, 8, xs)
                ]),
                e("div", Ss, c(s(i)("inventory.stock.history.noRecords")), 1),
                e("div", ws, c(s(i)("inventory.stock.history.changeDateRange")), 1),
                f(p),
                f(p)
              ]))
            ])
          ];
        }),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), Fs = /* @__PURE__ */ me({
  __name: "HrmPermissionGuard",
  props: {
    permission: { default: void 0 },
    permissions: { default: void 0 },
    mode: { default: "all" }
  },
  setup(V) {
    const m = V, y = E(() => {
      const S = [];
      return m.permission && S.push(m.permission), m.permissions && S.push(...m.permissions), S;
    });
    wt(() => {
    });
    const { hasPermission: _ } = bt(y, () => m.mode);
    return (S, C) => s(_) ? Ze(S.$slots, "default", { key: 0 }) : Ze(S.$slots, "fallback", { key: 1 });
  }
}), $s = {
  key: 0,
  class: "flex items-center gap-1"
}, js = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Vs = { class: "flex flex-col gap-8" }, Cs = { class: "flex flex-col" }, Ds = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Bs = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary line-clamp-1" }, ua = /* @__PURE__ */ me({
  __name: "StockView",
  setup(V) {
    const { t: m } = fe(), y = Re(), _ = je(), S = Ne(), C = gt(), v = Ae(), i = yt(), g = no(), { columnDefs: z } = co(), D = qe(), { hasPermission: u } = bt(
      E(() => [{ action: Ce.Action.manage, subject: Ce.Subject.Business.inventory_stockAdjustment }])
    ), d = E(
      () => {
        var B;
        return u.value || ((B = D.sessionUser.value) == null ? void 0 : B.role.isAdmin);
      }
    ), I = Oe(), k = we();
    _.watchLocation(o);
    const b = E(
      () => new Set(g.getAvailableItems(g.businessSubsidiaryId))
    ), n = G(!1);
    async function t() {
      I.open({
        title: m("inventory.stock.stock_balance.refreshBalance"),
        message: m("inventory.stock.stock_balance.refreshBalanceDescription"),
        closeButton: !0,
        primaryActions: {
          text: m("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: m("common.close"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary(async () => {
        await v.recalculation.refreshCurrentBalances(), k.open({
          title: "Refresh Stock Balance",
          message: "Stock balance refresh has been queued. This may take a moment to complete.",
          type: "success"
        });
      });
    }
    async function o() {
      if (_._currentLocation) {
        n.value = !0;
        try {
          await S.readStockBalance(), await S.readProductBalance(), await i.readStockEstimateBalance();
        } catch (B) {
          k.open({
            title: m("inventory.stock.error.title"),
            message: m("inventory.stock.error.message"),
            type: "error"
          }), console.error("error on fetch stock balance", B);
        } finally {
          n.value = !1;
        }
      }
    }
    const w = E(() => [
      {
        type: "string",
        key: "status",
        entity: "sku",
        values: ["Active", "Inactive"]
      }
    ]), H = G({
      logic: "AND",
      rules: [
        {
          property: "status",
          operator: "$in",
          value: ["Active"],
          type: "string"
        }
      ]
    }), R = E(() => {
      var q, P, l;
      const B = H.value ? so.build(H.value) : null, A = [];
      for (const r of y.skus) {
        let F = !0;
        if (g.isEnabled && U.value && b.value && F && (F = b.value.has(r._id)), B && F && (F = ao(
          {
            status: r.isInactive ? "Inactive" : "Active"
          },
          B
        )), F) {
          const $ = r.trackingMeasurement;
          let a = (P = (q = S.stockBalance.skus) == null ? void 0 : q.find(
            (te) => te.id === r._id
          )) == null ? void 0 : P.balance, p = i.inventoryForecast.skus.find(
            (te) => te.id === r._id
          );
          const L = {
            ...r,
            balance: a ?? {
              amount: 0,
              precision: 0
            },
            operator: p == null ? void 0 : p.operator,
            day: (p == null ? void 0 : p.depletionDays) ?? void 0,
            trackingUnitAbbrev: $ ? ((l = r.unit.measurements.find((te) => te.id === $)) == null ? void 0 : l.abbrev) ?? "" : r.unit.abbrev
          };
          A.push(L);
        }
      }
      return A;
    }), O = G(""), U = G(!0), { breakpoints: J } = Ht(), N = E(() => J.value.xs || J.value.sm), K = E(() => N.value ? 10 : 20), Y = Ft(), Q = E(() => {
      const B = [
        {
          label: m("inventory.stock.stock_balance.refreshBalance"),
          value: "refresh-balance",
          isPrimary: !0,
          prependIcon: "calculate"
        },
        {
          label: m("inventory.common.refresh"),
          value: "refresh"
        },
        {
          label: m("inventory.common.export"),
          value: "export"
        }
      ];
      return d.value && B.push({
        label: m("inventory.stock.stock_adjustment.title"),
        value: "stockAdjustment"
      }), B;
    }), ne = G(!1);
    function h() {
      ne.value = !0;
    }
    function x(B) {
      switch (B) {
        case "refresh-balance":
          return t();
        case "refresh":
          return o();
        case "export":
          return Mt(R.value);
        case "stockAdjustment":
          return h();
      }
    }
    return (B, A) => {
      const q = M("FmSwitch"), P = M("FmTable");
      return j(), ee($t, {
        title: s(m)("inventory.stock.title"),
        actions: Q.value,
        "onClick:action": x
      }, {
        default: T(() => {
          var l, r, F, $;
          return [
            e("div", {
              class: Ie([
                "flex flex-col gap-8 max-h-full",
                {
                  "p-0": N.value,
                  "px-24 ": !N.value
                }
              ])
            }, [
              f(Zt, {
                searchable: "",
                "change-location": "",
                search: O.value,
                "onUpdate:search": A[1] || (A[1] = (a) => O.value = a),
                "hide-filter-options": !0,
                filterable: "",
                "filter-attributes": w.value,
                filter: H.value,
                "onUpdate:filter": A[2] || (A[2] = (a) => H.value = a)
              }, {
                default: T(() => [
                  s(g).isEnabled ? (j(), W("div", $s, [
                    e("span", js, c(s(m)("inventory.integration.netsuite.subsidiaryHierarchy.filtering")), 1),
                    f(It),
                    f(Xe, null, {
                      default: T(() => [
                        f(q, {
                          modelValue: U.value,
                          "onUpdate:modelValue": A[0] || (A[0] = (a) => U.value = a)
                        }, null, 8, ["modelValue"])
                      ]),
                      _: 1
                    })
                  ])) : oe("", !0)
                ]),
                _: 1
              }, 8, ["search", "filter-attributes", "filter"]),
              (j(), ee(P, {
                style: ft(s(Y).tableHeight),
                "column-defs": s(z),
                "row-data": R.value,
                "search-value": O.value,
                loading: n.value || !s(_)._currentLocation,
                key: (l = s(_)._currentLocation) == null ? void 0 : l.dbName,
                onRowClick: A[3] || (A[3] = (a) => s(C).showSkuHistory(a.original)),
                "page-size": K.value
              }, {
                "list-row": T((a) => [
                  f(oo, {
                    row: a,
                    onRowClick: s(C).showSkuHistory
                  }, {
                    default: T((p) => {
                      var L, te, le, X, se, re, ie, pe, be, ye;
                      return [
                        e("div", Vs, [
                          e("div", Cs, [
                            e("div", Ds, [
                              f(s(it), {
                                render: (le = (te = (L = p.code) == null ? void 0 : L.column) == null ? void 0 : te.columnDef) == null ? void 0 : le.cell,
                                props: (se = (X = p.code) == null ? void 0 : X.getContext) == null ? void 0 : se.call(X)
                              }, null, 8, ["render", "props"])
                            ]),
                            e("div", Bs, [
                              f(s(it), {
                                render: (pe = (ie = (re = p.name) == null ? void 0 : re.column) == null ? void 0 : ie.columnDef) == null ? void 0 : pe.cell,
                                props: (ye = (be = p.name) == null ? void 0 : be.getContext) == null ? void 0 : ye.call(be)
                              }, null, 8, ["render", "props"])
                            ])
                          ]),
                          e("div", null, [
                            f(We, {
                              days: a.original.day
                            }, null, 8, ["days"])
                          ]),
                          e("div", null, [
                            f(vt, {
                              class: "xs:w-[160px]",
                              unit: a.original.unit,
                              sku: a.original,
                              amount: a.original.balance,
                              "default-tracking-measurement": a.original.trackingMeasurement ?? void 0
                            }, null, 8, ["unit", "sku", "amount", "default-tracking-measurement"])
                          ])
                        ])
                      ];
                    }),
                    _: 2
                  }, 1032, ["row", "onRowClick"])
                ]),
                _: 1
              }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"]))
            ], 2),
            (j(), ee(At, { to: "body" }, [
              (r = s(C).stockHistoryProps) != null && r.sku ? (j(), ee(As, et(Le({ key: 0 }, s(C).stockHistoryProps)), null, 16)) : oe("", !0),
              (F = s(C).convertSkuDialogProps) != null && F.sku ? (j(), ee(Fo, et(Le({ key: 1 }, s(C).convertSkuDialogProps)), null, 16)) : oe("", !0),
              ($ = s(C).adjustSkuDialogProps) != null && $.stock ? (j(), ee(Eo, Le({ key: 2 }, s(C).adjustSkuDialogProps, {
                onSubmitted: A[4] || (A[4] = (a) => o())
              }), null, 16)) : oe("", !0),
              f(Fs, {
                permission: { action: s(Ce).Action.manage, subject: s(Ce).Subject.Business.inventory_stockAdjustment }
              }, {
                default: T(() => [
                  ne.value ? (j(), ee(Jo, {
                    key: 0,
                    show: ne.value,
                    "onUpdate:show": A[5] || (A[5] = (a) => ne.value = a),
                    onSubmitted: A[6] || (A[6] = (a) => o())
                  }, null, 8, ["show"])) : oe("", !0)
                ]),
                _: 1
              }, 8, ["permission"])
            ]))
          ];
        }),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  ua as default
};
