import { components as X, useDialogChild as Ae, useSnackbar as ye, useDialog as De, FmButtonVariant as j } from "@feedmepos/ui-library";
import { defineStore as he } from "pinia";
import { F as le } from "./form-mode.enum-BKiNVH6A.js";
import { u as ve } from "./purchase-order-template-BBNXnta7.js";
import { ref as E, h as K, defineComponent as te, resolveComponent as U, openBlock as _, createElementBlock as k, createElementVNode as C, normalizeClass as V, createTextVNode as Ne, toDisplayString as N, unref as O, createCommentVNode as q, createVNode as P, withCtx as ee, Fragment as L, renderList as W, onMounted as Re, computed as me, watch as Fe, createSlots as Pe, createBlock as z } from "vue";
import { a as H, c as re, r as A, u as Z, l as Me, j as ce, s as Le, R as ue } from "./app-Bpb4394e.js";
import { useRouter as Be } from "vue-router";
import { a as Qe } from "./FmMultiselectDialog-D-38fV59.js";
import { D as Y, R as D } from "./row-action.enum-DQ9bJ_uv.js";
import { c as Ue } from "./component-kqxARxvM.js";
import { f as Ve } from "./format-time-from-id-BvLCC6cK.js";
import { useI18n as ne, useCoreStore as ge } from "@feedmepos/mf-common";
import { t as B, a as be, d as xe, s as Te, r as qe } from "./xlsx.util-BPV2vsSD.js";
import { F as He } from "./FmDroppableField-J0xUsOTV.js";
import { c as je, a as Q, t as G, g as J } from "./number-BVg7EKPV.js";
import { f as ze } from "./date2-DpnYOzUg.js";
import { u as oe } from "./supplier-Bu6V24R6.js";
import { a as Ye, B as Ke } from "./rules-CoimOM7X.js";
import { u as ae } from "./netsuite-BGUUAOqe.js";
import { u as We } from "./duplicate-template-ct64aRN_.js";
function Se(t) {
  const e = H(), a = t.sku, u = e.skuById[a._id];
  if (u.unit._id !== a.unit._id) return !0;
  const i = t.measurement;
  return i ? !e.unitById[u.unit._id].measurements.find((l) => l.id === i.id) : !1;
}
function de(t) {
  const { skuById: e } = H(), a = re(t);
  return a.purchaseOrder.items = t.purchaseOrder.items.filter((u) => e[u.sku._id]), a;
}
const _e = he(
  "transferTemplateTable",
  function() {
    const { t: e } = ne(), a = _t(), u = E(!1), i = E(new Array()), s = ve(), f = H();
    async function l() {
      i.value = [], u.value = !0;
      try {
        f.isInventoryLoaded || await f.readInventory();
        const [d] = await Promise.all([s.readTemplates()]).delayed(
          1e3
        );
        i.value = d.map(de);
      } catch (d) {
        console.log("Something went wrong when fetching templates:", d);
      } finally {
        u.value = !1;
      }
    }
    async function o(d) {
      if (!i.value.find((c) => c._id)) {
        u.value = !0;
        try {
          i.value = [
            await s.getTemplate(d).then(de).delayed(1e3)
          ];
        } catch (c) {
          console.log("Something went wrong when fetching templates:", c);
        } finally {
          u.value = !1;
        }
      }
    }
    function m(d, c) {
      switch (c = re(c), d) {
        case D.Details:
          return a.viewTemplate(c);
        case D.Edit:
          return a.updateTemplate(c);
        case D.Delete:
          return a.deleteTemplate(c, u, l);
        case D.Duplicate:
          return a.duplicateTemplate(c, u, l);
      }
    }
    return {
      columnDefs: [
        {
          id: "_id",
          accessorKey: "_id",
          header: () => e("inventory.transfer.table.createdAt"),
          cell(d) {
            return Ve(`${d.getValue()}`);
          },
          enableSorting: !0
        },
        {
          id: "name",
          accessorKey: "name",
          header: () => e("inventory.transfer.table.name"),
          enableSorting: !0,
          size: 200
        },
        {
          id: "supplier",
          accessorKey: "purchaseOrder.supplier.name",
          header: () => e("inventory.transfer.table.from"),
          enableSorting: !0,
          size: 200
        },
        {
          id: "noOfItems",
          accessorKey: "purchaseOrder.items.length",
          header: () => e("inventory.transfer.table.noOfItems"),
          enableSorting: !1,
          meta: {
            width: "10rem",
            textAlign: "right"
          },
          cell(d) {
            const c = Number(d.getValue()) || 0, v = d.row.original.purchaseOrder.items.some(Se);
            return c === 0 || v ? K("div", { class: "flex justify-end gap-4 items-center" }, [
              K(
                X.FmTooltip,
                {},
                {
                  content() {
                    return v ? "The template is invalid due to invalid unit on some of the items. Please update this template." : "The template is invalid due to deleted ingredients. Please update this template.";
                  },
                  default() {
                    return K(X.FmIcon, {
                      name: "error",
                      color: "system-error-300",
                      size: "sm"
                    });
                  }
                }
              ),
              c
            ]) : c;
          }
        },
        {
          id: "enabledLocations",
          accessorKey: "purchaseOrder.locations.length",
          header: () => "Enabled outlets",
          cell(d) {
            var v;
            const c = (v = d.row.original.locations) == null ? void 0 : v.length;
            return c ? `${c}` : "All";
          },
          enableSorting: !1,
          meta: {
            width: "10rem",
            textAlign: "right"
          }
        },
        {
          id: "ref",
          accessorKey: "purchaseOrder.ref",
          header: () => e("inventory.transfer.table.reference"),
          enableSorting: !1,
          size: "auto"
        },
        {
          id: "action",
          cell(d) {
            const c = d.row.original, v = [
              Y[D.Details],
              Y[D.Edit],
              Y[D.Duplicate],
              Y[D.Delete]
            ];
            return Ue(v, (b) => m(b, c));
          },
          enableSorting: !1,
          size: 40,
          meta: {
            cellClass: "",
            headerClass: ""
          }
        }
      ],
      templates: i,
      loading: u,
      fetchTemplates: l,
      loadTemplate: o
    };
  }
);
var se = /* @__PURE__ */ ((t) => (t.Source = "Source", t.Destination = "Destination", t.Ingredient = "Ingredient", t))(se || {});
const pe = je(0);
function we(t) {
  var u;
  const e = t.sku;
  return {
    code: e.code,
    overrideCode: t.code,
    name: e.name,
    unit: ((u = e.unit.measurements.find((i) => i.id === e.trackingMeasurement)) == null ? void 0 : u.abbrev) ?? e.unit.abbrev,
    defaultQuantity: +Q(t.quantity),
    minimumQuantity: +Q(t.minimumQuantity ?? pe),
    maximumQuantity: +Q(t.maximumQuantity ?? pe),
    quantityStep: +Q(t.quantityStep)
  };
}
function $e() {
  return [
    {
      id: "code",
      name: "Code"
    },
    {
      id: "overrideCode",
      name: "Override Code (Optional)"
    },
    {
      id: "name",
      name: "Name"
    },
    {
      id: "unit",
      name: "Unit"
    },
    {
      id: "defaultQuantity",
      name: "Default Quantity"
    },
    {
      id: "minimumQuantity",
      name: "Minimum Quantity"
    },
    {
      id: "maximumQuantity",
      name: "Maximum Quantity (Optional)"
    },
    {
      id: "quantityStep",
      name: "Quantity Step"
    }
  ];
}
function Ge(t) {
  var l;
  const a = ge().currentBusiness.value, i = (l = t.map((o) => {
    var b;
    const m = o.purchaseOrder.items.map((r) => we(r)), h = $e(), d = [
      ["Template ID", o._id],
      ["Template name", o.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],
      [
        "Purchase/Transfer",
        typeof o.purchaseOrder.supplier.internal == "string" ? A.enum.transfer : A.enum.purchase
      ],
      [
        "Transfer from",
        `${o.purchaseOrder.supplier.name} (${[
          o.purchaseOrder.supplier.internal,
          o.purchaseOrder.supplier._id
        ].filter((r) => r).join("_")})`
      ],
      [
        "Locations",
        ...(b = o.locations) != null && b.length ? o.locations.map((r) => `${r.name} (${r.dbName})`) : ["All"]
      ],
      ["Reference", o.purchaseOrder.ref ?? ""],
      ["Remark", o.purchaseOrder.remark ?? ""],
      [],
      h.map((r) => r.name),
      ...m.map((r) => h.map((x) => r[x.id]))
    ], c = h.map((r) => `system:${r.id}`), v = B(d, c);
    return { name: o.name, sheet: v };
  }).reduce(
    (o, m) => {
      var d;
      const h = m.name.slice(0, 12);
      return (d = o.sheetOccurence)[h] ?? (d[h] = 0), o.sheetOccurence[h] += 1, o.sheets[`${h} (${o.sheetOccurence[h]})`] = m.sheet, o;
    },
    {
      sheets: {},
      sheetOccurence: {}
    }
  )) == null ? void 0 : l.sheets, s = `${a == null ? void 0 : a.name} transfer templates (${ze(/* @__PURE__ */ new Date())}).xlsx`, f = be(i);
  return xe(f, s), s;
}
function Ze() {
  const t = ge(), e = oe(), a = Z(), u = H(), i = t.currentBusiness.value, s = we({
    sku: {
      unit: {
        _id: "",
        name: "Unit",
        abbrev: "Unit",
        precision: 0,
        measurements: []
      },
      code: "ING001",
      _id: "",
      name: "Sugar"
    },
    code: "ING001 (override optional)",
    name: "Sugar",
    quantity: {
      amount: 1,
      precision: 0
    },
    quantityStep: {
      amount: 1,
      precision: 0
    },
    minimumQuantity: {
      amount: 1,
      precision: 0
    },
    maximumQuantity: {
      amount: 1,
      precision: 0
    }
  }), f = $e(), l = [
    ["Template ID (leave empty to create new)"],
    ["Template Name", "New template"],
    ["Business name", i == null ? void 0 : i.name],
    ["Business ID", i == null ? void 0 : i._id],
    ["Menu version", i == null ? void 0 : i.menuVersion],
    ["Purchase/Transfer", "Purchase"],
    [
      "Transfer from",
      "Example supplier (supplier_xxx)",
      "Refer to sources list & copy whole cell."
    ],
    [
      "Location codes (leave empty to enable all)",
      "Example outlet (restaurant_xxx)",
      "Example outlet 2 (restaurant_xxx)"
    ],
    ["Reference"],
    ["Remark"],
    [],
    f.map((r) => r.name),
    f.map((r) => s[r.id])
  ], o = f.map((r) => `system:${r.id}`), m = B(l, o), h = B(
    [
      ...e.businessSuppliers.map((r) => [
        `${r.name} (${r._id})`,
        "Purchase",
        r.address.line1,
        r.address.line2,
        r.address.city,
        r.address.postcode,
        r.address.state,
        r.address.country
      ]),
      ...a.locations.map((r) => {
        var x, w, T, p, n, y;
        return [
          `${r.name} (${r.dbName})`,
          "Transfer",
          (x = r.doc.profile.address) == null ? void 0 : x.line1,
          (w = r.doc.profile.address) == null ? void 0 : w.line2,
          (T = r.doc.profile.address) == null ? void 0 : T.city,
          (p = r.doc.profile.address) == null ? void 0 : p.postcode,
          (n = r.doc.profile.address) == null ? void 0 : n.state,
          (y = r.doc.profile.address) == null ? void 0 : y.country
        ];
      })
    ],
    ["Name", "Type", "Line 1", "Line 2", "City", "Postal", "State", "Country"]
  ), d = B(
    a.locations.map((r) => {
      var x, w, T, p, n, y;
      return [
        `${r.name} (${r.dbName})`,
        (x = r.doc.profile.address) == null ? void 0 : x.line1,
        (w = r.doc.profile.address) == null ? void 0 : w.line2,
        (T = r.doc.profile.address) == null ? void 0 : T.city,
        (p = r.doc.profile.address) == null ? void 0 : p.postcode,
        (n = r.doc.profile.address) == null ? void 0 : n.state,
        (y = r.doc.profile.address) == null ? void 0 : y.country
      ];
    }),
    ["Name", "Line 1", "Line 2", "City", "Postal", "State", "Country"]
  ), c = B(
    u.skus.map((r) => [
      r.code,
      r.name,
      r.unit.abbrev,
      ...r.unit.measurements.map((x) => x.abbrev)
    ]),
    ["Code", "Name", "Base unit", "Measurements"]
  ), v = be({
    Template: m,
    Source: h,
    Destination: d,
    Ingredient: c
  }), b = `${i == null ? void 0 : i.name} transfer templates import.xlsx`;
  return xe(v, b), b;
}
function Je(t, e) {
  const a = new Array(), u = /(.*) \(((supplier_|warehouse_|restaurant_).{24,})\)/, s = Z().locationByDbName, l = oe().supplierById, o = t.trim(), m = u.exec(o);
  if (!m)
    return a.push(`Transfer from location value of ${o} cannot be read.`), {
      errors: a
    };
  const h = m[1], d = m[2];
  let c;
  if (d.startsWith("supplier"))
    c = l[d], e !== A.enum.purchase && a.push(`Expected transfer type Purchase but found ${e} instead.`);
  else {
    const v = s[d];
    if (!v)
      return a.push(`Location (${h}) of id ${d} is not found.`), {
        errors: a
      };
    h !== v.name && a.push(
      `Location id ${d} has non-matching name. Found ${h} but expected ${v.name}`
    ), c = {
      _id: v.doc._id,
      name: v.name,
      address: v.doc.profile.address ?? {
        line1: "",
        state: "",
        country: "",
        city: "",
        postcode: "",
        coordinates: [0, 0]
      },
      internal: d.split("_")[0] === "restaurant" ? ce.enum.restaurant : ce.enum.warehouse,
      phoneNumber: v.doc.profile.phoneNo ?? "",
      email: v.doc.profile.email ?? "",
      _rev: "",
      contactName: v.doc.profile.name ?? "",
      registrationNumber: v.doc.profile.regNo ?? ""
    };
  }
  return {
    from: c,
    errors: a
  };
}
function Xe(t) {
  if (!t.length || `${t[0]}`.toLocaleLowerCase() === "all")
    return [];
  const e = /(.*) \(((warehouse_|restaurant_).{24,})\)/, u = Z().locationByDbName;
  return t.map((i) => {
    const s = new Array(), f = i.trim(), l = e.exec(f);
    if (!l)
      return s.push(`Enabled location value of ${f} cannot be read.`), {
        errors: s
      };
    const o = l[1], m = l[2], h = u[m];
    return h ? (o !== h.name && s.push(
      `Location id ${m} has non-matching name. Found ${o} but expected ${h.name}`
    ), {
      errors: s,
      location: h
    }) : (s.push(`Location (${o}) of id ${m} is not found.`), {
      errors: s
    });
  });
}
function et(t) {
  const [
    e,
    a,
    u,
    i,
    s,
    f,
    l,
    o,
    m,
    h,
    d
  ] = Te(t);
  return {
    id: `${a[1] ?? ""}`.trim(),
    name: `${u[1] ?? ""}`.trim(),
    type: `${l[1] ?? ""}`.trim().toLocaleLowerCase() === "transfer" ? A.enum.transfer : A.enum.purchase,
    transferFrom: `${o[1] ?? ""}`.trim(),
    locations: m.slice(1).map((c) => `${c}`.trim()).filter((c) => c),
    reference: `${h[1] ?? ""}`.trim(),
    remark: `${d[1] ?? ""}`.trim()
  };
}
function tt(t) {
  const [
    e,
    a,
    u,
    i,
    s,
    f,
    l,
    o,
    m,
    h,
    d,
    c,
    v,
    ...b
  ] = Te(t);
  if (!e || !e.length || e.some((p) => p.length && !p.startsWith("system:")))
    throw new Error("Missing meta header. Excel file does not come from the template.");
  const r = e.map((p) => p.split(":")[1]), w = [
    "code",
    "name",
    "unit",
    "defaultQuantity",
    "minimumQuantity",
    "maximumQuantity",
    "quantityStep"
  ].filter((p) => !r.includes(p));
  if (w.length)
    throw new Error(
      `Missing meta headers (${w.join()}). Excel file does not come from the template.`
    );
  return b.map((p, n) => {
    const y = {};
    for (const S in r) {
      const $ = r[S];
      Object.assign(y, { [$]: p[S] });
    }
    return {
      index: n,
      data: y
    };
  });
}
function rt(t, e, a) {
  const u = t === "" ? null : G(t, a), i = e === "" ? null : G(e, a), s = u && i && u.amount > i.amount;
  return {
    min: u,
    max: i,
    compareError: s ? "Minimum amount must be less than or equal to maximum amount" : void 0
  };
}
function nt(t, e, a) {
  const u = H(), i = ae(), s = u.skuByCode[t.code], f = new Array();
  if (!s)
    return f.push(`Cannot find ingredient with code (${t.code}) ${t.name}.`), {
      index: e,
      errors: f
    };
  if (a.filter((p) => p.data.code === t.code).length > 1)
    return f.push(`Ingredient ${t.code} is defined twice.`), {
      index: e,
      errors: f
    };
  const l = s.unit, o = l == null ? void 0 : l.measurements.find((p) => p.abbrev === t.unit);
  if (l.abbrev !== t.unit && !o) {
    const p = `Cannot find unit measurement of symbol ${t.unit || "[empty]"} for ingredient (${t.code}) ${t.name}.`;
    f.push(p);
    const n = {
      sku: s,
      code: t.overrideCode || s.code,
      name: s.name,
      measurement: o,
      quantity: { amount: 0, precision: 0 },
      quantityStep: { amount: 0, precision: 0 },
      minimumQuantity: { amount: 0, precision: 0 },
      maximumQuantity: { amount: 0, precision: 0 }
    };
    if (i.isEnabled) {
      const y = i.getItemCustomCode(s);
      y && (n.code = y);
    }
    return {
      index: e,
      errors: f,
      templateItem: n
    };
  }
  const m = G(
    t.quantityStep,
    J(l, o)
  );
  (Number.isNaN(Number(t.quantityStep)) || Number(t.quantityStep) <= 0) && f.push("Amount step must be more than 0");
  const h = Ye(m), d = rt(
    t.minimumQuantity,
    t.maximumQuantity,
    J(l, o)
  ), c = d.min, v = d.max;
  d.compareError && f.push(d.compareError);
  const b = Ke(+t.minimumQuantity, +t.maximumQuantity), r = G(
    t.defaultQuantity,
    J(l, o)
  ), x = h(r);
  typeof x == "string" && f.push(`Default amount: ${x}`);
  const w = d.min && d.max ? b(`${t.defaultQuantity}`) : null;
  typeof w == "string" && f.push(`Default amount: ${w}`);
  const T = {
    sku: s,
    code: t.overrideCode || s.code,
    name: t.name || s.name,
    measurement: o,
    quantity: r,
    quantityStep: m,
    minimumQuantity: c,
    maximumQuantity: v
  };
  return {
    index: e,
    errors: f,
    templateItem: T
  };
}
function ot(t) {
  const e = t.SheetNames.filter(
    (s) => !Object.values(se).map(String).includes(s)
  ), u = _e().templates, i = Me(u, "_id");
  try {
    return e.reduce(
      (s, f) => {
        var p;
        const l = new Array(), o = t.Sheets[f], m = et(o), h = Je(m.transferFrom, m.type);
        l.push(...h.errors);
        const d = h.from, c = Xe(m.locations), v = c.filter((n) => n.location).map((n) => n.location);
        l.push(...c.flatMap((n) => n.errors));
        const b = tt(o).filter((n) => n.data.code), r = b.map(
          (n, y) => nt(n.data, y, b)
        );
        l.push(
          ...r.flatMap(
            (n) => n.errors.map((y) => `(Excel row ${n.index + 14}) ${y}`)
          )
        );
        const x = r.filter((n) => n.templateItem).map((n) => n.templateItem);
        if (m.id) {
          const n = i[m.id];
          if (!n) {
            const S = {
              _id: m.id,
              _rev: "",
              name: m.name || `(unnamed from sheet ${f || "<unnamed sheet>"})`,
              purchaseOrder: at()
            };
            return l.push(`Template ID ${m.id} is not found.`), s.importUpdateResult.push({
              type: "update",
              original: S,
              template: S,
              excelSheetName: f,
              errors: l
            }), s;
          }
          const y = {
            type: "update",
            original: n,
            template: {
              ...n,
              name: m.name,
              locations: v.length ? v : null,
              purchaseOrder: {
                ...n.purchaseOrder,
                supplier: d ?? ((p = n.purchaseOrder) == null ? void 0 : p.supplier),
                ref: m.reference,
                remark: m.remark,
                items: x
              }
            },
            excelSheetName: f,
            errors: l
          };
          return s.importUpdateResult.push(y), s;
        }
        const T = {
          type: "create",
          template: {
            name: m.name,
            locations: v.length ? v : null,
            purchaseOrder: {
              supplier: d ?? Ce(),
              ref: m.reference,
              remark: m.remark,
              items: x
            }
          },
          excelSheetName: f,
          errors: l
        };
        return s.importCreateResult.push(T), s;
      },
      {
        invalidExcel: !1,
        importCreateResult: new Array(),
        importUpdateResult: new Array()
      }
    );
  } catch (s) {
    return {
      invalidExcel: !0,
      invalidExcelMessage: (s == null ? void 0 : s.message) ?? "Invalid excel",
      importCreateResult: [],
      importUpdateResult: []
    };
  }
}
function Ce() {
  return {
    _id: "",
    name: "",
    address: {
      line2: void 0,
      line1: "",
      state: "",
      city: "",
      postcode: "",
      country: ""
    }
  };
}
function at() {
  return {
    remark: void 0,
    ref: void 0,
    items: [],
    supplier: Ce()
  };
}
const st = { class: "flex items-center gap-12 pl-8" }, it = { class: "flex flex-col" }, lt = { class: "fm-typo-en-body-md-400 text-fm-color-typo-primary flex items-center gap-4" }, mt = { class: "text-fm-color-typo-secondary fm-typo-en-body-md-400" }, ct = {
  key: 0,
  class: "text-fm-color-typo-secondary fm-typo-en-body-sm-400"
}, ut = { key: 0 }, fe = /* @__PURE__ */ te({
  __name: "TransferTemplateImportItem",
  props: {
    type: {},
    name: {},
    transferType: {},
    locations: {},
    items: {},
    errors: {}
  },
  setup(t) {
    return (e, a) => {
      var s, f, l;
      const u = U("FmIcon"), i = U("FmTooltip");
      return _(), k("div", st, [
        a[0] || (a[0] = C("div", null, "•", -1)),
        C("div", it, [
          C("div", lt, [
            C("div", {
              class: V({
                "text-fm-color-system-error-300": e.errors.length
              })
            }, [
              Ne(N(e.name) + " ", 1),
              C("span", mt, " (" + N(O(Le)(`${e.transferType}`)) + ") ", 1),
              e.type === "create" ? (_(), k("span", ct, "(new)")) : q("", !0)
            ], 2),
            e.errors.length ? (_(), k("div", ut, [
              P(i, { "z-index": 50 }, {
                content: ee(() => [
                  C("ol", null, [
                    (_(!0), k(L, null, W(e.errors, (o, m) => (_(), k("li", { key: m }, N(o), 1))), 128))
                  ])
                ]),
                default: ee(() => [
                  P(u, {
                    name: "error",
                    size: "sm",
                    color: "system-error-300"
                  })
                ]),
                _: 1
              })
            ])) : q("", !0)
          ]),
          C("div", {
            class: V([
              "fm-typo-en-body-sm-400",
              {
                "text-fm-color-system-error-200": e.errors.length,
                "text-fm-color-typo-secondary": !e.errors.length
              }
            ])
          }, N((s = e.locations) != null && s.length ? `${(f = e.locations) == null ? void 0 : f.length} locations` : "All locations") + ", " + N(`${(l = e.items) == null ? void 0 : l.length} items`), 3)
        ])
      ]);
    };
  }
}), dt = { class: "flex flex-col gap-24" }, pt = {
  key: 0,
  class: "flex items-center gap-8"
}, ft = { class: "flex flex-col gap-8" }, yt = { class: "line-clamp-2 text-ellipsis break-all" }, ht = {
  key: 2,
  class: "shrink-0"
}, vt = {
  key: 0,
  class: "flex flex-col"
}, gt = { class: "text-fm-color-system-error-300 fm-typo-en-body-sm-400" }, bt = {
  key: 0,
  class: "max-h-[200px] overflow-y-auto flex flex-col gap-8"
}, xt = { class: "fm-typo-en-body-lg-600" }, Tt = /* @__PURE__ */ te({
  __name: "TransferTemplateImport",
  setup(t) {
    const e = E(null), a = Ae(), u = ye(), i = E(!1), s = E(!1), f = oe();
    Re(async () => {
      s.value = !0;
      try {
        await f.readSuppliers().delayed(1e3);
      } catch {
        u.open({
          title: "Something went wrong.",
          message: "Error at reading suppliers list. Please try again.",
          type: "error"
        });
      } finally {
        s.value = !1;
      }
    });
    const l = E(new Array()), o = E([]), m = E([]), h = me(
      () => !!l.value.length || o.value.some((b) => b.errors.length) || m.value.some((b) => b.errors.length)
    ), d = me(
      () => !!o.value.length || !!m.value.length
    ), { t: c } = ne();
    async function v(b) {
      l.value = [], o.value = [], m.value = [];
      try {
        i.value = !0;
        const [r] = await Promise.all([
          qe(b),
          // fake buffer
          new Promise((p) => setTimeout(p, 1e3))
        ]);
        if (!r.SheetNames.filter(
          (p) => !Object.values(se).map(String).includes(p)
        ).find((p) => p)) {
          l.value.push(c("inventory.ingredient.import.fileError.noSheet"));
          return;
        }
        const T = ot(r);
        if (T.invalidExcel) {
          l.value.push(
            T.invalidExcelMessage ?? c("inventory.ingredient.import.fileError.invalidExcel")
          );
          return;
        }
        if (o.value = T.importCreateResult, m.value = T.importUpdateResult, !o.value.length && !m.value.length) {
          l.value.push(c("inventory.ingredient.import.fileError.noData"));
          return;
        }
        a.emitData(T);
      } catch (r) {
        u.open({
          title: c("inventory.ingredient.import.fileError.unableToRead"),
          message: r == null ? void 0 : r.message,
          type: "error"
        }), console.error("Error in reading file", r);
      } finally {
        l.value.length && u.open({
          title: c("inventory.ingredient.import.fileError.invalidExcel"),
          type: "error"
        }), i.value = !1;
      }
    }
    return Fe(e, (b) => {
      b && v(b);
    }), (b, r) => {
      const x = U("FmCircularProgress"), w = U("FmIcon"), T = U("FmButton");
      return _(), k("div", dt, [
        r[2] || (r[2] = C("div", { class: "fm-typo-en-body-md-400" }, "Import transfer templates from excel sheets.", -1)),
        s.value ? (_(), k("div", pt, [
          C("div", null, [
            P(x, {
              size: "md",
              color: "neutral-gray-200"
            })
          ]),
          r[1] || (r[1] = C("div", { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, "Loading...", -1))
        ])) : (_(), k(L, { key: 1 }, [
          P(He, {
            class: V({
              "w-full": !0,
              "h-[200px]": !e.value
            }),
            accept: ".xlsx",
            onFileUpload: r[0] || (r[0] = (p) => e.value = p),
            label: O(c)("inventory.ingredient.import.uploadTemplate"),
            "button-label": O(c)("inventory.ingredient.import.selectFile")
          }, Pe({ _: 2 }, [
            e.value ? {
              name: "default",
              fn: ee(({ openFileDialog: p }) => [
                C("div", ft, [
                  C("div", {
                    class: V([
                      "fm-corner-radius-md p-16 flex items-center gap-16",
                      {
                        "border border-fm-color-neutral-gray-100": i.value,
                        "border border-fm-color-neutral-gray-200": !i.value && !h.value,
                        "border border-fm-color-system-error-200": h.value
                      }
                    ])
                  }, [
                    i.value ? (_(), z(x, {
                      key: 0,
                      size: "md",
                      color: "neutral-gray-200"
                    })) : (_(), z(w, {
                      key: 1,
                      name: h.value ? "error" : "attach_file",
                      outline: "",
                      color: h.value ? "system-error-300" : void 0
                    }, null, 8, ["name", "color"])),
                    C("div", {
                      class: V([
                        "fm-typo-en-body-md-400 flex-1 h-[36px] flex items-center",
                        {
                          "text-fm-color-typo-disabled": i.value,
                          "text-fm-color-typo-primary": !i.value
                        }
                      ])
                    }, [
                      C("div", yt, N(e.value.name), 1)
                    ], 2),
                    i.value ? q("", !0) : (_(), k("div", ht, [
                      P(T, {
                        label: O(c)("inventory.ingredient.import.replaceFile"),
                        variant: h.value ? "destructive" : "secondary",
                        "prepend-icon": h.value ? void 0 : "autorenew",
                        onClick: p
                      }, null, 8, ["label", "variant", "prepend-icon", "onClick"])
                    ]))
                  ], 2),
                  l.value.length ? (_(), k("div", vt, [
                    (_(!0), k(L, null, W(l.value, (n, y) => (_(), k("div", {
                      key: y,
                      class: "flex gap-8 items-center"
                    }, [
                      P(w, {
                        name: "error",
                        size: "sm",
                        color: "system-error-300"
                      }),
                      C("div", gt, N(n), 1)
                    ]))), 128))
                  ])) : q("", !0)
                ])
              ]),
              key: "0"
            } : void 0
          ]), 1032, ["class", "label", "button-label"]),
          d.value ? (_(), k("div", bt, [
            C("div", xt, N(O(c)("inventory.ingredient.import.summary")), 1),
            (_(!0), k(L, null, W(o.value, (p, n) => (_(), z(fe, {
              key: n,
              name: p.template.name,
              "transfer-type": typeof p.template.purchaseOrder.supplier.internal == "string" ? O(A).enum.transfer : O(A).enum.purchase,
              locations: p.template.locations,
              items: p.template.purchaseOrder.items,
              errors: p.errors,
              type: "create"
            }, null, 8, ["name", "transfer-type", "locations", "items", "errors"]))), 128)),
            (_(!0), k(L, null, W(m.value, (p) => (_(), z(fe, {
              key: p.template._id,
              name: p.template.name,
              "transfer-type": typeof p.template.purchaseOrder.supplier.internal == "string" ? O(A).enum.transfer : O(A).enum.purchase,
              locations: p.template.locations,
              items: p.template.purchaseOrder.items,
              errors: p.errors,
              type: "update"
            }, null, 8, ["name", "transfer-type", "locations", "items", "errors"]))), 128))
          ])) : q("", !0)
        ], 64))
      ]);
    };
  }
});
function St(t) {
  var s, f;
  const e = ae();
  if (!e.isEnabled) return !0;
  if (!t.internal) {
    const l = e.getNetSuiteVendor(t._id), o = l == null ? void 0 : l.subsidiaryId, m = (s = e.currentVendorSubsidiary(t._id)) == null ? void 0 : s.id;
    return o && o == m;
  }
  const a = e.getNetSuiteLocation(`${t.internal}_${t._id}`), u = e.getLocationSubsidiary(a == null ? void 0 : a.netSuiteId).id, i = (f = e.currentLocationSubsidiary()) == null ? void 0 : f.id;
  return u && u == i;
}
const _t = he("transferTemplateActions", () => {
  const t = De(), e = ye(), a = Z(), u = _e(), i = We(), s = ve(), f = ae(), l = Be(), { t: o } = ne(), m = E({});
  function h() {
    m.value = {
      mode: le.CREATE,
      show: !0,
      "onUpdate:show"(n) {
        m.value.show = n;
      }
    };
  }
  function d(n) {
    m.value = {
      mode: le.UPDATE,
      modelValue: n,
      show: !0,
      "onUpdate:show"(y) {
        m.value.show = y;
      }
    };
  }
  function c(n, y, S) {
    t.open({
      title: `Confirm deleting template ${n.name}?`,
      message: "Deleted template can no longer be retrieved",
      primaryActions: {
        text: "Delete",
        variant: j.Destructive,
        close: !0
      },
      secondaryActions: {
        text: "Cancel",
        variant: j.Plain,
        close: !0
      }
    }).onPrimary(async () => {
      e.open({
        title: `Deleting ${n.name}`,
        type: "info"
      });
      try {
        y.value = !0;
        const [$] = await Promise.allSettled([
          s.deleteTemplate(n),
          new Promise((I) => setTimeout(I, 1e3))
        ]);
        if ($.status === "rejected") throw $.reason;
        e.open({
          title: `Deleted ${n.name}`,
          type: "success"
        });
      } catch ($) {
        e.open({
          title: `Unable to delete ${n.name}`,
          message: `See error from server: ${$}`,
          type: "error"
        }), console.error("error on deleting purchase order template", $);
      } finally {
        y.value = !1, S();
      }
    });
  }
  function v(n, y, S) {
    let $;
    t.open({
      title: `Confirm duplicating template "${n.name}"?`,
      message: "Duplicated template can be edited and used independently",
      primaryActions: {
        text: "Duplicate",
        variant: j.Destructive,
        close: !0
      },
      secondaryActions: {
        text: "Cancel",
        variant: j.Plain,
        close: !0
      },
      contentComponent: te({
        props: ["modelValue"],
        emits: ["update:modelValue"],
        setup(I) {
          return () => K(X.FmTextField, {
            modelValue: I.modelValue,
            "onUpdate:modelValue": (g) => $ = g,
            label: "New Template Name",
            size: "md",
            variant: "primary"
          });
        }
      })
    }).onPrimary(async () => {
      e.open({
        title: `Duplicating ${n.name}`,
        type: "info"
      });
      try {
        y.value = !0;
        const [I] = await Promise.allSettled([
          i.duplicatePurchaseOrderTemplate(n._id, $),
          new Promise((g) => setTimeout(g, 1e3))
        ]);
        if (I.status === "rejected") throw I.reason;
        e.open({
          title: `Duplicated ${n.name}`,
          type: "success"
        });
      } catch (I) {
        e.open({
          title: `Unable to duplicate ${n.name}`,
          message: `See error from server: ${I}`,
          type: "error"
        }), console.error("error on duplicating purchase order template", I);
      } finally {
        y.value = !1, S();
      }
    });
  }
  const b = E({});
  function r(n) {
    b.value = {
      template: n,
      show: !0,
      "onUpdate:show"(y) {
        b.value.show = y;
      },
      "onAction:edit"() {
        b.value.show = !1, d(re(n));
      }
    };
  }
  function x() {
    const { promise: n, resolve: y } = Promise.withResolvers(), S = (g) => {
      y(g);
    }, $ = u.templates.filter((g) => {
      var R, F;
      return ((R = g.purchaseOrder.supplier) == null ? void 0 : R._id) === a.currentLocation.doc._id ? !1 : (F = g.locations) != null && F.length ? g.locations.find((M) => M.doc._id === a.currentLocation.doc._id) : !0;
    });
    if (!$.length)
      return t.open({
        title: "Select one template",
        message: "There is no available template in your business. Configure a new template?",
        primaryActions: {
          text: "Go to templates",
          close: !0
        },
        secondaryActions: {
          text: "Close",
          close: !0
        }
      }).onPrimary(() => {
        l.push({ name: ue.TRANSFER_TEMPLATE }), S(void 0);
      }).onSecondary(() => S(void 0)).onClose(() => S(void 0)), n;
    const I = $.map((g) => {
      var ie;
      const R = !g.purchaseOrder.items.length || g.purchaseOrder.items.some(Se), F = !St(g.purchaseOrder.supplier), M = g.purchaseOrder.supplier.internal ? f.getNetSuiteLocation(
        `${g.purchaseOrder.supplier.internal}_${g.purchaseOrder.supplier._id}`
      ) : f.getNetSuiteVendor(g.purchaseOrder.supplier._id), ke = F ? `The subsidiary of the request
        location is ${(ie = f.getLocationSubsidiary(M == null ? void 0 : M.netSuiteId)) == null ? void 0 : ie.fullName}.` : void 0, Ie = R || F, Ee = R ? "This template is invalid. Update this template." : F ? ke : void 0, Oe = `${g.purchaseOrder.supplier.internal ? "Transfer" : "Purchase"} from ${g.purchaseOrder.supplier.name}`;
      return {
        label: g.name,
        value: g._id,
        disabled: Ie,
        sublabel: Ee ?? Oe
      };
    });
    return I.sort((g, R) => +!!g.disabled - +!!R.disabled), t.open({
      title: "Select one template",
      contentComponent: Qe,
      contentComponentProps: {
        items: I,
        singleSelect: !0
      },
      primaryActions: {
        text: "Confirm",
        close: !0
      },
      secondaryActions: {
        text: "Close",
        close: !0
      },
      tertiaryActions: {
        text: "Templates",
        close: !0
      }
    }).onPrimary((g) => Array.isArray(g) ? S(g[0]) : null).onSecondary(() => S(void 0)).onTertiary(() => {
      l.push({ name: ue.TRANSFER_TEMPLATE }), S(void 0);
    }).onClose(() => S(void 0)), n;
  }
  function w() {
    t.open({
      title: o("inventory.ingredient.import.title"),
      contentComponent: Tt,
      overlay: !0,
      closeButton: !0,
      primaryActions: {
        text: o("common.import"),
        close: !1
      },
      secondaryActions: {
        text: o("common.close"),
        close: !0
      },
      tertiaryActions: {
        text: o("inventory.ingredient.import.actions.downloadTemplate"),
        close: !1,
        variant: "plain"
      }
    }).onPrimary((n) => {
      if (!n) {
        e.open({
          title: o("inventory.ingredient.import.error.noData"),
          type: "error"
        });
        return;
      }
      if (!n.importCreateResult.length && !n.importUpdateResult.length) {
        e.open({
          title: o("inventory.ingredient.import.error.invalidContent"),
          message: o("inventory.ingredient.import.error.noImportData"),
          type: "error"
        });
        return;
      }
      if (n.importCreateResult.some((y) => y.errors.length) || n.importUpdateResult.some((y) => y.errors.length)) {
        e.open({
          title: o("inventory.ingredient.import.error.invalidContent"),
          message: o("inventory.ingredient.import.error.hasErrors"),
          type: "error"
        });
        return;
      }
      t.close(), T(n);
    }).onTertiary(Ze);
  }
  async function T(n) {
    try {
      const y = [
        ...n.importCreateResult.map(
          (g) => g.template
        ),
        ...n.importUpdateResult.map(
          (g) => g.template
        )
      ], S = 100;
      let $ = 0;
      const I = () => {
        $ += S, e.open({
          title: o("inventory.ingredient.import.progress", [
            Math.min($, y.length),
            y.length
          ])
        });
      };
      for (const g of y.chunk(100))
        I(), await s.importTemplates(g);
      e.open({
        title: o("inventory.ingredient.import.success"),
        type: "success"
      });
    } catch (y) {
      e.open({
        title: o("inventory.ingredient.import.error.failed"),
        message: o("inventory.ingredient.import.error.systemMessage", [y == null ? void 0 : y.message]),
        type: "error"
      }), console.error("Error in importing skus", n, y);
    } finally {
      u.fetchTemplates();
    }
  }
  function p() {
    const n = Ge(u.templates);
    e.open({
      title: o("inventory.ingredient.export.success"),
      message: o("inventory.ingredient.export.filename", [n]),
      type: "success"
    });
  }
  return {
    createTemplate: h,
    viewTemplate: r,
    updateTemplate: d,
    deleteTemplate: c,
    duplicateTemplate: v,
    getTemplateId: x,
    importTemplates: w,
    exportTemplates: p,
    templateDialogProps: m,
    templateDetailsProps: b
  };
});
function jt(t, e, a) {
  const u = (a == null ? void 0 : a.abbrev) ?? e.abbrev;
  return `${Q(t, !1)} ${u}`;
}
export {
  _e as a,
  jt as f,
  Se as t,
  _t as u
};
