import { ref as A, h as P, defineComponent as K, resolveComponent as E, openBlock as $, createElementBlock as D, createElementVNode as _, normalizeClass as q, createTextVNode as ae, toDisplayString as I, unref as p, createCommentVNode as O, createVNode as C, withCtx as V, Fragment as j, renderList as Z, computed as L, watch as Pe, createSlots as Ee, createBlock as U, isRef as Ye, normalizeStyle as Ge, Teleport as Ke, normalizeProps as We, guardReactiveProps as qe, mergeProps as Je } from "vue";
import { u as Xe, _ as Qe } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { useI18n as W, useCoreStore as de } from "@feedmepos/mf-common";
import { useDialog as pe, useDialogChild as Ze, useSnackbar as ce, FmButtonVariant as oe, components as Y, FmAdvancedSort as et, useProxiedModel as tt, useBreakpoints as nt } from "@feedmepos/ui-library";
import { defineStore as Ve, storeToRefs as Ne } from "pinia";
import { F as G } from "./form-mode.enum-BKiNVH6A.js";
import { a as me } from "./closing-template-ar_kUs4X.js";
import { u as fe, c as Ue, a as ve, l as ot } from "./app-Bpb4394e.js";
import { t as re, a as ge, d as ye, s as Le, r as st } from "./xlsx.util-BPV2vsSD.js";
import { F as lt } from "./FmDroppableField-J0xUsOTV.js";
import { f as Be, a as le } from "./date2-DpnYOzUg.js";
import { D as se, R as z } from "./row-action.enum-DQ9bJ_uv.js";
import { c as at } from "./component-kqxARxvM.js";
import { f as rt } from "./format-time-from-id-BvLCC6cK.js";
import { _ as it } from "./TemplatePublishDialog.vue_vue_type_script_setup_true_lang-BKLYNLrJ.js";
import { u as ct } from "./netsuite-BGUUAOqe.js";
import { u as mt } from "./duplicate-template-ct64aRN_.js";
import { _ as ut } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { R as dt, A as pt } from "./rules-CoimOM7X.js";
import { u as ft } from "./use-ingredient-select-dialog-WYM92c37.js";
import { d as vt } from "./defineDeepModel-BF0Cvhza.js";
import { F as X, _ as ze } from "./TableActionableRow.vue_vue_type_script_setup_true_lang-Ca_eYa8-.js";
import { u as gt } from "./use-template-enabled-locations-Puw8RG4I.js";
import { _ as yt } from "./SystemTrailDialog.vue_vue_type_script_setup_true_lang-qJoe3Rw5.js";
import { _ as ht } from "./_plugin-vue_export-helper-CHgC5LLL.js";
const ue = Ve(
  "closingTemplateTable",
  function() {
    const { t: r } = W(), a = pe(), u = A({}), t = ie(), n = A({}), v = A(new Array()), b = A(!1), c = fe(), l = me();
    function g(o) {
      const f = {
        title: o.name,
        doc: o,
        controller: {
          publishAll: async (T) => {
            const e = T || o.locations, k = await l.publishSingleDoc(
              o._id,
              e == null ? void 0 : e.map((M) => M.dbName)
            );
            return u.value = k.publishedRevByLocation || {}, u.value;
          },
          publishAtLocation: async (T) => {
            const e = await l.publishSingleDoc(o._id, [T.dbName]);
            return u.value = e.publishedRevByLocation || {}, u.value;
          },
          unpublishAll: async (T) => {
            const e = T || o.locations, k = await l.unpublishSingleDoc(
              o._id,
              e == null ? void 0 : e.map((M) => M.dbName)
            );
            return u.value = k.publishedRevByLocation || {}, u.value;
          },
          unpublishAtLocation: async (T) => {
            const e = await l.unpublishSingleDoc(o._id, [
              T.dbName
            ]);
            return u.value = e.publishedRevByLocation || {}, u.value;
          }
        },
        initialPublishedRev: u.value,
        locations: c.locations,
        enabledLocations: o.locations
      };
      a.open({
        title: "Publish template",
        contentComponent: it,
        contentComponentProps: f,
        closeButton: !0,
        minWidth: 700,
        maxHeight: "80vh",
        contentScrollable: !1,
        primaryActions: {
          text: r("common.close"),
          close: !0,
          variant: "tertiary"
        }
      });
    }
    async function i() {
      if (v.value = [], !!c._currentLocation) {
        b.value = !0;
        try {
          const [o, f, T] = await Promise.all([
            l.readTemplates(),
            l.getRecentPublishingJob(),
            l.getRecentPublishInfo()
          ]).delayed(1e3);
          v.value = o, n.value = f, u.value = T.publishedRevByLocation || {};
        } catch (o) {
          console.log("Something went wrong when fetching templates:", o);
        } finally {
          b.value = !1;
        }
      }
    }
    async function h(o) {
      if (!v.value.find((f) => f._id) && c._currentLocation) {
        b.value = !0;
        try {
          const [f] = await Promise.all([
            l.getTemplate(o),
            new Promise((T) => setTimeout(T, 1e3))
          ]);
          v.value = [f];
        } catch (f) {
          console.log("Something went wrong when fetching templates:", f);
        } finally {
          b.value = !1;
        }
      }
    }
    function w(o, f) {
      switch (f = Ue(f), o) {
        case z.Details:
          return t.viewTemplate(f);
        case z.Edit:
          return t.updateTemplate(f);
        case z.Delete:
          return t.deleteTemplate(f, b, i);
        case z.Publish:
          return g(f);
        case z.Duplicate:
          return t.duplicateTemplate(f, b, i);
      }
    }
    return {
      columnDefs: [
        {
          id: "_id",
          accessorKey: "_id",
          header: () => r("inventory.closing.table.createdAt"),
          cell(o) {
            return rt(`${o.getValue()}`);
          },
          enableSorting: !0
        },
        {
          id: "name",
          accessorKey: "name",
          header: () => r("inventory.closing.table.name"),
          enableSorting: !0,
          size: 200
        },
        {
          id: "noOfItems",
          accessorKey: "items.length",
          header: () => r("inventory.closing.table.noOfItems"),
          enableSorting: !1,
          meta: {
            width: "10rem",
            textAlign: "right"
          }
        },
        {
          id: "enabledLocations",
          accessorKey: "locations.length",
          header: () => r("inventory.closing.table.enabledOutlets"),
          cell(o) {
            var T;
            const f = (T = o.row.original.locations) == null ? void 0 : T.length;
            return f ? `${f}` : "All";
          },
          enableSorting: !1,
          meta: {
            width: "10rem",
            textAlign: "right"
          }
        },
        {
          id: "ref",
          accessorKey: "ref",
          header: () => r("inventory.closing.table.reference"),
          enableSorting: !1,
          size: "auto"
        },
        {
          id: "status",
          header: () => r("inventory.adjustment.template.table.status"),
          enableSorting: !1,
          cell(o) {
            const f = o.row.original, e = (o.row.original.locations || c.locations).filter((d) => !!c.locationByDbName[d.dbName]), k = e.filter((d) => !!(u.value[d.dbName] || []).find(
              (x) => x._id === f._id && (x.updatedAt ? x.updatedAt === f.updatedAt : x._rev === f._rev)
            )).length, M = e.length > 0 && k === e.length;
            return P(
              "div",
              {
                class: "flex items-center gap-8"
              },
              P(
                "div",
                {
                  class: [
                    "fm-status-badge",
                    M ? "fm-status-badge-success-secondary" : "fm-status-badge-info-secondary"
                  ]
                },
                M ? "Published" : "Unpublished"
              )
            );
          }
        },
        {
          id: "action",
          cell(o) {
            const f = o.row.original, T = [
              se[z.Edit],
              se[z.Duplicate],
              se[z.Delete],
              se[z.Publish]
            ];
            return at(T, (e) => w(e, f));
          },
          enableSorting: !1,
          size: 40,
          meta: {
            cellClass: "",
            headerClass: ""
          }
        }
      ],
      recentPublish: n,
      templates: v,
      loading: b,
      fetchTemplates: i,
      loadTemplate: h
    };
  }
);
var he = /* @__PURE__ */ ((m) => (m.Ingredients = "Ingredients", m))(he || {});
function He(m) {
  const r = m.sku, a = new Set(m.disabledMeasurements);
  return [
    {
      code: r.code,
      name: r.name,
      unit: r.unit.abbrev,
      enabled: !a.has(r.unit._id)
    },
    ...r.unit.measurements.map((n) => ({
      unit: n.abbrev,
      enabled: !a.has(n.id)
    }))
  ];
}
function Oe() {
  return [
    {
      id: "code",
      name: "Code"
    },
    {
      id: "name",
      name: "Name"
    },
    {
      id: "unit",
      name: "Unit"
    },
    {
      id: "enabled",
      name: "Enabled"
    }
  ];
}
function bt(m) {
  var b;
  const a = de().currentBusiness.value, t = (b = m.map((c) => {
    var y;
    const l = c.items.flatMap(He), g = Oe(), i = [
      ["Template ID", c._id],
      ["Template name", c.name],
      ["Business name", a == null ? void 0 : a.name],
      ["Business ID", a == null ? void 0 : a._id],
      ["Menu version", a == null ? void 0 : a.menuVersion],
      [
        "Locations",
        ...(y = c.locations) != null && y.length ? c.locations.map((o) => `${o.name} (${o.dbName})`) : ["All"]
      ],
      ["Reference", c.ref ?? ""],
      [],
      g.map((o) => o.name),
      ...l.map((o) => g.map((f) => o[f.id]))
    ], h = g.map((o) => `system:${o.id}`), w = re(i, h);
    return { name: c.name, sheet: w };
  }).reduce(
    (c, l) => {
      var i;
      const g = l.name.slice(0, 12);
      return (i = c.sheetOccurence)[g] ?? (i[g] = 0), c.sheetOccurence[g] += 1, c.sheets[`${g} (${c.sheetOccurence[g]})`] = l.sheet, c;
    },
    {
      sheets: {},
      sheetOccurence: {}
    }
  )) == null ? void 0 : b.sheets, n = `${a == null ? void 0 : a.name} closing templates (${Be(/* @__PURE__ */ new Date())}).xlsx`, v = ge(t);
  return ye(v, n), n;
}
function _t(m) {
  de().currentBusiness.value;
  const a = 3, u = (i) => {
    const h = [], w = i.sku, y = new Set(i.disabledMeasurements || []);
    y.has(w.unit._id) || h.push(w.unit.abbrev);
    for (const o of w.unit.measurements) {
      if (h.length >= a) break;
      y.has(o.id) || h.push(o.abbrev);
    }
    return h;
  }, t = ["#", "Code", "Name", "UOM"], n = [
    ["Template:", m.name],
    ["Reference:", m.ref ?? ""],
    [],
    t,
    ...m.items.map((i, h) => {
      const w = u(i);
      return [
        h + 1,
        // Index starting from 1
        i.sku.code,
        i.sku.name,
        // Add UOM columns (up to MAX_UOM_COLUMNS)
        ...Array(a).fill("").map(
          (y, o) => w[o] ? `_____ ${w[o]}` : ""
        )
      ];
    })
  ], v = re(n, t);
  if (v["!ref"]) {
    const i = {
      top: { style: "thin", color: { rgb: "000000" } },
      bottom: { style: "thin", color: { rgb: "000000" } },
      left: { style: "thin", color: { rgb: "000000" } },
      right: { style: "thin", color: { rgb: "000000" } }
    }, h = 4, w = h + m.items.length, y = t.map((o, f) => String.fromCharCode(65 + f));
    for (let o = h; o <= w; o++)
      y.forEach((f) => {
        const T = `${f}${o}`;
        v[T] || (v[T] = { t: "s", v: "" }), v[T].s = {
          border: i
        };
      });
  }
  v["!cols"] = [
    { wch: 5 },
    // Index column - narrow
    { wch: 15 },
    // Code column
    { wch: 30 },
    // Name column - adjusted for more columns
    ...Array.from({ length: a }, () => ({ wch: 15 }))
    // UOM columns
  ], v["!margins"] = {
    left: 0.7,
    right: 0.7,
    top: 0.75,
    bottom: 0.75,
    header: 0.3,
    footer: 0.3
  };
  const c = m.name.slice(0, 31), l = ge({ [c]: v }), g = `${m.name} - Closing Template (${Be(/* @__PURE__ */ new Date())}).xlsx`;
  return ye(l, g), g;
}
function xt() {
  const m = de(), r = ve(), a = ct(), u = He({
    sku: {
      unit: {
        _id: "",
        name: "Unit",
        abbrev: "Unit",
        precision: 0,
        measurements: []
      },
      code: "ING001",
      _id: "",
      name: "Sugar"
    }
  })[0], t = m.currentBusiness.value, n = Oe(), v = [
    ["Template ID (leave empty to create new)", ""],
    ["Template Name", "New template"],
    ["Business name", t == null ? void 0 : t.name],
    ["Business ID", t == null ? void 0 : t._id],
    ["Menu version", t == null ? void 0 : t.menuVersion],
    [
      "Location codes (leave empty to enable all)",
      "Example outlet (restaurant_xxx)",
      "Example outlet 2 (restaurant_xxx)"
    ],
    ["Reference:"],
    [],
    n.map((y) => y.name),
    n.map((y) => u[y.id])
  ], b = n.map((y) => `system:${y.id}`), c = re(v, b), l = a.isEnabled ? a.state.setting.childItems ?? [] : [], g = l.reduce(
    (y, o) => {
      var M, d;
      const f = (M = a.netSuiteItemIdToSkuId.get(o.parentNetSuiteId)) == null ? void 0 : M[0], T = (d = a.netSuiteMeasurementIdToMeasurementId.get(
        o.unitOfMeasureId
      )) == null ? void 0 : d[0];
      if (!o.externalId)
        return y;
      if (!f)
        return console.error(`Item ${o.externalId} cannot be mapped to parent FdoInventorySku.`, o), y;
      const e = r.skuById[f], k = e.unit.measurements.find((s) => s.id === T);
      return k ? (y[o.externalId] = {
        sku: e,
        measurement: k
      }, y) : (console.error(
        `Item ${o.externalId} found parent FdoInventorySku of ${e.code} ${e.name} but the measurement of netsuite id ${o.unitOfMeasureId} cannot be found.`,
        o
      ), y);
    },
    {}
  ), i = re(
    [
      ...r.skus.flatMap((y) => [
        [y.code, y.name, y.unit.abbrev, !0],
        ...y.unit.measurements.map((f) => [
          "",
          "",
          f.abbrev,
          !f.abbrev.toLocaleLowerCase("en-us").includes("inactive")
        ])
      ]),
      ...Object.entries(g).map(([y, { sku: o, measurement: f }]) => [
        o.code,
        o.name,
        f.abbrev,
        !f.abbrev.toLocaleLowerCase("en-us").includes("inactive"),
        y
      ])
    ],
    [
      "Code",
      "Name",
      "Units",
      "Enabled (true/false)",
      ...l.length ? ["Netsuite Parent"] : []
    ]
  ), h = ge({
    Template: c,
    Ingredients: i
  }), w = `${t == null ? void 0 : t.name} transfer templates import.xlsx`;
  return ye(h, w), w;
}
function wt(m) {
  if (!m.length || `${m[0]}`.toLocaleLowerCase() === "all")
    return [];
  const r = /(.*) \(((warehouse_|restaurant_).{24,})\)/, u = fe().locationByDbName;
  return m.map((t) => {
    const n = new Array(), v = t.trim(), b = r.exec(v);
    if (!b)
      return n.push(`Enabled location value of ${v} cannot be read.`), {
        errors: n
      };
    const c = b[1], l = b[2], g = u[l];
    return g ? (c !== g.name && n.push(
      `Location id ${l} has non-matching name. Found ${c} but expected ${g.name}`
    ), {
      errors: n,
      location: g
    }) : (n.push(`Location (${c}) of id ${l} is not found.`), {
      errors: n
    });
  });
}
function kt(m) {
  const [
    r,
    a,
    u,
    t,
    n,
    v,
    b,
    c
  ] = Le(m);
  return {
    id: `${a[1] ?? ""}`.trim(),
    name: `${u[1] ?? ""}`.trim(),
    locations: b.slice(1).map((l) => `${l}`.trim()).filter((l) => l),
    reference: `${c[1] ?? ""}`.trim()
  };
}
function Tt(m) {
  const [
    r,
    a,
    u,
    t,
    n,
    v,
    b,
    c,
    l,
    g,
    ...i
  ] = Le(m);
  if (!r || !r.length || r.some((f) => f.length && !f.startsWith("system:")))
    throw new Error("Missing meta header. Excel file does not come from the template.");
  const h = r.map((f) => f.split(":")[1]), y = ["code", "name", "unit", "enabled"].filter((f) => !h.includes(f));
  if (y.length)
    throw new Error(
      `Missing meta headers (${y.join()}). Excel file does not come from the template.`
    );
  return i.map((f, T) => {
    const e = {};
    for (const k in h) {
      const M = h[k];
      Object.assign(e, { [M]: f[k] });
    }
    return {
      index: T,
      data: e
    };
  });
}
function $t(m) {
  return m.reduce(
    (r, a) => {
      var n;
      const u = a.data, t = a.index;
      return u.unit && (u.code ? r.result.push({ parent: a, children: [] }) : r.result.length ? (n = r.result.at(-1)) == null || n.children.push(a) : r.errors.push(`Cannot find parent for row ${t + 9}`)), r;
    },
    { result: new Array(), errors: new Array() }
  );
}
function Ct(m) {
  const r = m.parent.data, a = new Array(), t = ve().skuByCode[r.code ?? ""];
  if (!t)
    return a.push(`Cannot find ingredient of code ${r.code} ${r.name}`), { errors: a };
  const n = {
    sku: t
  }, v = /* @__PURE__ */ new Set([t.unit._id, ...t.unit.measurements.map((c) => c.id)]), b = t.unit.measurements.find((c) => c.abbrev === r.unit);
  r.unit !== t.unit.abbrev && !b ? a.push(
    `Cannot find measurement unit of ${r.unit} for (${r.code}) ${r.name}.`
  ) : (r.enabled === !0 || `${r.enabled}`.toLocaleLowerCase() === "true") && v.delete(t.unit._id);
  for (const c of m.children) {
    const l = c.data, g = l.unit === t.unit.abbrev ? t.unit : void 0, i = t.unit.measurements.find((h) => h.abbrev === l.unit);
    if (!i && !g) {
      a.push(
        `Cannot find measurement unit of ${l.unit} for (${r.code}) ${r.name}.`
      );
      continue;
    }
    (l.enabled === !0 || `${l.enabled}`.toLocaleLowerCase() === "true") && v.delete((i == null ? void 0 : i.id) ?? (g == null ? void 0 : g._id) ?? "");
  }
  return v.has(t.unit._id) && n.sku.unit.measurements.every((c) => v.has(c.id)) && a.push(`Ingredient ${t.code} - ${t.name} must have at least one unit enabled.`), n.disabledMeasurements = [...v], { errors: a, templateItem: n };
}
function It(m) {
  const r = m.SheetNames.filter(
    (n) => !Object.values(he).map(String).includes(n)
  ), u = ue().templates, t = ot(u, "_id");
  try {
    return r.reduce(
      (n, v) => {
        const b = new Array(), c = m.Sheets[v], l = kt(c), g = wt(l.locations), i = g.filter((e) => e.location).map((e) => e.location);
        b.push(...g.flatMap((e) => e.errors));
        const h = Tt(c).filter(
          (e) => e.data.code || e.data.unit
        ), w = $t(h);
        b.push(...w.errors);
        const y = w.result.map(
          (e) => Ct(e)
        );
        b.push(...y.flatMap((e) => e.errors));
        const o = y.filter((e) => e.templateItem).map((e) => e.templateItem);
        if (l.id) {
          const e = t[l.id];
          if (!e) {
            const M = {
              _id: l.id,
              _rev: "",
              name: l.name || `(unnamed from sheet ${v || "<unnamed sheet>"})`,
              items: []
            };
            return b.push(`Template ID ${l.id} is not found.`), n.importUpdateResult.push({
              type: "update",
              original: M,
              template: M,
              excelSheetName: v,
              errors: b
            }), n;
          }
          const k = {
            type: "update",
            original: e,
            template: {
              ...e,
              name: l.name,
              locations: i.length ? i : null,
              ref: l.reference,
              items: o
            },
            excelSheetName: v,
            errors: b
          };
          return n.importUpdateResult.push(k), n;
        }
        const T = {
          type: "create",
          template: {
            name: l.name,
            locations: i.length ? i : null,
            ref: l.reference,
            items: o
          },
          excelSheetName: v,
          errors: b
        };
        return n.importCreateResult.push(T), n;
      },
      {
        invalidExcel: !1,
        importCreateResult: new Array(),
        importUpdateResult: new Array()
      }
    );
  } catch (n) {
    return {
      invalidExcel: !0,
      invalidExcelMessage: (n == null ? void 0 : n.message) ?? "Invalid excel",
      importCreateResult: [],
      importUpdateResult: []
    };
  }
}
const St = { class: "flex items-center gap-12 pl-8" }, Dt = { class: "flex flex-col" }, Mt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-primary flex items-center gap-4" }, Ft = {
  key: 0,
  class: "text-fm-color-typo-secondary fm-typo-en-body-sm-400"
}, At = { key: 0 }, Re = /* @__PURE__ */ K({
  __name: "ClosingTemplateImportItem",
  props: {
    type: {},
    name: {},
    locations: {},
    items: {},
    errors: {}
  },
  setup(m) {
    const { t: r } = W();
    return (a, u) => {
      var v, b, c;
      const t = E("FmIcon"), n = E("FmTooltip");
      return $(), D("div", St, [
        u[0] || (u[0] = _("div", null, "•", -1)),
        _("div", Dt, [
          _("div", Mt, [
            _("div", {
              class: q({
                "text-fm-color-system-error-300": a.errors.length
              })
            }, [
              ae(I(a.name) + " ", 1),
              a.type === "create" ? ($(), D("span", Ft, "(" + I(p(r)("inventory.closing.template.import.new")) + ")", 1)) : O("", !0)
            ], 2),
            a.errors.length ? ($(), D("div", At, [
              C(n, { "z-index": 50 }, {
                content: V(() => [
                  _("ol", null, [
                    ($(!0), D(j, null, Z(a.errors, (l, g) => ($(), D("li", { key: g }, I(l), 1))), 128))
                  ])
                ]),
                default: V(() => [
                  C(t, {
                    name: "error",
                    size: "sm",
                    color: "system-error-300"
                  })
                ]),
                _: 1
              })
            ])) : O("", !0)
          ]),
          _("div", {
            class: q([
              "fm-typo-en-body-sm-400",
              {
                "text-fm-color-system-error-200": a.errors.length,
                "text-fm-color-typo-secondary": !a.errors.length
              }
            ])
          }, I((v = a.locations) != null && v.length ? p(r)("inventory.closing.template.import.nLocations", { count: (b = a.locations) == null ? void 0 : b.length }) : p(r)("inventory.closing.template.import.allLocations")) + ", " + I(p(r)("inventory.closing.template.import.nItems", { count: (c = a.items) == null ? void 0 : c.length })), 3)
        ])
      ]);
    };
  }
}), Rt = { class: "flex flex-col gap-24" }, Pt = { class: "fm-typo-en-body-md-400" }, Et = {
  key: 0,
  class: "flex items-center gap-8"
}, Vt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Nt = { class: "flex flex-col gap-8" }, Ut = { class: "line-clamp-2 text-ellipsis break-all" }, Lt = {
  key: 2,
  class: "shrink-0"
}, Bt = {
  key: 0,
  class: "flex flex-col"
}, zt = { class: "text-fm-color-system-error-300 fm-typo-en-body-sm-400" }, Ht = {
  key: 0,
  class: "max-h-[200px] overflow-y-auto flex flex-col gap-8"
}, Ot = { class: "fm-typo-en-body-lg-600" }, jt = /* @__PURE__ */ K({
  __name: "ClosingTemplateImport",
  setup(m) {
    const r = A(null), a = Ze(), u = ce(), t = A(!1), n = A(!1), v = A(new Array()), b = A([]), c = A([]), l = L(
      () => !!v.value.length || b.value.some((w) => w.errors.length) || c.value.some((w) => w.errors.length)
    ), g = L(
      () => !!b.value.length || !!c.value.length
    ), { t: i } = W();
    async function h(w) {
      v.value = [], b.value = [], c.value = [];
      try {
        t.value = !0;
        const [y] = await Promise.all([
          st(w),
          // fake buffer
          new Promise((e) => setTimeout(e, 1e3))
        ]);
        if (!y.SheetNames.filter(
          (e) => !Object.values(he).map(String).includes(e)
        ).find((e) => e)) {
          v.value.push(i("inventory.ingredient.import.fileError.noSheet"));
          return;
        }
        const T = It(y);
        if (T.invalidExcel) {
          v.value.push(
            T.invalidExcelMessage ?? i("inventory.ingredient.import.fileError.invalidExcel")
          );
          return;
        }
        if (b.value = T.importCreateResult, c.value = T.importUpdateResult, !b.value.length && !c.value.length) {
          v.value.push(i("inventory.ingredient.import.fileError.noData"));
          return;
        }
        a.emitData(T);
      } catch (y) {
        u.open({
          title: i("inventory.ingredient.import.fileError.unableToRead"),
          message: y == null ? void 0 : y.message,
          type: "error"
        }), console.error("Error in reading file", y);
      } finally {
        v.value.length && u.open({
          title: i("inventory.ingredient.import.fileError.invalidExcel"),
          type: "error"
        }), t.value = !1;
      }
    }
    return Pe(r, (w) => {
      w && h(w);
    }), (w, y) => {
      const o = E("FmCircularProgress"), f = E("FmIcon"), T = E("FmButton");
      return $(), D("div", Rt, [
        _("div", Pt, I(p(i)("inventory.closing.template.import.message")), 1),
        n.value ? ($(), D("div", Et, [
          _("div", null, [
            C(o, {
              size: "md",
              color: "neutral-gray-200"
            })
          ]),
          _("div", Vt, I(p(i)("inventory.formField.loading")), 1)
        ])) : ($(), D(j, { key: 1 }, [
          C(lt, {
            class: q({
              "w-full": !0,
              "h-[200px]": !r.value
            }),
            accept: ".xlsx",
            onFileUpload: y[0] || (y[0] = (e) => r.value = e),
            label: p(i)("inventory.ingredient.import.uploadTemplate"),
            "button-label": p(i)("inventory.ingredient.import.selectFile")
          }, Ee({ _: 2 }, [
            r.value ? {
              name: "default",
              fn: V(({ openFileDialog: e }) => [
                _("div", Nt, [
                  _("div", {
                    class: q([
                      "fm-corner-radius-md p-16 flex items-center gap-16",
                      {
                        "border border-fm-color-neutral-gray-100": t.value,
                        "border border-fm-color-neutral-gray-200": !t.value && !l.value,
                        "border border-fm-color-system-error-200": l.value
                      }
                    ])
                  }, [
                    t.value ? ($(), U(o, {
                      key: 0,
                      size: "md",
                      color: "neutral-gray-200"
                    })) : ($(), U(f, {
                      key: 1,
                      name: l.value ? "error" : "attach_file",
                      outline: "",
                      color: l.value ? "system-error-300" : void 0
                    }, null, 8, ["name", "color"])),
                    _("div", {
                      class: q([
                        "fm-typo-en-body-md-400 flex-1 h-[36px] flex items-center",
                        {
                          "text-fm-color-typo-disabled": t.value,
                          "text-fm-color-typo-primary": !t.value
                        }
                      ])
                    }, [
                      _("div", Ut, I(r.value.name), 1)
                    ], 2),
                    t.value ? O("", !0) : ($(), D("div", Lt, [
                      C(T, {
                        label: p(i)("inventory.ingredient.import.replaceFile"),
                        variant: l.value ? "destructive" : "secondary",
                        "prepend-icon": l.value ? void 0 : "autorenew",
                        onClick: e
                      }, null, 8, ["label", "variant", "prepend-icon", "onClick"])
                    ]))
                  ], 2),
                  v.value.length ? ($(), D("div", Bt, [
                    ($(!0), D(j, null, Z(v.value, (k, M) => ($(), D("div", {
                      key: M,
                      class: "flex gap-8 items-center"
                    }, [
                      C(f, {
                        name: "error",
                        size: "sm",
                        color: "system-error-300"
                      }),
                      _("div", zt, I(k), 1)
                    ]))), 128))
                  ])) : O("", !0)
                ])
              ]),
              key: "0"
            } : void 0
          ]), 1032, ["class", "label", "button-label"]),
          g.value ? ($(), D("div", Ht, [
            _("div", Ot, I(p(i)("inventory.ingredient.import.summary")), 1),
            ($(!0), D(j, null, Z(b.value, (e, k) => ($(), U(Re, {
              key: k,
              name: e.template.name,
              locations: e.template.locations,
              items: e.template.items,
              errors: e.errors,
              type: "create"
            }, null, 8, ["name", "locations", "items", "errors"]))), 128)),
            ($(!0), D(j, null, Z(c.value, (e) => ($(), U(Re, {
              key: e.template._id,
              name: e.template.name,
              locations: e.template.locations,
              items: e.template.items,
              errors: e.errors,
              type: "update"
            }, null, 8, ["name", "locations", "items", "errors"]))), 128))
          ])) : O("", !0)
        ], 64))
      ]);
    };
  }
}), ie = Ve("closingTemplateActions", () => {
  const { t: m } = W(), r = pe(), a = ce(), u = me(), t = mt(), n = ue(), { loading: v } = Ne(n), b = A({});
  function c() {
    b.value = {
      mode: G.CREATE,
      show: !0,
      "onUpdate:show"(e) {
        b.value.show = e;
      }
    };
  }
  function l(e) {
    b.value = {
      mode: G.UPDATE,
      modelValue: e,
      show: !0,
      "onUpdate:show"(k) {
        b.value.show = k;
      }
    };
  }
  function g(e, k, M) {
    r.open({
      title: `Confirm deleting template ${e.name}?`,
      message: "Deleted template can no longer be retrieved",
      primaryActions: {
        text: "Delete",
        variant: oe.Destructive,
        close: !0
      },
      secondaryActions: {
        text: "Cancel",
        variant: oe.Plain,
        close: !0
      }
    }).onPrimary(async () => {
      a.open({
        title: `Deleting ${e.name}`,
        type: "info"
      });
      try {
        k.value = !0;
        const [d] = await Promise.allSettled([
          u.deleteTemplate(e),
          new Promise((s) => setTimeout(s, 1e3))
        ]);
        if (d.status === "rejected") throw d.reason;
        a.open({
          title: `Deleted "${e.name}"`,
          type: "success"
        });
      } catch (d) {
        a.open({
          title: `Unable to delete "${e.name}"`,
          message: d.message,
          type: "error"
        });
      } finally {
        k.value = !1, M();
      }
    });
  }
  function i(e, k, M) {
    let d;
    r.open({
      title: `Confirm duplicating template "${e.name}"?`,
      message: "Duplicated template can be edited after creation",
      primaryActions: {
        text: "Duplicate",
        variant: oe.Destructive,
        close: !0
      },
      secondaryActions: {
        text: "Cancel",
        variant: oe.Plain,
        close: !0
      },
      contentComponent: K({
        props: ["modelValue"],
        emits: ["update:modelValue"],
        setup(s) {
          return () => P(Y.FmTextField, {
            modelValue: s.modelValue,
            "onUpdate:modelValue": (x) => d = x,
            label: "New Template Name",
            size: "md",
            variant: "primary"
          });
        }
      })
    }).onPrimary(async () => {
      a.open({
        title: `Duplicating "${e.name}"`,
        type: "info"
      });
      try {
        k.value = !0;
        const [s] = await Promise.allSettled([
          t.duplicateClosingTemplate(e._id, d),
          new Promise((x) => setTimeout(x, 1e3))
        ]);
        if (s.status === "rejected") throw s.reason;
        a.open({
          title: `Duplicated "${e.name}"`,
          type: "success"
        });
      } catch (s) {
        a.open({
          title: `Unable to duplicate "${e.name}"`,
          message: `See error from server: ${s}`,
          type: "error"
        }), console.error("error on duplicating closing template", s);
      } finally {
        k.value = !1, M();
      }
    });
  }
  const h = A({});
  function w(e) {
    h.value = {
      template: e,
      show: !0,
      "onUpdate:show"(k) {
        h.value.show = k;
      },
      "onAction:edit"() {
        h.value.show = !1, l(Ue(e));
      }
    };
  }
  function y() {
    if (!n.templates.length) {
      a.open({
        title: "No data to export",
        type: "error"
      });
      return;
    }
    const e = bt(n.templates);
    a.open({
      title: m("inventory.ingredient.export.success"),
      message: m("inventory.ingredient.export.filename", [e]),
      type: "success"
    });
  }
  function o(e) {
    if (!e.items.length) {
      a.open({
        title: "No items in template to export",
        type: "error"
      });
      return;
    }
    const k = _t(e);
    a.open({
      title: m("inventory.ingredient.export.success"),
      message: m("inventory.ingredient.export.filename", [k]),
      type: "success"
    });
  }
  function f() {
    n.loading || r.open({
      title: m("inventory.ingredient.import.title"),
      contentComponent: jt,
      overlay: !0,
      closeButton: !0,
      primaryActions: {
        text: m("common.import"),
        close: !1
      },
      secondaryActions: {
        text: m("common.close"),
        close: !0
      },
      tertiaryActions: {
        text: m("inventory.ingredient.import.actions.downloadTemplate"),
        close: !1,
        variant: "plain"
      }
    }).onPrimary((e) => {
      if (!e) {
        a.open({
          title: m("inventory.ingredient.import.error.noData"),
          type: "error"
        });
        return;
      }
      if (!e.importCreateResult.length && !e.importUpdateResult.length) {
        a.open({
          title: m("inventory.ingredient.import.error.invalidContent"),
          message: m("inventory.ingredient.import.error.noImportData"),
          type: "error"
        });
        return;
      }
      if (e.importCreateResult.some((k) => k.errors.length) || e.importUpdateResult.some((k) => k.errors.length)) {
        a.open({
          title: m("inventory.ingredient.import.error.invalidContent"),
          message: m("inventory.ingredient.import.error.hasErrors"),
          type: "error"
        });
        return;
      }
      r.close(), T(e);
    }).onTertiary(xt);
  }
  async function T(e) {
    v.value = !0;
    try {
      const k = [
        ...e.importCreateResult.map(
          (x) => x.template
        ),
        ...e.importUpdateResult.map(
          (x) => x.template
        )
      ], M = 100;
      let d = 0;
      const s = () => {
        d += M, a.open({
          title: m("inventory.ingredient.import.progress", [
            Math.min(d, k.length),
            k.length
          ])
        });
      };
      for (const x of k.chunk(100))
        s(), await u.importTemplates(x);
      a.open({
        title: m("inventory.ingredient.import.success"),
        type: "success"
      });
    } catch (k) {
      a.open({
        title: m("inventory.ingredient.import.error.failed"),
        message: m("inventory.ingredient.import.error.systemMessage", [k == null ? void 0 : k.message]),
        type: "error"
      }), console.error("Error in importing skus", e, k);
    } finally {
      v.value = !1, n.fetchTemplates();
    }
  }
  return {
    createTemplate: c,
    viewTemplate: w,
    updateTemplate: l,
    deleteTemplate: g,
    duplicateTemplate: i,
    exportTemplates: y,
    exportSingleTemplate: o,
    importTemplates: f,
    templateDialogProps: b,
    templateDetailsProps: h
  };
});
var Q = /* @__PURE__ */ ((m) => (m.Name = "Name", m.Unit = "Unit", m.Delete = "Delete", m))(Q || {});
function Yt(m) {
  return {
    columnDefs: L(() => {
      const a = m.items.map((t) => t.sku.unit.measurements.length).reduce((t, n) => Math.max(t, n), 0);
      return [
        {
          id: "Name",
          header: () => "Name",
          enableSorting: !1,
          size: 400,
          minSize: 400,
          accessorFn: (t) => `${t.sku.name} ${t.sku.code}`,
          cell(t) {
            const n = t.row.original;
            return P(
              "div",
              {
                class: "flex flex-col",
                style: { minWidth: "400px" }
              },
              [
                P(
                  "span",
                  { class: "fm-typo-en-body-lg-400 text-fm-color-typo-primary line-clamp-1" },
                  n.sku.name
                ),
                P(
                  "span",
                  { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary line-clamp-1" },
                  n.sku.code
                )
              ]
            );
          }
        },
        {
          id: "Unit",
          header: () => "Enable unit",
          enableSorting: !1,
          minSize: 200,
          maxSize: 400,
          cell(t) {
            var v, b, c;
            const n = t.row.original;
            return P("div", { class: "flex items-center gap-32" }, [
              P(
                Y.FmFormGroup,
                {
                  value: n.sku.unit._id,
                  modelValue: !((v = n.disabledMeasurements) != null && v.includes(n.sku.unit._id))
                },
                P(
                  "div",
                  {
                    class: "flex items-center gap-4",
                    style: { width: "120px" }
                  },
                  [
                    P(Y.FmCheckbox, {
                      value: n.sku.unit._id,
                      modelValue: !((b = n.disabledMeasurements) != null && b.includes(n.sku.unit._id)),
                      disabled: m.disabled || !((c = n.disabledMeasurements) != null && c.includes(n.sku.unit._id)) && n.sku.unit.measurements.every(
                        (l) => {
                          var g;
                          return (g = n.disabledMeasurements) == null ? void 0 : g.includes(l.id);
                        }
                      ),
                      "onUpdate:modelValue"(l) {
                        var g;
                        if (l)
                          m.updateItem({
                            ...n,
                            disabledMeasurements: (g = n.disabledMeasurements) == null ? void 0 : g.filter(
                              (i) => i !== n.sku.unit._id
                            )
                          });
                        else {
                          const i = n.disabledMeasurements ?? [];
                          m.updateItem({
                            ...n,
                            disabledMeasurements: [...i, n.sku.unit._id]
                          });
                        }
                      }
                    }),
                    P(
                      Y.FmTooltip,
                      { zIndex: 51 },
                      {
                        content() {
                          return n.sku.unit.abbrev;
                        },
                        default() {
                          return P(
                            "div",
                            { class: "line-clamp-2 fm-typo-en-body-lg-400" },
                            n.sku.unit.abbrev
                          );
                        }
                      }
                    )
                  ]
                )
              ),
              ...Array.from({ length: Math.max(a, 0) }).map((l, g) => {
                var w, y, o, f;
                const i = t.row.original, h = i.sku.unit.measurements[g];
                return h ? P(
                  Y.FmFormGroup,
                  {
                    modelValue: !((w = i.disabledMeasurements) != null && w.includes(h.id)),
                    value: h.id
                  },
                  P(
                    "div",
                    {
                      class: "flex items-center gap-4",
                      style: { width: "120px" }
                    },
                    [
                      P(Y.FmCheckbox, {
                        value: h.id,
                        modelValue: !((y = i.disabledMeasurements) != null && y.includes(h.id)),
                        disabled: m.disabled || !((o = i.disabledMeasurements) != null && o.includes(h.id)) && ((f = i.disabledMeasurements) == null ? void 0 : f.includes(i.sku.unit._id)) && i.sku.unit.measurements.filter((T) => T.id != h.id).every((T) => {
                          var e;
                          return (e = i.disabledMeasurements) == null ? void 0 : e.includes(T.id);
                        }),
                        "onUpdate:modelValue"(T) {
                          var e;
                          if (T)
                            m.updateItem({
                              ...i,
                              disabledMeasurements: (e = i.disabledMeasurements) == null ? void 0 : e.filter(
                                (k) => k !== h.id
                              )
                            });
                          else {
                            const k = i.disabledMeasurements ?? [];
                            m.updateItem({
                              ...i,
                              disabledMeasurements: [...k, h.id]
                            });
                          }
                        }
                      }),
                      P(
                        Y.FmTooltip,
                        { zIndex: 51 },
                        {
                          content() {
                            return h.abbrev;
                          },
                          default() {
                            return P(
                              "div",
                              { class: "line-clamp-2 fm-typo-en-body-lg-400" },
                              h.abbrev
                            );
                          }
                        }
                      )
                    ]
                  )
                ) : null;
              })
            ]);
          }
        },
        {
          id: "Delete",
          header: "",
          cell(t) {
            const n = t.row.original;
            return P(
              "div",
              { class: "w-full flex justify-end" },
              P(Y.FmButton, {
                class: "delete-button",
                key: n.sku._id,
                type: "button",
                icon: "delete",
                variant: "tertiary",
                size: "md",
                disabled: m.disabled,
                onClick: () => {
                  m.deleteItem(n);
                }
              })
            );
          },
          enableSorting: !1,
          size: 40,
          meta: {
            cellClass: "",
            headerClass: ""
          }
        }
      ];
    })
  };
}
const Gt = { class: "flex flex-col gap-16 py-12" }, Kt = { class: "flex" }, Wt = { class: "flex-1 flex flex-col" }, qt = { class: "fm-typo-en-title-sm-600 text-fm-color-typo-primary" }, Jt = { class: "fm-typo-en-body-lg-400 text-fm-color-typo-secondary" }, Xt = { class: "flex flex-col gap-4" }, Qt = /* @__PURE__ */ K({
  __name: "ClosingTemplateItem",
  props: {
    cellByColId: {},
    row: {}
  },
  setup(m) {
    const r = m, a = L(() => r.row), u = L(
      () => a.value.getVisibleCells().filter((t) => t.column.id !== Q.Name && t.column.id !== Q.Delete)
    );
    return (t, n) => {
      var v, b, c, l, g;
      return $(), D("div", Gt, [
        _("div", Kt, [
          _("div", Wt, [
            _("div", qt, I(a.value.original.sku.name), 1),
            _("div", Jt, I(a.value.original.sku.code), 1)
          ]),
          _("div", null, [
            C(p(X), {
              render: (c = (b = (v = t.cellByColId[p(Q).Delete]) == null ? void 0 : v.column) == null ? void 0 : b.columnDef) == null ? void 0 : c.cell,
              props: (g = (l = t.cellByColId[p(Q).Delete]) == null ? void 0 : l.getContext) == null ? void 0 : g.call(l)
            }, null, 8, ["render", "props"])
          ])
        ]),
        _("div", Xt, [
          n[0] || (n[0] = _("div", { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, null, -1)),
          ($(!0), D(j, null, Z(u.value, (i) => {
            var h, w, y;
            return $(), D("div", {
              key: i.id
            }, [
              C(p(X), {
                render: (w = (h = i.column) == null ? void 0 : h.columnDef) == null ? void 0 : w.cell,
                props: (y = i.getContext) == null ? void 0 : y.call(i)
              }, null, 8, ["render", "props"])
            ]);
          }), 128))
        ])
      ]);
    };
  }
}), Zt = { class: "flex flex-col gap-16" }, en = { class: "flex flex-col gap-24" }, tn = { class: "flex flex-col gap-16" }, nn = { class: "flex items-center" }, on = { class: "flex-1 fm-typo-en-title-sm-600" }, sn = { class: "flex flex-col gap-16" }, ln = { class: "flex items-center" }, an = { class: "flex-1 gap-8 fm-typo-en-title-sm-600" }, rn = { class: "flex gap-8" }, cn = { key: 0 }, mn = /* @__PURE__ */ K({
  __name: "ClosingTemplateForm",
  props: {
    modelValue: {},
    disabled: { type: Boolean }
  },
  setup(m, { expose: r }) {
    const a = m, u = vt(), { t } = W(), n = ve(), {
      promptSelectLocations: v,
      columnDefs: b,
      rowData: c
    } = gt({
      getLocations() {
        return u.locations;
      },
      setLocations(d) {
        u.locations = d;
      }
    }), l = A(), g = A(""), i = A(null), h = A(!1), w = [
      {
        key: "name",
        label: "Name",
        getter: (d) => {
          var s;
          return (s = d.sku) == null ? void 0 : s.name;
        }
      },
      {
        key: "code",
        label: "Code",
        getter: (d) => {
          var s;
          return (s = d.sku) == null ? void 0 : s.code;
        }
      }
    ], y = A([]), o = L(() => u.items.map((d, s) => ({ item: d, originalIndex: s })).sort((d, s) => {
      const x = d.item.position ?? d.originalIndex, F = s.item.position ?? s.originalIndex;
      return x - F;
    }).map(({ item: d }) => d));
    function f() {
      h.value ? u.items = y.value.map(({ id: d, label: s, ...x }, F) => ({
        ...x,
        position: F
      })) : y.value = o.value.map((d) => ({
        ...d,
        id: d.sku._id,
        label: `${d.sku.code} ${d.sku.name}`
      })), h.value = !h.value;
    }
    r({
      validateInputs: () => {
        var d, s;
        (s = (d = l.value) == null ? void 0 : d.validateInputs) == null || s.call(d);
      },
      resetInputsValidation: () => {
        var d, s;
        (s = (d = l.value) == null ? void 0 : d.resetInputsValidation) == null || s.call(d);
      },
      resetInputs: () => {
        var d, s;
        (s = (d = l.value) == null ? void 0 : d.resetInputs) == null || s.call(d);
      }
    });
    const T = Yt({
      updateItem: (d) => {
        u.items = u.items.map((s) => s.sku._id !== d.sku._id ? s : d);
      },
      deleteItem: (d) => {
        u.items = u.items.filter((s) => s.sku._id !== d.sku._id);
      },
      get items() {
        return o.value;
      },
      get disabled() {
        return a.disabled;
      }
    }), e = L(() => T.columnDefs.value), { promptSelectIngredients: k } = ft();
    async function M() {
      const s = n.skus.map((S) => ({
        label: S.name,
        sublabel: S.code,
        value: S
      })).filter((S) => {
        var N;
        return (N = u.items) == null ? void 0 : N.find((H) => H.sku._id === S.value._id);
      }).map((S) => S.value), x = u.items ?? [], F = await k(
        s.map((S) => S._id),
        (S) => {
          const N = n.skuById[S], H = x.find((R) => R.sku._id === N._id);
          return H || {
            sku: N
          };
        }
      );
      F && (F.sort((S, N) => S.sku.code.localeCompare(N.sku.code)), u.items = F);
    }
    return (d, s) => {
      const x = E("FmTextField"), F = E("FmButton"), S = E("FmTable"), N = E("FmIcon"), H = E("FmFormGroup"), B = E("FmForm");
      return $(), U(B, {
        ref_key: "formRef",
        ref: l,
        class: "flex flex-col gap-32",
        disabled: d.disabled
      }, {
        default: V(() => [
          _("div", Zt, [
            _("div", en, [
              C(x, {
                label: p(t)("inventory.closing.form.name"),
                "label-mark": "required",
                modelValue: p(u).name,
                "onUpdate:modelValue": s[0] || (s[0] = (R) => p(u).name = R),
                rules: [p(dt)()]
              }, null, 8, ["label", "modelValue", "rules"]),
              C(x, {
                label: p(t)("inventory.closing.form.reference"),
                "label-mark": "optional",
                modelValue: p(u).ref,
                "onUpdate:modelValue": s[1] || (s[1] = (R) => p(u).ref = R)
              }, null, 8, ["label", "modelValue"])
            ])
          ]),
          _("div", tn, [
            _("div", nn, [
              _("div", on, I(p(t)("inventory.closing.form.locations")), 1),
              C(F, {
                disabled: d.disabled,
                label: p(t)("inventory.closing.form.selectLocation"),
                "prepend-icon": "add",
                variant: "plain",
                class: "border-2 rounded-lg border-fm-color-primary",
                onClick: p(v)
              }, null, 8, ["disabled", "label", "onClick"])
            ]),
            C(S, {
              "column-defs": p(b),
              "row-data": p(c),
              "shrink-at": 9999,
              onRowClick: p(v),
              "hide-footer": ""
            }, null, 8, ["column-defs", "row-data", "onRowClick"])
          ]),
          _("div", sn, [
            _("div", ln, [
              _("div", an, I(p(t)("inventory.closing.form.items.title")), 1),
              _("div", rn, [
                p(u).items.length > 0 ? ($(), U(F, {
                  key: 0,
                  disabled: d.disabled,
                  label: h.value ? p(t)("inventory.common.done") : p(t)("inventory.common.rearrange"),
                  "prepend-icon": h.value ? "check" : "swap_vert",
                  variant: h.value ? "primary" : "secondary",
                  class: q(["border-2 rounded-lg", h.value ? "" : "border-fm-color-secondary"]),
                  onClick: f,
                  size: "md"
                }, null, 8, ["disabled", "label", "prepend-icon", "variant", "class"])) : O("", !0),
                h.value ? O("", !0) : ($(), U(F, {
                  key: 1,
                  disabled: d.disabled,
                  label: p(t)("inventory.closing.form.items.addItem"),
                  "prepend-icon": "add",
                  variant: "plain",
                  class: "border-2 rounded-lg border-fm-color-primary",
                  onClick: s[2] || (s[2] = (R) => M()),
                  size: "md"
                }, null, 8, ["disabled", "label"]))
              ])
            ]),
            h.value ? ($(), D("div", cn, [
              C(p(et), {
                modelValue: y.value,
                "onUpdate:modelValue": s[3] || (s[3] = (R) => y.value = R),
                "sort-fields": w,
                "left-column-label": p(t)("inventory.closing.form.items.availableItems"),
                "right-column-label": p(t)("inventory.closing.form.items.organizedGroups"),
                height: "600px"
              }, null, 8, ["modelValue", "left-column-label", "right-column-label"])
            ])) : ($(), D(j, { key: 1 }, [
              C(x, {
                placeholder: p(t)("inventory.formField.filterItems"),
                modelValue: g.value,
                "onUpdate:modelValue": s[5] || (s[5] = (R) => g.value = R)
              }, Ee({ _: 2 }, [
                g.value ? {
                  name: "append",
                  fn: V(() => [
                    C(N, {
                      name: "close",
                      onClick: s[4] || (s[4] = (R) => g.value = ""),
                      class: "cursor-pointer"
                    })
                  ]),
                  key: "0"
                } : void 0
              ]), 1032, ["placeholder", "modelValue"]),
              _("div", {
                ref_key: "itemsTableRef",
                ref: i
              }, [
                ($(), U(S, {
                  "search-value": g.value,
                  "column-defs": e.value,
                  "row-data": o.value,
                  key: o.value.map((R) => R.sku._id).join("."),
                  "hide-footer": o.value.length <= 10,
                  "page-size": Math.min(10, o.value.length)
                }, {
                  "list-row": V((R) => [
                    ($(), U(ze, {
                      row: R,
                      key: o.value.map((J) => J.sku._id).join(".")
                    }, {
                      default: V((J) => [
                        C(Qt, {
                          row: R,
                          "cell-by-col-id": J
                        }, null, 8, ["row", "cell-by-col-id"])
                      ]),
                      _: 2
                    }, 1032, ["row"]))
                  ]),
                  _: 1
                }, 8, ["search-value", "column-defs", "row-data", "hide-footer", "page-size"]))
              ], 512)
            ], 64)),
            C(H, {
              "model-value": p(u).items.length,
              rules: [p(pt)(1)]
            }, null, 8, ["model-value", "rules"])
          ])
        ]),
        _: 1
      }, 8, ["disabled"]);
    };
  }
}), un = { class: "flex items-center" }, dn = { class: "fm-typo-en-title-md-600" }, pn = { class: "flex justify-between" }, fn = { class: "fm-typo-en-body-lg-600" }, vn = { class: "flex flex-col gap-8" }, gn = { class: "flex flex-col gap-4" }, yn = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, hn = { class: "flex items-center gap-8" }, bn = { class: "fm-typo-en-body-lg-600" }, _n = { class: "flex gap-4" }, xn = /* @__PURE__ */ K({
  __name: "ClosingTemplateDialog",
  props: {
    mode: {},
    modelValue: {},
    show: { type: Boolean }
  },
  emits: ["update:show", "submitted"],
  setup(m, { expose: r, emit: a }) {
    var d;
    const u = m, t = a, n = me(), v = ie(), b = ce(), { t: c } = W(), l = tt(u, "show");
    function g() {
      return {
        _id: "",
        name: "",
        items: []
      };
    }
    const i = A(u.modelValue ?? g()), h = A(((d = u.modelValue) == null ? void 0 : d._id) ?? `${Math.random()}`);
    Pe(
      () => u.show,
      (s) => {
        var x;
        s && (i.value = u.modelValue ?? g(), h.value = ((x = u.modelValue) == null ? void 0 : x._id) ?? `${Math.random()}`);
      }
    );
    const w = A(!1), y = L(() => {
      switch (u.mode) {
        case G.READ:
          return "";
        case G.CREATE:
          return c("inventory.closing.template.create.title");
        case G.UPDATE:
          return c("inventory.closing.template.update.title");
      }
      return "";
    }), o = A();
    r({
      validateInputs: () => {
        var s, x;
        (x = (s = o.value) == null ? void 0 : s.validateInputs) == null || x.call(s);
      },
      resetInputsValidation: () => {
        var s, x;
        (x = (s = o.value) == null ? void 0 : s.resetInputsValidation) == null || x.call(s);
      },
      resetInputs: () => {
        var s, x;
        (x = (s = o.value) == null ? void 0 : s.resetInputs) == null || x.call(s);
      }
    });
    async function f() {
      const s = i.value;
      if (s) {
        w.value = !0;
        try {
          await n.createTemplate(s), await new Promise((x) => setTimeout(x, 1e3)), b.open({
            title: c("inventory.closing.template.create.success"),
            message: c("inventory.closing.template.create.successMessage"),
            type: "success"
          }), t("update:show", !1), t("submitted");
        } catch (x) {
          b.open({
            title: c("inventory.closing.template.create.error"),
            message: c("inventory.closing.template.create.errorMessage"),
            type: "error"
          }), console.error("Error in creating closing template", x);
        } finally {
          w.value = !1;
        }
      }
    }
    async function T() {
      const s = i.value;
      if (s) {
        w.value = !0, delete s.updatedAt;
        try {
          await n.updateTemplate({
            ...s,
            _rev: s._rev ?? ""
          }), await new Promise((x) => setTimeout(x, 1e3)), b.open({
            title: c("inventory.closing.template.update.success"),
            message: c("inventory.closing.template.update.successMessage"),
            type: "success"
          }), t("update:show", !1), t("submitted");
        } catch (x) {
          b.open({
            title: c("inventory.closing.template.update.error"),
            message: c("inventory.closing.template.update.errorMessage"),
            type: "error"
          }), console.error("Error in updating closing template", x);
        } finally {
          w.value = !1;
        }
      }
    }
    function e() {
      switch (u.mode) {
        case G.CREATE:
          return f();
        case G.UPDATE:
          return T();
      }
    }
    function k() {
      var s, x;
      (x = (s = o.value) == null ? void 0 : s.validateInputs) == null || x.call(s);
    }
    function M() {
      i.value && v.exportSingleTemplate(i.value);
    }
    return (s, x) => {
      const F = E("FmMenuDivider"), S = E("FmCard"), N = E("FmButton"), H = E("FmSideSheet");
      return $(), U(H, {
        modelValue: p(l),
        "onUpdate:modelValue": x[2] || (x[2] = (B) => Ye(l) ? l.value = B : null),
        "dismiss-away": "",
        "close-button": "",
        "max-width": 9999
      }, {
        "side-sheet-header": V(() => [
          _("div", un, [
            _("div", dn, I(y.value), 1)
          ])
        ]),
        default: V(() => [
          i.value.updatedAt ? ($(), U(S, {
            key: 0,
            variant: "outlined",
            class: "flex flex-col gap-8 px-12 py-16 mb-16"
          }, {
            default: V(() => {
              var B;
              return [
                _("div", pn, [
                  _("div", fn, I(p(c)("inventory.transfer.template.details.templateSummary")), 1)
                ]),
                C(F),
                _("div", vn, [
                  _("div", gn, [
                    _("div", yn, I(p(c)("inventory.transfer.receiveRequest.details.updatedAt")), 1),
                    _("div", hn, [
                      _("div", bn, [
                        ae(I(p(le)(i.value.updatedAt)) + " ", 1),
                        (B = i.value.updatedBy) != null && B.name ? ($(), D(j, { key: 0 }, [
                          ae(" (" + I(i.value.updatedBy.name) + ") ", 1)
                        ], 64)) : O("", !0)
                      ]),
                      C(yt, {
                        "closing-id": i.value._id
                      }, null, 8, ["closing-id"])
                    ])
                  ])
                ])
              ];
            }),
            _: 1
          })) : O("", !0),
          ($(), U(mn, {
            class: "w-full",
            ref_key: "formRef",
            ref: o,
            onValidationSuccess: e,
            "model-value": i.value,
            "onUpdate:modelValue": x[0] || (x[0] = (B) => i.value = B),
            disabled: w.value,
            key: h.value
          }, null, 8, ["model-value", "disabled"]))
        ]),
        "side-sheet-footer": V(() => [
          _("div", _n, [
            C(N, {
              loading: w.value,
              label: p(c)("common.save"),
              onClick: k
            }, null, 8, ["loading", "label"]),
            s.mode === p(G).UPDATE ? ($(), U(N, {
              key: 0,
              disabled: w.value,
              variant: "secondary",
              label: p(c)("inventory.common.export"),
              "prepend-icon": "download",
              onClick: M
            }, null, 8, ["disabled", "label"])) : O("", !0),
            C(N, {
              disabled: w.value,
              variant: "tertiary",
              label: p(c)("common.close"),
              onClick: x[1] || (x[1] = (B) => t("update:show", !1))
            }, null, 8, ["disabled", "label"])
          ])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), wn = {};
function kn(m, r) {
  return $(), D("div");
}
const Tn = /* @__PURE__ */ ht(wn, [["render", kn]]), $n = { class: "flex flex-col gap-40" }, Cn = { key: 0 }, In = {
  key: 1,
  class: "flex gap-8 items-center"
}, Sn = { class: "fm-typo-en-body-lg-400 text-fm-color-typo-primary" }, Dn = {
  key: 2,
  class: "fm-typo-en-body-lg-400 text-fm-color-typo-primary"
}, Mn = {
  key: 3,
  class: "fm-typo-en-body-lg-400 text-fm-color-typo-primary flex flex-col gap-12"
}, Fn = { class: "fm-typo-en-body-md-600" }, An = { class: "fm-typo-en-body-md-600" }, Rn = { key: 4 }, Pn = { class: "fm-typo-en-body-md-600" }, En = { class: "fm-typo-en-body-md-600" }, Vn = { class: "flex sm:flex-col xs:flex-col justify-end gap-8 w-full mb-16" }, Nn = /* @__PURE__ */ K({
  __name: "ClosingTemplatePublish",
  emits: ["close"],
  setup(m, { emit: r }) {
    const a = A(!1), u = ce(), t = me(), n = ue(), { t: v } = W(), b = r;
    async function c() {
      a.value = !0;
      try {
        await t.startNewPublish().delayed(1e3), u.open({
          title: "Success",
          message: "You may refresh after a while to review publish status",
          type: "success"
        }), i();
      } catch (h) {
        u.open({
          title: "Something went wrong",
          message: "Please try again",
          type: "error"
        }), console.error("error on creating publish task", h);
      } finally {
        a.value = !1;
      }
    }
    const l = L(() => n.recentPublish.recentJob), g = L(
      () => n.templates.length && (!l.value || l.value.outlets.length === l.value.completed.length)
    );
    function i() {
      b("close");
    }
    return (h, w) => {
      const y = E("FmCircularProgress"), o = E("i18n-t"), f = E("FmButton");
      return $(), D("div", $n, [
        p(n).templates.length ? a.value ? ($(), D("div", In, [
          _("div", null, [
            C(y, {
              size: "md",
              color: "neutral-gray-300"
            })
          ]),
          _("div", Sn, [
            _("span", null, I(p(v)("inventory.closing.template.publish.publishing")), 1)
          ])
        ])) : l.value ? l.value.outlets.length === l.value.completed.length ? ($(), D("div", Mn, [
          C(o, {
            keypath: "inventory.closing.template.publish.recentlyPublishedAt",
            tag: "p"
          }, {
            started: V(() => [
              _("span", Fn, I(p(le)(new Date(l.value.createdAt))), 1)
            ]),
            finished: V(() => [
              _("span", An, I(p(le)(new Date(l.value.updatedAt))), 1)
            ]),
            _: 1
          }),
          _("p", null, I(p(v)("inventory.closing.template.publish.message")), 1)
        ])) : ($(), D("div", Rn, [
          C(o, {
            keypath: "inventory.closing.template.publish.stillPublishing",
            tag: "p"
          }, {
            started: V(() => [
              _("span", Pn, I(p(le)(new Date(l.value.createdAt))), 1)
            ]),
            progress: V(() => [
              _("span", En, " (" + I(l.value.completed.length) + "/" + I(l.value.outlets.length) + " completed) ", 1)
            ]),
            _: 1
          }),
          ae(" Your recent publishing task is still pending (" + I(l.value.completed.length) + " / " + I(l.value.outlets.length) + "). Please wait until all publishing task has completed. ", 1)
        ])) : ($(), D("div", Dn, [
          _("p", null, I(p(v)("inventory.closing.template.publish.noRecentActivity")), 1),
          _("p", null, I(p(v)("inventory.closing.template.publish.message")), 1)
        ])) : ($(), D("div", Cn, [
          _("p", null, I(p(v)("inventory.closing.template.publish.nothingToPublish")), 1)
        ])),
        _("div", Vn, [
          C(f, {
            disabled: !g.value,
            loading: a.value,
            label: "Publish to all outlets",
            onClick: c
          }, null, 8, ["disabled", "loading"]),
          C(f, {
            variant: "tertiary",
            label: "Close",
            onClick: i
          })
        ])
      ]);
    };
  }
}), Un = { class: "flex-1 flex flex-col gap-8" }, Ln = { class: "flex flex-col" }, Bn = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, zn = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary" }, Hn = { class: "fm-typo-en-body-lg-400 text-fm-color-typo-secondary line-clamp-2" }, On = { class: "fm-typo-en-body-lg-400 line-clamp-2" }, go = /* @__PURE__ */ K({
  __name: "ClosingTemplateView",
  setup(m) {
    const { t: r } = W(), { createTemplate: a, updateTemplate: u, exportTemplates: t, importTemplates: n } = ie(), { templateDialogProps: v, templateDetailsProps: b } = Ne(ie()), c = fe(), l = pe(), g = ue(), i = Xe(), { breakpoints: h } = nt();
    c.watchLocation(g.fetchTemplates);
    const w = L(() => g.loading), y = A(""), o = L(() => h.value.xs || h.value.sm), f = L(() => o.value ? 10 : 20);
    function T(d) {
      switch (d) {
        case z.Add:
          return a();
        case "publish":
          return e();
        case "import":
          return n();
        case "export":
          return t();
        case "refresh":
          return g.fetchTemplates();
      }
    }
    function e() {
      l.open({
        title: "Publish closing templates",
        contentComponent: Nn,
        contentComponentProps: {
          onClose() {
            l.close();
          }
        }
      });
    }
    function k(d) {
      return d;
    }
    const M = L(() => o.value ? [
      {
        label: r("inventory.closing.template.create.title"),
        value: z.Add,
        isPrimary: !0,
        prependIcon: "add"
      },
      {
        label: r("inventory.common.refresh"),
        value: "refresh",
        isPrimary: !1
      },
      {
        label: r("inventory.common.publish"),
        value: "publish",
        isPrimary: !1
      },
      {
        label: r("inventory.common.import"),
        value: "import",
        isPrimary: !1
      },
      {
        label: r("inventory.common.export"),
        value: "export",
        isPrimary: !1
      }
    ] : [
      {
        label: r("inventory.closing.template.create.title"),
        value: z.Add,
        isPrimary: !0,
        prependIcon: "add"
      },
      {
        label: r("inventory.common.publish"),
        value: "publish",
        isPrimary: !1
      },
      {
        label: r("inventory.common.import"),
        value: "import",
        isPrimary: !1
      },
      {
        label: r("inventory.common.refresh"),
        value: "refresh",
        isPrimary: !1
      },
      {
        label: r("inventory.common.export"),
        value: "export",
        isPrimary: !1
      }
    ]);
    return (d, s) => {
      const x = E("FmTable");
      return $(), D(j, null, [
        C(Qe, {
          title: p(r)("inventory.closing.template.title"),
          actions: M.value,
          "onClick:action": T
        }, {
          default: V(() => [
            _("div", {
              class: q([
                "flex flex-col gap-8 max-h-full",
                {
                  "p-0": o.value,
                  "px-24 ": !o.value
                }
              ])
            }, [
              C(ut, {
                searchable: "",
                search: y.value,
                "onUpdate:search": s[0] || (s[0] = (F) => y.value = F)
              }, null, 8, ["search"]),
              C(x, {
                style: Ge(p(i).tableHeight),
                "column-defs": p(g).columnDefs,
                "row-data": p(g).templates,
                "search-value": y.value,
                loading: w.value,
                onRowClick: s[1] || (s[1] = (F) => p(u)(F.original)),
                "page-size": f.value
              }, {
                "list-row": V((F) => [
                  C(ze, {
                    row: F,
                    onRowClick: (S) => p(u)(S)
                  }, {
                    default: V((S) => {
                      var N, H, B, R, J, be, _e, xe, ee, we, ke, Te, $e, Ce, Ie, te, Se, De, Me, Fe, ne, Ae;
                      return [
                        _("div", Un, [
                          _("div", Ln, [
                            _("div", Bn, [
                              C(p(X), {
                                render: (B = (H = (N = S._id) == null ? void 0 : N.column) == null ? void 0 : H.columnDef) == null ? void 0 : B.cell,
                                props: (J = (R = S._id) == null ? void 0 : R.getContext) == null ? void 0 : J.call(R)
                              }, null, 8, ["render", "props"])
                            ]),
                            _("div", zn, [
                              C(p(X), {
                                render: (xe = (_e = (be = S.name) == null ? void 0 : be.column) == null ? void 0 : _e.columnDef) == null ? void 0 : xe.cell,
                                props: (we = (ee = S.name) == null ? void 0 : ee.getContext) == null ? void 0 : we.call(ee)
                              }, null, 8, ["render", "props"])
                            ]),
                            _("div", null, I((ke = F.original.locations) != null && ke.length ? p(r)("inventory.closing.table.enabledForN", {
                              count: ((Te = F.original.locations) == null ? void 0 : Te.length) ?? 0
                            }) : p(r)("inventory.closing.table.enabledForAll")), 1),
                            _("div", Hn, I([
                              ...F.original.items.slice(0, 3).map((je) => je.sku.name),
                              ...F.original.items.length >= 3 ? [`and ${F.original.items.length - 3} more items`] : []
                            ].join(", ")), 1),
                            _("div", On, [
                              C(p(X), {
                                render: (Ie = (Ce = ($e = S.ref) == null ? void 0 : $e.column) == null ? void 0 : Ce.columnDef) == null ? void 0 : Ie.cell,
                                props: (Se = (te = S.ref) == null ? void 0 : te.getContext) == null ? void 0 : Se.call(te)
                              }, null, 8, ["render", "props"])
                            ])
                          ]),
                          _("div", null, [
                            C(p(X), {
                              render: (Fe = (Me = (De = S.status) == null ? void 0 : De.column) == null ? void 0 : Me.columnDef) == null ? void 0 : Fe.cell,
                              props: (Ae = (ne = S.status) == null ? void 0 : ne.getContext) == null ? void 0 : Ae.call(ne)
                            }, null, 8, ["render", "props"])
                          ])
                        ])
                      ];
                    }),
                    _: 2
                  }, 1032, ["row", "onRowClick"])
                ]),
                _: 1
              }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"])
            ], 2)
          ]),
          _: 1
        }, 8, ["title", "actions"]),
        ($(), U(Ke, { to: "body" }, [
          C(Tn, We(qe(p(b))), null, 16),
          C(xn, Je(p(v), {
            onSubmitted: s[2] || (s[2] = (F) => p(g).fetchTemplates())
          }), null, 16)
        ]))
      ], 64);
    };
  }
});
export {
  go as default
};
