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

Last refreshed: ${new Date($.value).toLocaleString()}` : f;
      D.open({
        title: u("inventory.stock.stock_balance.refreshBalance"),
        message: v,
        closeButton: !0,
        primaryActions: {
          text: u("common.confirm"),
          close: !1,
          isLoading: O,
          disabled: O
        },
        secondaryActions: {
          text: u("common.close"),
          close: !0,
          variant: "tertiary",
          disabled: O
        }
      }).onPrimary(async () => {
        if (!t.value) {
          t.value = !0;
          try {
            await d.recalculation.refreshCurrentBalances();
          } catch (i) {
            console.log("Failed to queue refresh balan22ce", typeof i);
            const x = typeof i == "object" ? JSON.stringify(i) : String(i);
            console.log("Error details:", x), t.value = !1, m.open({
              title: u("inventory.common.refreshFailed"),
              message: (i instanceof Error ? i.message : null) ?? u("inventory.stock.stock_balance.refreshBalanceError"),
              type: "error"
            });
          }
        }
      }).onClose(() => {
        t.value = !1, N();
      });
    }
    async function X() {
      if (y._currentLocation) {
        o.value = !0;
        try {
          await S.readStockBalance(), await S.readProductBalance(), await r.readStockEstimateBalance();
        } catch (f) {
          m.open({
            title: u("inventory.stock.error.title"),
            message: u("inventory.stock.error.message"),
            type: "error"
          }), console.error("error on fetch stock balance", f);
        } finally {
          o.value = !1;
        }
      }
    }
    const z = T(() => [
      {
        type: "string",
        key: "status",
        entity: "sku",
        values: ["Active", "Inactive"]
      }
    ]), K = Y({
      logic: "AND",
      rules: [
        {
          property: "status",
          operator: "$in",
          value: ["Active"],
          type: "string"
        }
      ]
    }), U = T(() => {
      var i, x, P;
      const f = K.value ? mo.build(K.value) : null, v = [];
      for (const ee of k.skus) {
        let ae = !0;
        if (b.isEnabled && re.value && w.value && ae && (ae = w.value.has(ee._id)), f && ae && (ae = fo(
          {
            status: ee.isInactive ? "Inactive" : "Active"
          },
          f
        )), ae) {
          const Q = ee.trackingMeasurement;
          let W = (x = (i = S.stockBalance.skus) == null ? void 0 : i.find(
            (ce) => ce.id === ee._id
          )) == null ? void 0 : x.balance, te = r.inventoryForecast.skus.find(
            (ce) => ce.id === ee._id
          );
          const le = {
            ...ee,
            balance: W ?? {
              amount: 0,
              precision: 0
            },
            operator: te == null ? void 0 : te.operator,
            day: (te == null ? void 0 : te.depletionDays) ?? void 0,
            trackingUnitAbbrev: Q ? ((P = ee.unit.measurements.find((ce) => ce.id === Q)) == null ? void 0 : P.abbrev) ?? "" : ee.unit.abbrev
          };
          v.push(le);
        }
      }
      return v;
    }), Z = Y(""), re = Y(!0), { breakpoints: g } = Lt(), F = T(() => g.value.xs || g.value.sm), G = T(() => F.value ? 10 : 20), H = Bt(), J = T(() => {
      const f = [
        {
          label: u("inventory.stock.stock_balance.refreshBalance"),
          value: "refresh-balance",
          isPrimary: !0,
          prependIcon: "calculate"
        },
        {
          label: u("inventory.common.refresh"),
          value: "refresh"
        },
        {
          label: u("inventory.common.export"),
          value: "export"
        }
      ];
      return a.value && f.push({
        label: u("inventory.stock.stock_adjustment.title"),
        value: "stockAdjustment"
      }), f;
    }), I = Y(!1);
    function c() {
      I.value = !0;
    }
    function h(f) {
      switch (f) {
        case "refresh-balance":
          return L();
        case "refresh":
          return X();
        case "export":
          return Rt(U.value);
        case "stockAdjustment":
          return c();
      }
    }
    return (f, v) => {
      const i = B("FmSwitch"), x = B("FmTable");
      return V(), ne(Mt, {
        title: s(u)("inventory.stock.title"),
        actions: J.value,
        "onClick:action": h
      }, {
        default: M(() => {
          var P, ee, ae, Q;
          return [
            e("div", {
              class: He([
                "flex flex-col gap-8 max-h-full",
                {
                  "p-0": F.value,
                  "px-24 ": !F.value
                }
              ])
            }, [
              _(ro, {
                searchable: "",
                "change-location": "",
                search: Z.value,
                "onUpdate:search": v[1] || (v[1] = (W) => Z.value = W),
                "hide-filter-options": !0,
                filterable: "",
                "filter-attributes": z.value,
                filter: K.value,
                "onUpdate:filter": v[2] || (v[2] = (W) => K.value = W)
              }, {
                default: M(() => [
                  s(b).isEnabled ? (V(), q("div", Hs, [
                    e("span", Ts, p(s(u)("inventory.integration.netsuite.subsidiaryHierarchy.filtering")), 1),
                    _(Nt),
                    _(Je, null, {
                      default: M(() => [
                        _(i, {
                          modelValue: re.value,
                          "onUpdate:modelValue": v[0] || (v[0] = (W) => re.value = W)
                        }, null, 8, ["modelValue"])
                      ]),
                      _: 1
                    })
                  ])) : se("", !0)
                ]),
                _: 1
              }, 8, ["search", "filter-attributes", "filter"]),
              (V(), ne(x, {
                style: kt(s(H).tableHeight),
                "column-defs": s(R),
                "row-data": U.value,
                "search-value": Z.value,
                loading: o.value || s(n) || !s(y)._currentLocation,
                key: (P = s(y)._currentLocation) == null ? void 0 : P.dbName,
                onRowClick: v[3] || (v[3] = (W) => s(j).showSkuHistory(W.original)),
                "page-size": G.value
              }, {
                "list-row": M((W) => [
                  _(uo, {
                    row: W,
                    onRowClick: s(j).showSkuHistory
                  }, {
                    default: M((te) => {
                      var le, ce, je, me, de, Ze, et, tt, Ve, ot;
                      return [
                        e("div", Es, [
                          e("div", Us, [
                            e("div", Ps, [
                              _(s(ft), {
                                render: (je = (ce = (le = te.code) == null ? void 0 : le.column) == null ? void 0 : ce.columnDef) == null ? void 0 : je.cell,
                                props: (de = (me = te.code) == null ? void 0 : me.getContext) == null ? void 0 : de.call(me)
                              }, null, 8, ["render", "props"])
                            ]),
                            e("div", Rs, [
                              _(s(ft), {
                                render: (tt = (et = (Ze = te.name) == null ? void 0 : Ze.column) == null ? void 0 : et.columnDef) == null ? void 0 : tt.cell,
                                props: (ot = (Ve = te.name) == null ? void 0 : Ve.getContext) == null ? void 0 : ot.call(Ve)
                              }, null, 8, ["render", "props"])
                            ])
                          ]),
                          e("div", null, [
                            _(Ke, {
                              days: W.original.day
                            }, null, 8, ["days"])
                          ]),
                          e("div", null, [
                            _(ht, {
                              class: "xs:w-[160px]",
                              unit: W.original.unit,
                              sku: W.original,
                              amount: W.original.balance,
                              "default-tracking-measurement": W.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),
            (V(), ne(Dt, { to: "body" }, [
              (ee = s(j).stockHistoryProps) != null && ee.sku ? (V(), ne(Bs, at(ze({ key: 0 }, s(j).stockHistoryProps)), null, 16)) : se("", !0),
              (ae = s(j).convertSkuDialogProps) != null && ae.sku ? (V(), ne(Mo, at(ze({ key: 1 }, s(j).convertSkuDialogProps)), null, 16)) : se("", !0),
              (Q = s(j).adjustSkuDialogProps) != null && Q.stock ? (V(), ne(Go, ze({ key: 2 }, s(j).adjustSkuDialogProps, {
                onSubmitted: v[4] || (v[4] = (W) => X())
              }), null, 16)) : se("", !0),
              _(Ms, {
                permission: {
                  action: s(De).Action.manage,
                  subject: s(De).Subject.Business.inventory_stockAdjustment
                }
              }, {
                default: M(() => [
                  I.value ? (V(), ne(sn, {
                    key: 0,
                    show: I.value,
                    "onUpdate:show": v[5] || (v[5] = (W) => I.value = W),
                    onSubmitted: v[6] || (v[6] = (W) => X())
                  }, null, 8, ["show"])) : se("", !0)
                ]),
                _: 1
              }, 8, ["permission"])
            ]))
          ];
        }),
        _: 1
      }, 8, ["title", "actions"]);
    };
  }
});
export {
  _a as default
};
